From c0129d5f12f6d0efacf049082fb66beda1d7bbfb Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Wed, 11 Nov 2026 13:28:14 +0100 Subject: [PATCH 01/55] feat(parser): add registered block macro sessions and target queries Recognize opt-in block macros with the shared attribute parser and run fresh processors after document acceptance. Retain source-position attributes, deferred requests, typed queries, and collision-free target IDs. Reject pending nodes at finalization and checked ASG export. Keep ordinary parser entry points and inactive behavior unchanged. Callbacks cannot affect later includes or conditionals. Validation: 12,405 workspace tests and 117 doctests passed; strict Clippy, formatting, feature-off parser/HTML checks, and whitespace checks passed. 1 workspace test skipped; 5 doctests ignored. Refs: SC-256 --- ARCHITECTURE.adoc | 18 + acdc-cli/src/subcommands/inspect.rs | 2 +- acdc-editor-wasm/src/ast_highlight.rs | 2 +- acdc-mcp/src/render.rs | 2 +- acdc-parser/CHANGELOG.md | 8 + acdc-parser/README.adoc | 20 + acdc-parser/README.md | 19 + .../extensions/extension-query-top.adoc | 3 + .../includes/extensions/extension-query.adoc | 3 + .../tests/includes/extensions/extensions.adoc | 5 + .../extensions/extensions_queries.adoc | 57 +++ .../extensions/extensions_registered.adoc | 52 +++ .../schemas/asg/support-inventory.json | 13 + acdc-parser/src/asg/diagnostics.rs | 1 + acdc-parser/src/asg/projection.rs | 1 + acdc-parser/src/ast/attributes.rs | 14 +- acdc-parser/src/ast/blocks.rs | 9 + acdc-parser/src/ast/content_fields.rs | 1 + acdc-parser/src/ast/identity.rs | 1 + acdc-parser/src/ast/traversal.rs | 1 + acdc-parser/src/error.rs | 9 +- acdc-parser/src/extensions/block_macro.rs | 147 ++++++ acdc-parser/src/extensions/deferred.rs | 60 +++ acdc-parser/src/extensions/finalization.rs | 129 ++++++ acdc-parser/src/extensions/mod.rs | 75 ++++ acdc-parser/src/extensions/query.rs | 392 ++++++++++++++++ acdc-parser/src/extensions/recognition.rs | 92 ++++ acdc-parser/src/extensions/registry.rs | 177 ++++++++ acdc-parser/src/extensions/session.rs | 257 +++++++++++ acdc-parser/src/extensions/target.rs | 154 +++++++ acdc-parser/src/extensions/tests/mod.rs | 374 +++++++++++++++ acdc-parser/src/extensions/tests/queries.rs | 425 ++++++++++++++++++ acdc-parser/src/extensions/tests/support.rs | 50 +++ acdc-parser/src/extensions/traversal.rs | 219 +++++++++ acdc-parser/src/grammar/attributes.rs | 26 +- acdc-parser/src/grammar/document/peg.rs | 30 ++ .../src/grammar/document/references.rs | 1 + acdc-parser/src/grammar/location_walk.rs | 4 + acdc-parser/src/grammar/mod.rs | 2 +- acdc-parser/src/grammar/reference_walk.rs | 1 + acdc-parser/src/grammar/state.rs | 4 +- acdc-parser/src/lib.rs | 46 +- acdc-parser/src/model/caption.rs | 3 + acdc-parser/src/model/mod.rs | 7 + acdc-parser/src/model/section.rs | 23 + acdc-parser/src/options.rs | 5 + acdc-parser/src/parsed.rs | 31 +- acdc-parser/src/proptests/invariants.rs | 2 + acdc-parser/src/reference_repair.rs | 31 +- acdc-parser/tests/extensions.rs | 83 ++++ converters/html/src/delimited.rs | 2 +- converters/html/src/html_visitor.rs | 2 +- converters/manpage/src/manpage_visitor.rs | 2 +- converters/markdown/src/markdown_visitor.rs | 2 +- converters/pdf/src/visitor.rs | 2 +- converters/terminal/src/terminal_visitor.rs | 2 +- 56 files changed, 3071 insertions(+), 32 deletions(-) create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extension-query-top.adoc create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extension-query.adoc create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extensions.adoc create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extensions_queries.adoc create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extensions_registered.adoc create mode 100644 acdc-parser/src/extensions/block_macro.rs create mode 100644 acdc-parser/src/extensions/deferred.rs create mode 100644 acdc-parser/src/extensions/finalization.rs create mode 100644 acdc-parser/src/extensions/mod.rs create mode 100644 acdc-parser/src/extensions/query.rs create mode 100644 acdc-parser/src/extensions/recognition.rs create mode 100644 acdc-parser/src/extensions/registry.rs create mode 100644 acdc-parser/src/extensions/session.rs create mode 100644 acdc-parser/src/extensions/target.rs create mode 100644 acdc-parser/src/extensions/tests/mod.rs create mode 100644 acdc-parser/src/extensions/tests/queries.rs create mode 100644 acdc-parser/src/extensions/tests/support.rs create mode 100644 acdc-parser/src/extensions/traversal.rs create mode 100644 acdc-parser/tests/extensions.rs diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc index 9ba388867..fcb59e3eb 100644 --- a/ARCHITECTURE.adoc +++ b/ARCHITECTURE.adoc @@ -86,6 +86,24 @@ The preprocessed text gets transformed into an Abstract Syntax Tree (AST). The primary PEG grammar lives in `grammar/document/peg.rs` using the `peg::parser!` macro. It handles document structure (header, sections, blocks), block-level elements (paragraphs, lists, tables, delimited blocks), attributes and metadata, and all the nesting rules. +==== Registered extensions + +The parser owns an optional registry of block-macro descriptors and factories. +Recognition records invocations and their source-position attributes without +calling extension code. Once the complete document is accepted, the host runs +macros once in document order, then repairs prepared captions and catalogs. + +Queries return the same typed views as ordinary parser consumers, plus stable +handles for ID assignment. Reference and footnote repair reuse the shared prepared +content services. The host allocates generated literal text without reparsing it +or storing backend markup. + +The working session retains deferred requests and document-local processors. +Its checked `finish()` operation rejects unresolved requests and returns the +ordinary `ParseResult` for conversion. Registrations are explicit, and an empty +registry retains the ordinary parsing path. Callbacks cannot change source +processing, includes, or conditionals. + ==== Inline preprocessing Inline content needs special handling, as specified in https://gitlab.eclipse.org/eclipse/asciidoc-lang/asciidoc-lang/-/blob/main/spec/sdrs/sdr-005-formal-grammar-for-inline-syntax.adoc[SDR-005: Formal Grammar for Inline Syntax]. diff --git a/acdc-cli/src/subcommands/inspect.rs b/acdc-cli/src/subcommands/inspect.rs index b4e967d20..73b5d4e35 100644 --- a/acdc-cli/src/subcommands/inspect.rs +++ b/acdc-cli/src/subcommands/inspect.rs @@ -308,7 +308,7 @@ impl<'doc, W: Write> BlockVisitor<'doc> for TreeVisitor { self.print_tree_line("DiscreteHeader", Some(&detail), location) } BlockKind::DocumentAttribute(_) | BlockKind::Comment(_) => Ok(()), - _ => self.print_tree_line("Unknown", None, location), + BlockKind::Extension(_) | _ => self.print_tree_line("Unknown", None, location), } } } diff --git a/acdc-editor-wasm/src/ast_highlight.rs b/acdc-editor-wasm/src/ast_highlight.rs index acc89dad9..236d7463a 100644 --- a/acdc-editor-wasm/src/ast_highlight.rs +++ b/acdc-editor-wasm/src/ast_highlight.rs @@ -147,7 +147,7 @@ fn collect_block_spans(input: &str, block: BlockRef<'_>, spans: &mut Vec) BlockKind::TableOfContents(_) => { push_block_span(input, spans, block.location(), "adoc-macro"); } - _ => {} + BlockKind::Extension(_) | _ => {} } } diff --git a/acdc-mcp/src/render.rs b/acdc-mcp/src/render.rs index fba5e2441..0e4f56f7e 100644 --- a/acdc-mcp/src/render.rs +++ b/acdc-mcp/src/render.rs @@ -294,7 +294,7 @@ pub(super) fn render_block( BlockKind::TableOfContents(_) | BlockKind::DocumentAttribute(_) | BlockKind::Comment(_) => { String::new() } - _ => "[unsupported block]".into(), + BlockKind::Extension(_) | _ => "[unsupported block]".into(), }; if format == Format::Asciidoc { if !title.is_empty() && !matches!(block.kind(), BlockKind::DiscreteHeading(_)) { diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index f3a7527a7..30d70a9ca 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -185,6 +185,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ordered, unordered, and description list items in both compatibility modes, matching Asciidoctor. Only a standalone `+` acts as a list continuation. +- Applications can register block macros with `extensions::Registry`. Each + document has fresh processor state. Typed queries cover nested containers and + discrete headings. Stable target handles support collision-free ID assignment. + Generated paragraphs contain literal text. Call `ExtensionParseResult::finish()` + before conversion or checked ASG export; unresolved requests return a located + error. Callbacks run after parsing and cannot change later includes or + conditionals, unlike source-changing Asciidoctor extensions. + - Faster parsing of paragraphs, mixed ASCII and Unicode text, formatting, inline passthroughs, and duplicated ordinary table cells (`3*|text`) in both compatibility modes, including text expanded from attributes, while diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index c1ef32a03..08aa1fa08 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2052,6 +2052,26 @@ Add new modules to the appropriate suite's `main.rs`. Allocation measurements, tracing tests, fixture support tests, and custom harnesses remain separate targets to preserve their isolation. The fixture runner's case names are unchanged. +[#registered-extensions] +== Registered extensions + +Applications can register block macros with +`extensions::Registry`. Each parse creates fresh processor instances. Callbacks +run once after the document is accepted and cannot change later includes, +conditionals, or parsing. This differs from source-changing Asciidoctor extensions. +Both compatibility modes support registrations. + +Use `query()` to inspect typed block, content, attribute, and caption views. +Document-local `TargetId` handles identify targets independently of their output +IDs. Use `ensure_id()` to preserve existing IDs or assign collision-free IDs +without rerunning macro processors. Generated paragraphs contain literal text +and are not reparsed. + +Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used +for conversion or serialization. It rejects unresolved deferred requests at their +source locations. See the `extensions` module documentation for registration and +processor examples. An empty registry uses the ordinary parser path. + [#parser-fixtures] == Parser fixtures diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 80b10c18a..4c21df371 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1697,6 +1697,25 @@ Add new modules to the appropriate suite's `main.rs`. Allocation measurements, tracing tests, fixture support tests, and custom harnesses remain separate targets to preserve their isolation. The fixture runner's case names are unchanged. +## Registered extensions + +Applications can register block macros with +`extensions::Registry`. Each parse creates fresh processor instances. Callbacks +run once after the document is accepted and cannot change later includes, +conditionals, or parsing. This differs from source-changing Asciidoctor extensions. +Both compatibility modes support registrations. + +Use `query()` to inspect typed block, content, attribute, and caption views. +Document-local `TargetId` handles identify targets independently of their output +IDs. Use `ensure_id()` to preserve existing IDs or assign collision-free IDs +without rerunning macro processors. Generated paragraphs contain literal text +and are not reparsed. + +Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used +for conversion or serialization. It rejects unresolved deferred requests at their +source locations. See the `extensions` module documentation for registration and +processor examples. An empty registry uses the ordinary parser path. + ## Parser fixtures We use two fixture styles, and they are intentionally different. diff --git a/acdc-parser/fixtures/tests/includes/extensions/extension-query-top.adoc b/acdc-parser/fixtures/tests/includes/extensions/extension-query-top.adoc new file mode 100644 index 000000000..286905b60 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extension-query-top.adoc @@ -0,0 +1,3 @@ +== !!! + +See xref:extension-query-top.adoc[]. diff --git a/acdc-parser/fixtures/tests/includes/extensions/extension-query.adoc b/acdc-parser/fixtures/tests/includes/extensions/extension-query.adoc new file mode 100644 index 000000000..b3fe1de01 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extension-query.adoc @@ -0,0 +1,3 @@ +.Included {label} +[.assign] +image::included.svg[] diff --git a/acdc-parser/fixtures/tests/includes/extensions/extensions.adoc b/acdc-parser/fixtures/tests/includes/extensions/extensions.adoc new file mode 100644 index 000000000..e3df9e07c --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extensions.adoc @@ -0,0 +1,5 @@ +:mode: included + +record::included[] + +defer::included-deferred[title="A, B"] diff --git a/acdc-parser/fixtures/tests/includes/extensions/extensions_queries.adoc b/acdc-parser/fixtures/tests/includes/extensions/extensions_queries.adoc new file mode 100644 index 000000000..d7c556401 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extensions_queries.adoc @@ -0,0 +1,57 @@ += Queries +:label: Early +:figure-caption: Picture + +.Original {label} +[#authored.assign] +image::one.svg[] + +== Outer + +.Source *title* +[source,rust,role=assign] +---- +println!("hello"); +---- + +[example] +-- +Inside an open example. +-- + +[listing] +==== +Inside an example delimiter. +==== + +* Item ++ +.Attached +[.assign] +image::attached.svg[] + +Term:: Definition ++ +defer::description[] + +[cols="a,l"] +|=== +|.Cell image +[.assign] +image::cell.svg[] +|Literal cell + +|== Cell section + +defer::cell[] +|Other literal cell +|=== + +:label: Late +:figure-caption: Later picture + +include::extension-query.adoc[] + +=== Inner + +defer::section[] diff --git a/acdc-parser/fixtures/tests/includes/extensions/extensions_registered.adoc b/acdc-parser/fixtures/tests/includes/extensions/extensions_registered.adoc new file mode 100644 index 000000000..deb3c0828 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extensions_registered.adoc @@ -0,0 +1,52 @@ += Registered macros +:mode: first + +record::target[,"quoted, comma",third="a\"b"] + +record::{mode}[named,second=override,third=tail] + +:mode: second + +ifdef::missing[] +record::inactive[] +endif::[] + +unknown::ordinary[] + +\record::escaped[] + +[source] +---- +record::literal[] +---- + +record::attribute-values[first,key=None,empty="",flag,third=] + +.Outer title +[#retained] +record::metadata[] + +See <>. + +== Nested section + +==== +record::example[] + +-- +record::open[] +-- +==== + +* item ++ +record::continuation[] + +[cols="2*a"] +|=== +2*|record::duplicate[] +|=== + +include::extensions.adoc[] + +defer::last[one,,three] diff --git a/acdc-parser/schemas/asg/support-inventory.json b/acdc-parser/schemas/asg/support-inventory.json index 79bf517c3..c4122bb88 100644 --- a/acdc-parser/schemas/asg/support-inventory.json +++ b/acdc-parser/schemas/asg/support-inventory.json @@ -3976,6 +3976,9 @@ "DocumentAttribute": [ "0" ], + "Extension": [ + "0" + ], "Image": [ "0" ], @@ -4074,6 +4077,12 @@ "policy": "no-direct-field-mapping-is-established-for", "upstream": "#/$defs/block" }, + "variant:Extension": { + "policy": "unsupported" + }, + "Extension.0": { + "policy": "unsupported" + }, "variant:Image": { "policy": "candidate", "upstream": "#/$defs/block" @@ -6009,6 +6018,10 @@ "file": "src/asg/projection.rs", "name": "unresolved_macro_and_callout_owners_are_rejected" }, + { + "file": "src/extensions/tests/mod.rs", + "name": "extensions_pending_blocks_are_rejected_by_checked_asg_exports" + }, { "file": "tests/asg/asg_references.rs", "name": "reference_forms_preserve_targets_and_effective_labels" diff --git a/acdc-parser/src/asg/diagnostics.rs b/acdc-parser/src/asg/diagnostics.rs index 1dd9ccee3..b938f4291 100644 --- a/acdc-parser/src/asg/diagnostics.rs +++ b/acdc-parser/src/asg/diagnostics.rs @@ -71,6 +71,7 @@ pub(super) fn inline_construct(value: &InlineNode<'_>) -> &'static str { pub(super) fn block_construct(value: &Block<'_>) -> &'static str { match value { Block::Paragraph(_) => "paragraph", + Block::Extension(_) => "pending extension block", Block::Section(_) => "section", Block::Comment(_) => "comment", Block::TableOfContents(_) => "table of contents", diff --git a/acdc-parser/src/asg/projection.rs b/acdc-parser/src/asg/projection.rs index 3038a3ccf..0dd341578 100644 --- a/acdc-parser/src/asg/projection.rs +++ b/acdc-parser/src/asg/projection.rs @@ -440,6 +440,7 @@ impl<'a, 'doc> Export<'a, 'doc> { fn block(&mut self, value: &'a Block<'doc>, at: &str) -> Result, Error> { let projected = match value { + Block::Extension(_) => return Err(super::unsupported(at, "pending extension block")), Block::Paragraph(paragraph) => self.paragraph(paragraph, at, false)?, Block::Section(section) => self.section(section, at)?, Block::UnorderedList(list) => { diff --git a/acdc-parser/src/ast/attributes.rs b/acdc-parser/src/ast/attributes.rs index ff1277961..7cfdb551d 100644 --- a/acdc-parser/src/ast/attributes.rs +++ b/acdc-parser/src/ast/attributes.rs @@ -55,6 +55,7 @@ pub struct AttributesRef<'doc> { #[derive(Clone, Copy, Debug)] enum Owner<'doc> { + Extension(&'doc crate::extensions::ExtensionBlock<'doc>), Raw(&'doc Raw<'doc>), Bold(&'doc Bold<'doc>), Italic(&'doc Italic<'doc>), @@ -132,6 +133,12 @@ impl Field { } impl<'doc> AttributesRef<'doc> { + pub(super) fn extension(node: &'doc crate::extensions::ExtensionBlock<'doc>) -> Self { + Self { + owner: Owner::Extension(node), + } + } + /// The recorded block-metadata span, if retained. /// /// This is the collection's span, not an individual value's range. @@ -431,6 +438,7 @@ impl<'doc> AttributesRef<'doc> { Substitutions, ], Owner::Header(_) + | Owner::Extension(_) | Owner::Paragraph(_) | Owner::Section(_) | Owner::Delimited(_) @@ -541,6 +549,7 @@ impl<'doc> AttributesRef<'doc> { pub(super) fn metadata(self) -> Option<&'doc BlockMetadata<'doc>> { match self.owner { Owner::Header(node) => Some(&node.metadata), + Owner::Extension(node) => Some(&node.metadata), Owner::Paragraph(node) => Some(&node.metadata), Owner::Section(node) => Some(&node.metadata), Owner::Delimited(node) => Some(&node.metadata), @@ -598,6 +607,7 @@ impl<'doc> AttributesRef<'doc> { pub(super) fn title(self) -> Option> { let title = match self.owner { Owner::Header(node) => &node.title, + Owner::Extension(node) => &node.title, Owner::Paragraph(node) => &node.title, Owner::Section(node) => &node.title, Owner::Delimited(node) => &node.title, @@ -685,7 +695,8 @@ impl<'doc> AttributesRef<'doc> { }), Owner::Header(node) => node.metadata.heading_anchor().map(ElementIdRef::from), Owner::ThematicBreak(node) => node.primary_anchor().map(ElementIdRef::from), - Owner::Paragraph(_) + Owner::Extension(_) + | Owner::Paragraph(_) | Owner::Delimited(_) | Owner::Admonition(_) | Owner::UnorderedList(_) @@ -750,6 +761,7 @@ impl<'doc> AttributesRef<'doc> { Owner::Mailto(node) => TokensRef::new(Some(&node.metadata.roles)), Owner::ThematicBreak(_) => TokensRef::new(None), Owner::Header(_) + | Owner::Extension(_) | Owner::Paragraph(_) | Owner::Section(_) | Owner::Delimited(_) diff --git a/acdc-parser/src/ast/blocks.rs b/acdc-parser/src/ast/blocks.rs index 7bf9dc8e2..03599d87b 100644 --- a/acdc-parser/src/ast/blocks.rs +++ b/acdc-parser/src/ast/blocks.rs @@ -42,6 +42,11 @@ macro_rules! delimited_ref { }; } +node_ref!( + ExtensionRef<'doc>, + crate::extensions::ExtensionBlock<'doc>, + "A pending extension block in a working session." +); node_ref!(DocumentRef<'doc>, Document<'doc>, "A document."); node_ref!(SectionRef<'doc>, Section<'doc>, "A section."); node_ref!(ParagraphRef<'doc>, Paragraph<'doc>, "A paragraph."); @@ -143,6 +148,7 @@ pub struct BlockRef<'doc> { #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub enum BlockKind<'doc> { + Extension(ExtensionRef<'doc>), TableOfContents(TableOfContentsRef<'doc>), Admonition(AdmonitionRef<'doc>), DiscreteHeading(DiscreteHeadingRef<'doc>), @@ -183,6 +189,7 @@ impl<'doc> BlockRef<'doc> { #[must_use] pub fn location(self) -> LocationRef<'doc> { match self.kind { + BlockKind::Extension(node) => node.location(), BlockKind::TableOfContents(node) => node.location(), BlockKind::Admonition(node) => node.location(), BlockKind::DiscreteHeading(node) => node.location(), @@ -429,6 +436,7 @@ impl<'doc> From<&'doc Block<'doc>> for BlockRef<'doc> { Block::DescriptionList(node) => { BlockKind::DescriptionList(DescriptionListRef::new(node)) } + Block::Extension(node) => BlockKind::Extension(ExtensionRef::new(node)), Block::Section(node) => BlockKind::Section(SectionRef::from(node)), Block::Paragraph(node) => BlockKind::Paragraph(ParagraphRef::from(node)), Block::Image(node) => BlockKind::Image(ImageRef::new(node)), @@ -540,6 +548,7 @@ impl<'doc> From> for Block<'doc> { BlockKind::OrderedList(node) => Self::OrderedList(node.node.clone()), BlockKind::CalloutList(node) => Self::CalloutList(node.node.clone()), BlockKind::DescriptionList(node) => Self::DescriptionList(node.node.clone()), + BlockKind::Extension(node) => Self::Extension(Box::new(node.node.clone())), BlockKind::Section(node) => Self::Section(node.node.clone()), BlockKind::Paragraph(node) => Self::Paragraph(node.node.clone()), BlockKind::Image(node) => Self::Image(node.node.clone()), diff --git a/acdc-parser/src/ast/content_fields.rs b/acdc-parser/src/ast/content_fields.rs index 8aeb12543..c2dcc973c 100644 --- a/acdc-parser/src/ast/content_fields.rs +++ b/acdc-parser/src/ast/content_fields.rs @@ -139,6 +139,7 @@ impl<'doc> StructuralRef<'doc> { | BlockKind::Audio(_) | BlockKind::Video(_) | BlockKind::Comment(_) + | BlockKind::Extension(_) | BlockKind::Stem(_) => (Body, None), }; let metadata = block.attributes().and_then(super::AttributesRef::metadata); diff --git a/acdc-parser/src/ast/identity.rs b/acdc-parser/src/ast/identity.rs index 13b8d6dd3..d0822f984 100644 --- a/acdc-parser/src/ast/identity.rs +++ b/acdc-parser/src/ast/identity.rs @@ -58,6 +58,7 @@ impl<'doc> BlockRef<'doc> { #[must_use] pub fn attributes(self) -> Option> { match self.kind() { + BlockKind::Extension(node) => Some(super::AttributesRef::extension(node.node)), BlockKind::Section(node) => Some(node.attributes()), BlockKind::Paragraph(node) => Some(node.attributes()), BlockKind::Admonition(node) => Some(node.attributes()), diff --git a/acdc-parser/src/ast/traversal.rs b/acdc-parser/src/ast/traversal.rs index 61cc98f78..25b9dc594 100644 --- a/acdc-parser/src/ast/traversal.rs +++ b/acdc-parser/src/ast/traversal.rs @@ -107,6 +107,7 @@ impl<'doc> StructuralRef<'doc> { | BlockKind::Literal(_) | BlockKind::Passthrough(_) | BlockKind::Verse(_) + | BlockKind::Extension(_) | BlockKind::Stem(_) => Children::Empty, }, Self::ListItem(item) => Children::Blocks(item.node.blocks.iter()), diff --git a/acdc-parser/src/error.rs b/acdc-parser/src/error.rs index 553fb94ef..1ebe66531 100644 --- a/acdc-parser/src/error.rs +++ b/acdc-parser/src/error.rs @@ -8,6 +8,9 @@ use crate::{ #[non_exhaustive] #[derive(thiserror::Error, Debug)] pub enum Error { + #[error("Extension error: {1}, position: {0}")] + Extension(Box, String), + #[error("Invalid include path: {1}, position: {0}")] InvalidIncludePath(Box, PathBuf), @@ -121,7 +124,8 @@ impl Error { #[must_use] pub fn source_location(&self) -> Option<&SourceLocation> { match self { - Self::NestedSectionLevelMismatch(detail, ..) + Self::Extension(detail, ..) + | Self::NestedSectionLevelMismatch(detail, ..) | Self::MismatchedDelimiters(detail, ..) | Self::InvalidAdmonitionVariant(detail, ..) | Self::Parse(detail, ..) @@ -227,7 +231,8 @@ impl Error { Self::IncludeExpansionTooLarge(..) => Some( "Select less include text with lines=, tag=, or tags=. For trusted input, the caller can raise max_total_include_bytes (CLI: --max-total-include-bytes).", ), - Self::ParseGrammar(_) + Self::Extension(..) + | Self::ParseGrammar(_) | Self::Io(_) | Self::IncludeSource(_) | Self::ParseInt(_) diff --git a/acdc-parser/src/extensions/block_macro.rs b/acdc-parser/src/extensions/block_macro.rs new file mode 100644 index 000000000..b497236df --- /dev/null +++ b/acdc-parser/src/extensions/block_macro.rs @@ -0,0 +1,147 @@ +use std::{borrow::Cow, fmt, sync::Arc}; + +use crate::{DocumentAttributes, ElementAttributes, SourceLocation}; + +/// The parser scope in which a block macro can be recognized. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum MacroContext { + /// Document and section bodies, including `AsciiDoc` table cells. + Document, + /// Bodies of compound blocks such as examples and sidebars. + Compound, +} + +/// Whether a macro requires a target before its attribute list. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum MacroTarget { + #[default] + Optional, + Required, + Empty, +} + +/// Immutable syntax and factory for one block macro. +#[derive(Clone)] +pub struct BlockMacro { + pub(crate) name: String, + pub(crate) contexts: Vec, + pub(crate) target: MacroTarget, + pub(crate) positional: Vec, + pub(crate) defaults: ElementAttributes<'static>, + pub(super) factory: Arc Box + Send + Sync>, +} + +impl fmt::Debug for BlockMacro { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("BlockMacro") + .field("name", &self.name) + .field("contexts", &self.contexts) + .field("target", &self.target) + .field("positional", &self.positional) + .field("defaults", &self.defaults) + .finish_non_exhaustive() + } +} + +impl BlockMacro { + /// Create a macro whose factory runs once per document, in registration order. + /// + /// Factories can share immutable resources. Processors need not be `Send` or + /// `Sync`; each processor belongs to one document session. + pub fn new( + name: impl Into, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Self { + Self { + name: name.into(), + contexts: vec![MacroContext::Document, MacroContext::Compound], + target: MacroTarget::Optional, + positional: Vec::new(), + defaults: ElementAttributes::default(), + factory: Arc::new(move || Box::new(factory())), + } + } + + #[must_use] + pub fn with_contexts(mut self, contexts: impl IntoIterator) -> Self { + self.contexts = contexts.into_iter().collect(); + self + } + + #[must_use] + pub const fn with_target(mut self, target: MacroTarget) -> Self { + self.target = target; + self + } + + /// Map positional arguments to names. Empty slots keep their positions. + /// Named arguments take precedence over positional arguments and defaults. + #[must_use] + pub fn with_positional_attributes( + mut self, + names: impl IntoIterator>, + ) -> Self { + self.positional = names.into_iter().map(Into::into).collect(); + self + } + + #[must_use] + pub fn with_defaults(mut self, defaults: ElementAttributes<'static>) -> Self { + self.defaults = defaults; + self + } +} + +/// Arguments and source-position attributes of one accepted macro invocation. +/// The document attributes are a read-only snapshot at the macro's location. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct MacroInvocation<'a> { + pub name: Cow<'a, str>, + pub target: Cow<'a, str>, + pub positional: Vec>>, + pub attributes: ElementAttributes<'a>, + pub document_attributes: DocumentAttributes<'a>, + pub location: SourceLocation, +} + +/// A processor instance is used only within one document session. +pub trait BlockMacroProcessor { + /// Process an accepted invocation. Returning an error stops the parse. + /// + /// # Errors + /// Return a message describing why this invocation cannot be processed. + fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result; +} + +/// Content produced by a registered block macro. +#[derive(Debug)] +#[non_exhaustive] +pub enum BlockMacroOutput { + /// Emit one plain-text node in a paragraph, preserving the macro's outer + /// title and metadata. The text is not parsed as inline markup. + Paragraph(String), + /// Remove the macro and its block metadata. + None, + /// Retain a placeholder and its arguments for document-level construction. + Deferred, +} + +impl MacroInvocation<'_> { + pub(super) fn to_owned_invocation(&self) -> MacroInvocation<'static> { + MacroInvocation { + name: Cow::Owned(self.name.to_string()), + target: Cow::Owned(self.target.to_string()), + positional: self + .positional + .iter() + .map(|value| value.as_ref().map(|value| Cow::Owned(value.to_string()))) + .collect(), + attributes: self.attributes.clone().into_static(), + document_attributes: self.document_attributes.clone().into_static(), + location: self.location.clone(), + } + } +} diff --git a/acdc-parser/src/extensions/deferred.rs b/acdc-parser/src/extensions/deferred.rs new file mode 100644 index 000000000..4cd4c4475 --- /dev/null +++ b/acdc-parser/src/extensions/deferred.rs @@ -0,0 +1,60 @@ +use serde::{Serialize, Serializer, ser::SerializeMap}; + +use crate::{BlockMetadata, Location, Title}; + +use super::{MacroInvocation, TargetId}; + +/// An opaque identity valid only in the document session that allocated it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct PlaceholderId(pub(crate) usize); + +/// A request retained by its document session for deferred construction. +#[derive(Debug)] +#[non_exhaustive] +pub struct DeferredBlock { + pub placeholder: PlaceholderId, + pub invocation: MacroInvocation<'static>, + pub(super) target: TargetId, +} + +impl DeferredBlock { + /// The handle used to query this request's placeholder block. + #[must_use] + pub const fn target(&self) -> &TargetId { + &self.target + } +} + +/// A deferred block that must be resolved before conversion. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct ExtensionBlock<'a> { + pub(crate) metadata: BlockMetadata<'a>, + pub(crate) title: Title<'a>, + pub(crate) location: Location, + pub(crate) processor: usize, + pub(crate) invocation: MacroInvocation<'a>, + pub(crate) placeholder: Option, +} + +impl ExtensionBlock<'_> { + #[must_use] + pub const fn placeholder(&self) -> Option { + self.placeholder + } +} + +impl Serialize for ExtensionBlock<'_> { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(None)?; + map.serialize_entry("name", "extension")?; + map.serialize_entry("type", "block")?; + map.serialize_entry("macro", &self.invocation.name)?; + map.serialize_entry("target", &self.invocation.target)?; + map.serialize_entry("attributes", &self.invocation.attributes)?; + map.serialize_entry("metadata", &self.metadata)?; + map.serialize_entry("title", &self.title)?; + map.serialize_entry("location", &self.location)?; + map.end() + } +} diff --git a/acdc-parser/src/extensions/finalization.rs b/acdc-parser/src/extensions/finalization.rs new file mode 100644 index 000000000..b49353085 --- /dev/null +++ b/acdc-parser/src/extensions/finalization.rs @@ -0,0 +1,129 @@ +use super::ExtensionParseResult; +use crate::{ + Error, Warning, WarningKind, + grammar::reference_walk::{self, ReferenceVisitor}, +}; + +#[derive(Default)] +struct Uses<'a> { + xrefs: Vec<(&'a str, crate::Location)>, + seen: std::collections::HashMap<&'a str, crate::Location>, + warnings: Vec, +} +impl<'a> Uses<'a> { + fn register(&mut self, id: &'a str, location: &crate::Location) { + if let Some(first) = self.seen.get(id) { + if first != location { + self.warnings.push(Warning::new( + WarningKind::DuplicateId { + id: id.into(), + first: Box::new(crate::SourceLocation::at_location(None, first.clone())), + }, + Some(crate::SourceLocation::at_location(None, location.clone())), + )); + } + } else { + self.seen.insert(id, location.clone()); + } + } +} +impl<'a> ReferenceVisitor<'a> for Uses<'a> { + type Error = std::convert::Infallible; + fn header(&mut self, header: &crate::Header<'a>) -> Result<(), Self::Error> { + if let Some(anchor) = header.metadata.heading_anchor() { + self.register(anchor.id, &anchor.location); + } + Ok(()) + } + fn section(&mut self, section: &mut crate::Section<'a>, _: bool) -> Result<(), Self::Error> { + if let Some(id) = section.id { + self.register(id, §ion.heading_location); + } + Ok(()) + } + fn anchor( + &mut self, + anchor: &crate::Anchor<'a>, + _: Option<&crate::ContentAttribute<'a>>, + _: Option<&crate::BlockMetadata<'a>>, + _: Option>, + _: Option>, + ) -> Result<(), Self::Error> { + self.register(anchor.id, &anchor.location); + Ok(()) + } + fn untitled(&mut self, id: &'a str, location: &crate::Location) -> Result<(), Self::Error> { + self.register(id, location); + Ok(()) + } +} + +impl ExtensionParseResult { + pub(super) fn repair_after_edit(&mut self) -> Result<(), Error> { + let warnings = self.parsed.with_document_mut(|_, document| { + document + .rebuild_footnotes() + .map_err(|error| failure(document, error))?; + document + .rebuild_extension_references() + .map_err(|error| failure(document, error))?; + if let Some(index) = self.targets.get() { + index.repair_section_references(document); + } + let mut uses = Uses::default(); + if let Some(header) = &document.header { + reference_walk::header(&mut uses, header).unwrap_or_else(|never| match never {}); + } + reference_walk::blocks(&mut uses, &mut document.blocks, true) + .unwrap_or_else(|never| match never {}); + crate::grammar::walk_document_inline_nodes_mut(document, &mut |inline| { + if let crate::InlineNode::Macro(crate::InlineMacro::CrossReference(reference)) = + inline + && (reference.target_is_local + || reference.source_syntax.target_is_local(reference.target)) + { + uses.xrefs + .push((reference.target, reference.location.clone())); + } + }); + uses.warnings.extend( + uses.xrefs + .into_iter() + .filter(|(target, _)| !document.references.contains_key(target)) + .map(|(target, location)| { + Warning::new( + WarningKind::UnresolvedReference { + target: target.into(), + }, + Some(crate::SourceLocation::at_location(None, location)), + ) + }), + ); + Ok::<_, Error>(uses.warnings) + })?; + self.parsed.replace_reference_warnings(warnings); + if let Some(index) = self.targets.get_mut() { + index.reserve_warnings(&self.parsed); + } + Ok(()) + } +} + +fn failure(document: &crate::Document<'_>, error: impl std::fmt::Display) -> Error { + Error::Extension( + Box::new(crate::SourceLocation::at_location( + None, + document.location.clone(), + )), + error.to_string(), + ) +} + +pub(crate) fn repair_macros(document: &mut crate::Document<'_>) -> Result<(), Error> { + document + .rebuild_footnotes() + .map_err(|error| failure(document, error))?; + document + .rebuild_references_and_toc() + .map_err(|error| failure(document, error)) +} diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs new file mode 100644 index 000000000..f5c71b252 --- /dev/null +++ b/acdc-parser/src/extensions/mod.rs @@ -0,0 +1,75 @@ +//! Registered block macros with document-local queries and processor state. +//! +//! ``` +//! use acdc_parser::{Options, extensions::{ +//! BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry, +//! }}; +//! +//! struct Greeting; +//! impl BlockMacroProcessor for Greeting { +//! fn process(&mut self, call: &MacroInvocation<'_>) -> Result { +//! Ok(BlockMacroOutput::Paragraph(format!("Hello, {}!", call.target))) +//! } +//! } +//! +//! let mut builder = Registry::builder(); +//! builder.register(BlockMacro::new("greet", || Greeting))?; +//! let registry = builder.build(); +//! let parsed = registry.parse("greet::World[]", &Options::default())?; +//! assert!(parsed.deferred_blocks().is_empty()); +//! assert_eq!(parsed.finish()?.document().blocks().count(), 1); +//! # Ok::<(), Box>(()) +//! ``` +//! +//! On success, each accepted macro runs once, in document order, after the document is accepted. +//! Its attribute snapshot reflects the macro's position. The host repairs catalogs +//! after the callbacks finish. +//! Callbacks cannot affect conditionals, includes, or later parsing. Deferred +//! blocks retain their arguments and a session-local identity; they are not +//! renderable content. `ExtensionParseResult::finish()` rejects unresolved requests +//! and returns an ordinary `ParseResult` for conversion. +//! +//! Query parsed blocks by semantic context and let the host assign link targets: +//! +//! ``` +//! use acdc_parser::{Options, extensions::{BlockContext, Registry}}; +//! +//! let mut result = Registry::default().parse(".A figure\nimage::figure.svg[]", &Options::default())?; +//! let images: Vec<_> = result.query().select(BlockContext::Image) +//! .map(|image| image.target().clone()).collect(); +//! for target in images { +//! let id = result.ensure_id(&target)?.to_owned(); +//! assert_eq!(result.query().get(&target).unwrap().output_id(), Some(id.as_str())); +//! } +//! # Ok::<(), Box>(()) +//! ``` +//! +//! Queries include nested list attachments, compound blocks, and `AsciiDoc` cells. +//! Titles and captions carry their parsed source-position values. Assigning an ID +//! preserves existing IDs and updates the reference catalog; it does not change +//! block order or rerun processors. Deferred requests expose the same target handles. +//! +mod block_macro; +mod deferred; +pub(crate) mod finalization; +mod query; +mod recognition; +mod registry; +mod session; +mod target; +mod traversal; + +pub use block_macro::{ + BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroContext, MacroInvocation, MacroTarget, +}; +pub use deferred::{DeferredBlock, ExtensionBlock, PlaceholderId}; +pub use query::{BlockContext, BlockView, DocumentQuery}; +pub use registry::{RegistrationError, Registry, RegistryBuilder}; +pub use session::ExtensionParseResult; +pub use target::{TargetError, TargetId}; + +pub(crate) use recognition::recognize; +pub(crate) use session::Session; + +#[cfg(test)] +mod tests; diff --git a/acdc-parser/src/extensions/query.rs b/acdc-parser/src/extensions/query.rs new file mode 100644 index 000000000..326592b08 --- /dev/null +++ b/acdc-parser/src/extensions/query.rs @@ -0,0 +1,392 @@ +use std::collections::{HashMap, HashSet}; + +use crate::{ + Block, CaptionKind, DelimitedBlockType, Document, InlineMacro, InlineNode, ParseResult, + SourceLocation, WarningKind, model::SectionReference, +}; + +use super::{ + Session, TargetId, + target::DocumentIdentity, + traversal::{BlockPath, Children, visit_children}, +}; + +/// The semantic context used to select blocks, independent of their Rust representation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum BlockContext { + Section, + Paragraph, + Example, + Open, + Sidebar, + Quote, + Verse, + Listing, + Literal, + Passthrough, + Stem, + Table, + Image, + Audio, + Video, + Admonition, + UnorderedList, + OrderedList, + DescriptionList, + CalloutList, + DiscreteHeading, + ThematicBreak, + PageBreak, + TableOfContents, + Comment, + DocumentAttribute, + Extension, +} + +impl BlockContext { + fn of(block: &Block<'_>) -> Self { + match block { + Block::Section(_) => Self::Section, + Block::Paragraph(block) => Self::styled(block.metadata.style, Self::Paragraph), + Block::DelimitedBlock(block) => match &block.inner { + DelimitedBlockType::DelimitedExample(_) => Self::Example, + DelimitedBlockType::DelimitedOpen(_) => { + Self::styled(block.metadata.style, Self::Open) + } + DelimitedBlockType::DelimitedSidebar(_) => Self::Sidebar, + DelimitedBlockType::DelimitedQuote(_) => Self::Quote, + DelimitedBlockType::DelimitedVerse(_) => Self::Verse, + DelimitedBlockType::DelimitedListing(_) => match block.metadata.style { + Some("literal") => Self::Literal, + _ => Self::Listing, + }, + DelimitedBlockType::DelimitedLiteral(_) => match block.metadata.style { + Some("listing" | "source") => Self::Listing, + _ => Self::Literal, + }, + DelimitedBlockType::DelimitedPass(_) => Self::Passthrough, + DelimitedBlockType::DelimitedStem(_) => Self::Stem, + DelimitedBlockType::DelimitedTable(_) => Self::Table, + DelimitedBlockType::DelimitedComment(_) => Self::Comment, + }, + Block::Image(_) => Self::Image, + Block::Audio(_) => Self::Audio, + Block::Video(_) => Self::Video, + Block::Admonition(_) => Self::Admonition, + Block::UnorderedList(_) => Self::UnorderedList, + Block::OrderedList(_) => Self::OrderedList, + Block::DescriptionList(_) => Self::DescriptionList, + Block::CalloutList(_) => Self::CalloutList, + Block::DiscreteHeading(_) => Self::DiscreteHeading, + Block::ThematicBreak(_) => Self::ThematicBreak, + Block::PageBreak(_) => Self::PageBreak, + Block::TableOfContents(_) => Self::TableOfContents, + Block::Comment(_) => Self::Comment, + Block::DocumentAttribute(_) => Self::DocumentAttribute, + Block::Extension(_) => Self::Extension, + } + } + + fn styled(style: Option<&str>, default: Self) -> Self { + match style { + Some("example") => Self::Example, + Some("listing" | "source") => Self::Listing, + Some("literal") => Self::Literal, + Some("quote") => Self::Quote, + Some("verse") => Self::Verse, + Some("sidebar") => Self::Sidebar, + Some("pass") => Self::Passthrough, + Some("stem" | "latexmath" | "asciimath") => Self::Stem, + _ => default, + } + } +} + +#[derive(Debug)] +pub(super) struct Entry { + pub(super) target: TargetId, + pub(super) path: BlockPath, + section: Option, +} + +#[derive(Debug)] +pub(super) struct TargetIndex { + document: DocumentIdentity, + entries: Vec, + slots: Vec>, + unresolved_targets: HashSet, + caption_high_water: Option<[u32; 4]>, + section_references: HashMap, +} + +impl TargetIndex { + pub(super) fn prepare_edit(&mut self, document: &mut Document<'_>) { + if self.caption_high_water.is_some() { + return; + } + let is_book = document.attributes.text("doctype") == Some("book"); + let references = + crate::model::section::extension_reference_numbers(&mut document.blocks, is_book); + let sections = self + .entries + .iter() + .filter(|entry| matches!(entry.path.get(&document.blocks), Some(Block::Section(_)))); + self.section_references.extend( + sections + .zip(references) + .map(|(entry, reference)| (entry.target.slot, reference)), + ); + self.caption_high_water.get_or_insert_with(|| { + [ + CaptionKind::Example, + CaptionKind::Figure, + CaptionKind::Listing, + CaptionKind::Table, + ] + .map(|kind| document.highest_caption_number(kind)) + }); + } + + pub(super) fn section_reference(&self, target: &TargetId) -> Option<&SectionReference> { + self.entry(target)?; + self.section_references.get(&target.slot) + } + + pub(super) fn repair_section_references(&self, document: &mut Document<'_>) { + for entry in &self.entries { + let Some(Block::Section(section)) = entry.path.get(&document.blocks) else { + continue; + }; + if let Some(reference) = document.references.get_mut(section.id().as_ref()) + && reference.occurrence == section.occurrence + { + reference.section = self.section_reference(&entry.target).cloned(); + } + } + let names: HashMap<_, _> = document + .references + .iter() + .filter_map(|(id, reference)| Some((*id, reference.section.as_ref()?.name))) + .collect(); + crate::grammar::walk_document_inline_nodes_mut(document, &mut |inline| { + if let InlineNode::Macro(InlineMacro::CrossReference(xref)) = inline { + xref.refresh_signifier(names.get(xref.target).copied()); + } + }); + } + + pub(super) fn reserve_warnings(&mut self, parsed: &ParseResult) { + self.unresolved_targets + .extend(parsed.warnings().iter().filter_map(|warning| { + if let WarningKind::UnresolvedReference { target } = &warning.kind { + Some(target.clone()) + } else { + None + } + })); + } + pub(super) fn new(parsed: &ParseResult, session: &Session) -> Self { + let unresolved_targets = parsed + .warnings() + .iter() + .filter_map(|warning| { + if let WarningKind::UnresolvedReference { target } = &warning.kind { + Some(target.clone()) + } else { + None + } + }) + .collect(); + let mut index = Self { + document: session.identity().clone(), + entries: Vec::new(), + slots: vec![None; session.deferred.len()], + unresolved_targets, + caption_high_water: None, + section_references: HashMap::new(), + }; + for (position, block) in parsed.document_storage().blocks.iter().enumerate() { + index.visit(block, &BlockPath::root(position), None, session); + } + index + } + + pub(super) fn reserves_id(&self, id: &str) -> bool { + self.unresolved_targets.contains(id) + } + + fn visit( + &mut self, + block: &Block<'_>, + path: &BlockPath, + section: Option<&TargetId>, + session: &Session, + ) { + let deferred = if let Block::Extension(block) = block { + block + .placeholder() + .and_then(|placeholder| session.deferred.get(placeholder.0)) + } else { + None + }; + let target = if let Some(request) = deferred { + let target = request.target().clone(); + if let Some(slot) = self.slots.get_mut(target.slot) { + *slot = Some(self.entries.len()); + } + target + } else { + let target = TargetId { + document: self.document.clone(), + slot: self.slots.len(), + }; + self.slots.push(Some(self.entries.len())); + target + }; + self.entries.push(Entry { + target: target.clone(), + path: path.clone(), + section: section.cloned(), + }); + let section = if matches!(block, Block::Section(_)) { + Some(&target) + } else { + section + }; + visit_children(block, |children, blocks| { + let section = if matches!(children, Children::Cell { .. }) { + None + } else { + section + }; + for (position, child) in blocks.iter().enumerate() { + self.visit(child, &path.child(children, position), section, session); + } + }); + } + + pub(super) fn entry(&self, target: &TargetId) -> Option<&Entry> { + if target.document != self.document { + return None; + } + self.entries + .get(self.slots.get(target.slot).copied().flatten()?) + } +} + +/// Read-only access to blocks in depth-first document order, parents before children. +/// +/// Traversal includes list attachments, compound blocks, and `AsciiDoc` table-cell documents. +/// List items and table cells are containers, rather than separate block targets. +/// The document header is outside this block query. +pub struct DocumentQuery<'doc> { + pub(super) parsed: &'doc ParseResult, + pub(super) index: &'doc TargetIndex, +} + +impl<'doc> DocumentQuery<'doc> { + /// Visit every block in document order. + pub fn blocks(&self) -> impl Iterator> + '_ { + self.index + .entries + .iter() + .filter_map(|entry| self.view(entry)) + } + + /// Select blocks by semantic context, retaining document order. + pub fn select(&self, context: BlockContext) -> impl Iterator> + '_ { + self.blocks().filter(move |view| view.context() == context) + } + + /// Resolve a document-local handle. Foreign or removed targets return `None`. + #[must_use] + pub fn get(&self, target: &TargetId) -> Option> { + self.view(self.index.entry(target)?) + } + + fn view(&self, entry: &'doc Entry) -> Option> { + Some(BlockView { + parsed: self.parsed, + entry, + block: entry.path.get(&self.parsed.document_storage().blocks)?, + }) + } +} + +/// A selected block, its identity, and its source and containing-section context. +pub struct BlockView<'doc> { + parsed: &'doc ParseResult, + entry: &'doc Entry, + block: &'doc Block<'doc>, +} + +impl<'doc> BlockView<'doc> { + #[must_use] + pub const fn target(&self) -> &'doc TargetId { + &self.entry.target + } + + /// The nearest enclosing section within the same document scope. + /// A section excludes itself, and `AsciiDoc` cells start a new document scope. + #[must_use] + pub fn containing_section(&self) -> Option<&'doc TargetId> { + self.entry.section.as_ref() + } + + #[must_use] + pub fn context(&self) -> BlockContext { + BlockContext::of(self.block) + } + + #[must_use] + pub fn block(&self) -> crate::ast::BlockRef<'doc> { + crate::ast::BlockRef::from(self.block) + } + + #[cfg(test)] + pub(super) const fn storage(&self) -> &'doc Block<'doc> { + self.block + } + + /// The title after its source-position substitutions, before backend rendering. + #[must_use] + pub fn title(&self) -> Option> { + self.block().title() + } + + #[must_use] + pub fn attributes(&self) -> Option> { + self.block().attributes() + } + + /// Caption settings and ordinal resolved by the host for this block. + #[must_use] + pub fn caption(&self) -> Option> { + self.block + .metadata()? + .caption + .as_ref() + .map(crate::ast::CaptionRef::from) + } + + #[must_use] + pub fn source_location(&self) -> SourceLocation { + self.parsed.source_location(self.block.location()) + } + + /// The authored or host-assigned output ID, if present and non-empty. + #[must_use] + pub fn output_id(&self) -> Option<&'doc str> { + output_id(self.block) + } +} + +pub(super) fn output_id<'doc>(block: &'doc Block<'_>) -> Option<&'doc str> { + let id = if let Block::Section(section) = block { + crate::Section::explicit_id(§ion.metadata).or(section.id) + } else { + block.anchor().map(|anchor| anchor.id) + }; + id.filter(|id| !id.is_empty()) +} diff --git a/acdc-parser/src/extensions/recognition.rs b/acdc-parser/src/extensions/recognition.rs new file mode 100644 index 000000000..5cac2bc7b --- /dev/null +++ b/acdc-parser/src/extensions/recognition.rs @@ -0,0 +1,92 @@ +use std::borrow::Cow; + +use crate::{ + AttributeValue, Block, BlockMetadata, DocumentAttributes, ElementAttributes, Error, Location, + Substitution, Title, apply_attribute_substitutions, grammar::ParserState, +}; + +use super::{ExtensionBlock, MacroInvocation, MacroTarget}; + +pub(crate) fn recognize<'a>( + state: &ParserState<'a>, + name: &'a str, + target: &'a str, + arguments: &'a str, + metadata: BlockMetadata<'a>, + title: Title<'a>, + location: Location, +) -> Result, Error> { + let (processor, descriptor) = state + .options + .extensions + .as_ref() + .and_then(|r| r.find(name)) + .ok_or_else(|| { + Error::Extension( + Box::new(state.create_error_source_location(location.clone())), + format!("unregistered block macro: {name}"), + ) + })?; + let target = state.intern_cow(apply_attribute_substitutions( + target, + &[Substitution::Attributes], + &state.document_attributes, + )); + if matches!(descriptor.target, MacroTarget::Required) && target.is_empty() + || matches!(descriptor.target, MacroTarget::Empty) && !target.is_empty() + { + return Err(Error::Extension( + Box::new(state.create_error_source_location(location)), + format!("invalid target for block macro {name}"), + )); + } + let scanned = if arguments.trim().is_empty() { + Vec::new() + } else { + crate::grammar::attributes::extension_attributes(state, arguments) + }; + let mut positional = Vec::new(); + let mut attributes = ElementAttributes::default(); + for (slot, argument) in scanned.into_iter().enumerate() { + if argument.name.is_some() && argument.is_unset() { + continue; + } + let value = state.intern_str(&argument.value); + if let Some(name) = argument.name { + attributes.set( + Cow::Borrowed(state.intern_str(&name)), + AttributeValue::String(Cow::Borrowed(value)), + ); + } else { + positional.resize(slot, None); + positional.push((!value.is_empty()).then_some(value)); + } + } + for (name, value) in descriptor.positional.iter().zip(&positional) { + if let Some(value) = value { + attributes.insert_if_absent( + Cow::Borrowed(state.intern_str(name)), + AttributeValue::String(Cow::Borrowed(value)), + ); + } + } + attributes.merge_defaults(descriptor.defaults.clone()); + Ok(Block::Extension(Box::new(ExtensionBlock { + metadata, + title, + invocation: MacroInvocation { + name: Cow::Borrowed(name), + target: Cow::Borrowed(target), + positional: positional + .into_iter() + .map(|value| value.map(Cow::Borrowed)) + .collect(), + attributes, + document_attributes: DocumentAttributes::clone(&state.document_attributes), + location: state.create_error_source_location(location.clone()), + }, + location, + processor, + placeholder: None, + }))) +} diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs new file mode 100644 index 000000000..f6c571164 --- /dev/null +++ b/acdc-parser/src/extensions/registry.rs @@ -0,0 +1,177 @@ +use std::{collections::HashMap, path::Path, sync::Arc}; + +use crate::{Error, Options, ParseResult}; + +use super::{BlockMacro, ExtensionParseResult, Session}; + +/// A registration rejected before any document is parsed. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[non_exhaustive] +pub enum RegistrationError { + #[error("invalid extension name: {0}")] + InvalidName(String), + #[error("block macro name is reserved: {0}")] + ReservedName(String), + #[error("block macro is already registered: {0}")] + DuplicateName(String), + #[error("block macro is not registered: {0}")] + UnknownName(String), +} + +/// Builds a registry without modifying existing registry snapshots. +#[derive(Debug, Default)] +pub struct RegistryBuilder { + macros: Vec, + names: HashMap, +} + +impl RegistryBuilder { + /// Register a macro after the existing registrations. + /// + /// Names match `[A-Za-z][A-Za-z0-9_-]*`. Built-in macro names are reserved. + /// + /// # Errors + /// Rejects invalid names, built-in names, and duplicate registrations. + pub fn register(&mut self, descriptor: BlockMacro) -> Result<&mut Self, RegistrationError> { + validate_name(&descriptor.name)?; + if self.names.contains_key(&descriptor.name) { + return Err(RegistrationError::DuplicateName(descriptor.name)); + } + self.names + .insert(descriptor.name.clone(), self.macros.len()); + self.macros.push(descriptor); + Ok(self) + } + + /// Replace a macro explicitly, preserving its registration position. + /// + /// # Errors + /// Rejects names that have not been registered. + pub fn replace(&mut self, descriptor: BlockMacro) -> Result<&mut Self, RegistrationError> { + let index = *self + .names + .get(&descriptor.name) + .ok_or_else(|| RegistrationError::UnknownName(descriptor.name.clone()))?; + if let Some(entry) = self.macros.get_mut(index) { + *entry = descriptor; + } + Ok(self) + } + + #[must_use] + pub fn build(self) -> Registry { + Registry(Arc::new(RegistryData { + macros: self.macros, + names: self.names, + })) + } +} + +fn validate_name(name: &str) -> Result<(), RegistrationError> { + validate_identifier(name)?; + if matches!( + name, + "image" | "audio" | "video" | "toc" | "include" | "ifdef" | "ifndef" | "ifeval" | "endif" + ) { + return Err(RegistrationError::ReservedName(name.to_owned())); + } + Ok(()) +} + +fn validate_identifier(name: &str) -> Result<(), RegistrationError> { + let mut bytes = name.bytes(); + if !bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic()) + || !bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + { + return Err(RegistrationError::InvalidName(name.to_owned())); + } + Ok(()) +} + +#[derive(Debug, Default)] +struct RegistryData { + macros: Vec, + names: HashMap, +} + +/// A cheap-to-clone, immutable collection of extension factories. +#[derive(Clone, Debug, Default)] +pub struct Registry(Arc); + +impl Registry { + #[must_use] + pub fn builder() -> RegistryBuilder { + RegistryBuilder::default() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.0.macros.is_empty() + } + + /// Parse with fresh processors and retain this document's deferred requests. + /// + /// Macro processors run after the complete document is accepted. The host + /// repairs captions and catalogs. Callbacks cannot change source processing. + /// An empty registry uses the ordinary parser path. + /// + /// # Errors + /// Returns preprocessing, parsing, or processor errors with source locations. + pub fn parse(&self, input: &str, options: &Options<'_>) -> Result { + self.parse_using(options, |options, session| { + crate::parse_with_session(input, options, session) + }) + } + + /// Parse a file with the same session contract as [`Self::parse`]. + /// + /// # Errors + /// Returns file, preprocessing, parsing, or processor errors. + pub fn parse_file( + &self, + path: impl AsRef, + options: &Options<'_>, + ) -> Result { + self.parse_using(options, |options, session| { + crate::parse_file_with_session(path.as_ref(), options, session) + }) + } + + fn parse_using( + &self, + options: &Options<'_>, + parse: impl FnOnce(&Options<'_>, Option<&mut Session>) -> Result, + ) -> Result { + let mut session = self.session(); + let parsed = if self.0.macros.is_empty() { + parse(options, None)? + } else { + let mut options = options.clone(); + options.extensions = Some(self.clone()); + parse(&options, Some(&mut session))? + }; + let mut result = ExtensionParseResult::new(parsed, session); + if result.session.processed_blocks { + result.repair_after_edit()?; + } + Ok(result) + } + + pub(crate) fn find(&self, name: &str) -> Option<(usize, &BlockMacro)> { + let index = *self.0.names.get(name)?; + self.0 + .macros + .get(index) + .map(|descriptor| (index, descriptor)) + } + + pub(crate) fn session(&self) -> Session { + Session::new( + self.0 + .macros + .iter() + .map(|entry| (entry.factory)()) + .collect(), + ) + } +} diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs new file mode 100644 index 000000000..19a227c73 --- /dev/null +++ b/acdc-parser/src/extensions/session.rs @@ -0,0 +1,257 @@ +use std::{cell::OnceCell, fmt}; + +use crate::{ + Block, DelimitedBlockType, Document, Error, InlineNode, Paragraph, ParseResult, Plain, + grammar::ParserState, +}; + +use super::{ + BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, PlaceholderId, TargetId, + query::TargetIndex, target::DocumentIdentity, +}; + +pub(crate) struct Session { + processors: Vec>, + pub(super) deferred: Vec, + pub(super) processed_blocks: bool, + identity: OnceCell, +} + +impl fmt::Debug for Session { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Session") + .field("deferred", &self.deferred) + .finish_non_exhaustive() + } +} + +/// A parsed document and the processors and requests that belong to it. +#[derive(Debug)] +#[must_use] +pub struct ExtensionParseResult { + pub(super) parsed: ParseResult, + pub(super) session: Session, + // Keep unqueried extension results small. + pub(super) targets: OnceCell>, +} + +impl ExtensionParseResult { + pub(super) fn new(parsed: ParseResult, session: Session) -> Self { + Self { + parsed, + session, + targets: OnceCell::new(), + } + } + + /// Recoverable problems from parsing and subsequent edits. + #[must_use] + pub fn warnings(&self) -> &[crate::Warning] { + self.parsed.warnings() + } + + /// Finish this session for conversion. + /// + /// # Errors + /// Returns a located error if a deferred request remains unresolved. + pub fn finish(self) -> Result { + if let Some(request) = self.session.deferred.first() { + return Err(Error::Extension( + Box::new(request.invocation.location.clone()), + "unresolved deferred block".into(), + )); + } + Ok(self.parsed) + } + + #[must_use] + pub fn deferred_blocks(&self) -> &[DeferredBlock] { + &self.session.deferred + } + + /// Query blocks and their document-local identities. + /// + /// The host builds the query index on first use. Parsing without queries + /// does not allocate an index. + #[must_use] + pub fn query(&self) -> DocumentQuery<'_> { + DocumentQuery { + parsed: &self.parsed, + index: self.target_index(), + } + } + + pub(super) fn target_index(&self) -> &TargetIndex { + self.targets + .get_or_init(|| Box::new(TargetIndex::new(&self.parsed, &self.session))) + } +} + +impl Session { + pub(super) fn new(processors: Vec>) -> Self { + Self { + processors, + deferred: Vec::new(), + processed_blocks: false, + identity: OnceCell::new(), + } + } + + pub(super) fn identity(&self) -> &DocumentIdentity { + self.identity.get_or_init(DocumentIdentity::default) + } + + pub(crate) fn process<'a>( + &mut self, + document: &mut Document<'a>, + state: &ParserState<'a>, + ) -> Result { + self.blocks(&mut document.blocks, state)?; + Ok(self.processed_blocks) + } + + fn blocks<'a>( + &mut self, + blocks: &mut Vec>, + state: &ParserState<'a>, + ) -> Result<(), Error> { + let mut result = Ok(()); + blocks.retain_mut(|block| { + if result.is_err() { + return true; + } + match self.block(block, state) { + Ok(keep) => keep, + Err(error) => { + result = Err(error); + true + } + } + }); + result + } + + fn block<'a>(&mut self, block: &mut Block<'a>, state: &ParserState<'a>) -> Result { + match block { + Block::Extension(extension) => { + self.processed_blocks = true; + let output = self + .processors + .get_mut(extension.processor) + .ok_or_else(|| { + Error::Extension( + Box::new(extension.invocation.location.clone()), + "processor is absent from the document session".into(), + ) + })? + .process(&extension.invocation) + .map_err(|message| { + Error::Extension(Box::new(extension.invocation.location.clone()), message) + })?; + match output { + BlockMacroOutput::Paragraph(text) => { + let mut paragraph = Paragraph::new( + vec![InlineNode::PlainText(Plain { + content: state.intern_str(&text), + location: extension.location.clone(), + escaped: true, + })], + extension.location.clone(), + ); + paragraph.metadata = std::mem::take(&mut extension.metadata); + paragraph.title = std::mem::take(&mut extension.title); + if let Some(kind) = crate::CaptionKind::for_style(paragraph.metadata.style) + { + paragraph.metadata.caption = Some(crate::Caption::resolve( + ¶graph.metadata, + &extension.invocation.document_attributes, + kind, + )); + } + *block = Block::Paragraph(paragraph); + } + BlockMacroOutput::None => return Ok(false), + BlockMacroOutput::Deferred => { + let placeholder = PlaceholderId(self.deferred.len()); + extension.placeholder = Some(placeholder); + self.deferred.push(DeferredBlock { + placeholder, + invocation: extension.invocation.to_owned_invocation(), + target: TargetId { + document: self.identity().clone(), + slot: placeholder.0, + }, + }); + } + } + } + Block::Section(section) => self.blocks(&mut section.content, state)?, + Block::Admonition(admonition) => self.blocks(&mut admonition.blocks, state)?, + Block::UnorderedList(list) => { + for item in &mut list.items { + self.blocks(&mut item.blocks, state)?; + } + } + Block::OrderedList(list) => { + for item in &mut list.items { + self.blocks(&mut item.blocks, state)?; + } + } + Block::CalloutList(list) => { + for item in &mut list.items { + self.blocks(&mut item.blocks, state)?; + } + } + Block::DescriptionList(list) => { + for item in &mut list.items { + if let Some(definition) = &mut item.definition { + self.blocks(&mut definition.blocks, state)?; + } + } + } + Block::DelimitedBlock(delimited) => self.delimited(&mut delimited.inner, state)?, + Block::TableOfContents(_) + | Block::DiscreteHeading(_) + | Block::DocumentAttribute(_) + | Block::ThematicBreak(_) + | Block::PageBreak(_) + | Block::Paragraph(_) + | Block::Image(_) + | Block::Audio(_) + | Block::Video(_) + | Block::Comment(_) => {} + } + Ok(true) + } + fn delimited<'a>( + &mut self, + inner: &mut DelimitedBlockType<'a>, + state: &ParserState<'a>, + ) -> Result<(), Error> { + match inner { + DelimitedBlockType::DelimitedExample(blocks) + | DelimitedBlockType::DelimitedOpen(blocks) + | DelimitedBlockType::DelimitedSidebar(blocks) + | DelimitedBlockType::DelimitedQuote(blocks) => self.blocks(blocks, state)?, + DelimitedBlockType::DelimitedTable(table) => { + for row in table + .header + .iter_mut() + .chain(&mut table.rows) + .chain(&mut table.footer) + { + for column in &mut row.columns { + self.blocks(&mut column.content, state)?; + } + } + } + DelimitedBlockType::DelimitedComment(_) + | DelimitedBlockType::DelimitedListing(_) + | DelimitedBlockType::DelimitedLiteral(_) + | DelimitedBlockType::DelimitedPass(_) + | DelimitedBlockType::DelimitedVerse(_) + | DelimitedBlockType::DelimitedStem(_) => {} + } + Ok(()) + } +} diff --git a/acdc-parser/src/extensions/target.rs b/acdc-parser/src/extensions/target.rs new file mode 100644 index 000000000..ba54c506b --- /dev/null +++ b/acdc-parser/src/extensions/target.rs @@ -0,0 +1,154 @@ +use std::{ + fmt, + hash::{Hash, Hasher}, + rc::Rc, +}; + +use crate::{Anchor, Block, ReferenceTarget, grammar::reference_walk}; + +use super::ExtensionParseResult; + +#[derive(Clone, Debug, Default)] +pub(super) struct DocumentIdentity(Rc<()>); + +impl PartialEq for DocumentIdentity { + fn eq(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } +} + +impl Eq for DocumentIdentity {} + +impl Hash for DocumentIdentity { + fn hash(&self, state: &mut H) { + Rc::as_ptr(&self.0).hash(state); + } +} + +/// An opaque block identity belonging to one parsed document. +/// +/// Assigning an output ID does not change this handle. Handles from separate +/// parses are distinct, even when the inputs and output IDs are identical. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct TargetId { + pub(super) document: DocumentIdentity, + pub(super) slot: usize, +} + +impl fmt::Debug for TargetId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TargetId").finish_non_exhaustive() + } +} + +/// A target cannot be used for the requested operation. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[non_exhaustive] +pub enum TargetError { + #[error("target does not belong to this document or is no longer present")] + UnknownTarget, + #[error("this block cannot carry an output ID")] + NotReferenceable, +} + +impl ExtensionParseResult { + /// Return the target's output ID, assigning one when it has none. + /// + /// Existing authored and generated IDs are preserved. New IDs avoid all + /// registered targets and unresolved reference names, so a previously broken + /// reference cannot accidentally bind to this block. IDs are deterministic + /// for identical conversions, independent of request order. + /// The reference catalog is updated without rerunning extension callbacks. + /// + /// # Errors + /// Rejects foreign or removed targets and blocks that cannot carry an ID. + pub fn ensure_id(&mut self, target: &TargetId) -> Result<&str, TargetError> { + let entry = self + .target_index() + .entry(target) + .ok_or(TargetError::UnknownTarget)?; + let block = entry + .path + .get(&self.parsed.document_storage().blocks) + .ok_or(TargetError::UnknownTarget)?; + if super::query::output_id(block).is_none() { + if block.metadata().is_none() && !matches!(block, Block::ThematicBreak(_)) { + return Err(TargetError::NotReferenceable); + } + let path = entry.path.clone(); + let is_section = matches!(block, Block::Section(_)); + if is_section && let Some(index) = self.targets.get_mut() { + self.parsed + .with_document_mut(|_, document| index.prepare_edit(document)); + } + let section_reference = self.target_index().section_reference(target).cloned(); + let base = format!("_acdc_{}", target.slot + 1); + let mut id = base.clone(); + let mut suffix = 2; + while self + .parsed + .document_storage() + .references + .contains_key(id.as_str()) + || self.target_index().reserves_id(&id) + { + id = format!("{base}_{suffix}"); + suffix += 1; + } + self.parsed.with_document_mut(|owner, document| { + let id: &str = owner.arena.alloc_str(&id); + let block = path + .get_mut(&mut document.blocks) + .ok_or(TargetError::UnknownTarget)?; + let anchor = Anchor::new(id, block.location().clone()); + if let Block::ThematicBreak(block) = block { + block.anchors.push(anchor); + } else { + block + .metadata_mut() + .ok_or(TargetError::NotReferenceable)? + .id = Some(anchor); + } + if let Block::Section(section) = block { + section.id = Some(id); + if document.references.get("").is_some_and(|reference| { + reference.section_category().is_some() + && reference.location.start == section.location.start + && reference.location.absolute_start == section.location.absolute_start + }) { + document.references.remove(""); + } + for entry in &mut document.toc_entries { + if entry.id.is_empty() + && entry.level == section.level + && entry.kind == section.kind + && entry.title == section.title + && entry.location.start.file == section.location.start.file + && section.location.absolute_start <= entry.location.absolute_start + && section.location.absolute_end >= entry.location.absolute_end + { + entry.id = id; + } + } + } + let mut reference = ReferenceTarget::for_anchor( + &Anchor::new(id, block.location().clone()), + block + .metadata() + .and_then(reference_walk::metadata_xreflabel), + block.title().cloned(), + block + .metadata() + .and_then(|metadata| metadata.caption.clone()), + ); + reference.section = section_reference; + document.references.insert(id, reference); + Ok(()) + })?; + } + self.query() + .get(target) + .and_then(|view| view.output_id()) + .ok_or(TargetError::UnknownTarget) + } +} diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs new file mode 100644 index 000000000..68175c5ac --- /dev/null +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -0,0 +1,374 @@ +#![allow(clippy::expect_used, clippy::indexing_slicing, clippy::panic)] + +use std::{ + cell::Cell, + error::Error as StdError, + rc::Rc, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; + +use acdc_parser::{ + Block, CompatibilityMode, Error, InlineNode, Options, SafeMode, WarningKind, + extensions::{ + BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroContext, MacroInvocation, + MacroTarget, RegistrationError, Registry, + }, +}; + +#[path = "support.rs"] +mod support; + +#[path = "queries.rs"] +mod queries; + +type TestResult = Result<(), Box>; + +struct Counter { + calls: Rc>, + total: Arc, + drops: Arc, +} + +impl BlockMacroProcessor for Counter { + fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result { + self.total.fetch_add(1, Ordering::Relaxed); + self.calls.set(self.calls.get() + 1); + match invocation.target.as_ref() { + "fail" => Err("deliberate failure".into()), + "skip" => Ok(BlockMacroOutput::None), + _ => Ok(BlockMacroOutput::Paragraph(self.calls.get().to_string())), + } + } +} + +impl Drop for Counter { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::Relaxed); + } +} + +fn counter_macro(total: &Arc, drops: &Arc) -> BlockMacro { + let total = Arc::clone(total); + let drops = Arc::clone(drops); + BlockMacro::new("count", move || Counter { + calls: Rc::new(Cell::new(0)), + total: Arc::clone(&total), + drops: Arc::clone(&drops), + }) +} + +fn paragraph_text(block: &Block<'_>) -> String { + let Block::Paragraph(paragraph) = block else { + panic!("expected paragraph, got {block:?}"); + }; + paragraph + .content + .iter() + .filter_map(|node| { + if let InlineNode::PlainText(text) = node { + Some(text.content) + } else { + None + } + }) + .collect() +} + +#[test] +fn extensions_fresh_local_processors_live_with_their_result() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let registry = builder.build(); + let first = registry.parse("count::one[]\n\ncount::two[]", &Options::default())?; + let second = registry + .clone() + .parse("count::one[]", &Options::default())?; + assert_eq!( + paragraph_text(&first.parsed.document_storage().blocks[1]), + "2" + ); + assert_eq!( + paragraph_text(&second.parsed.document_storage().blocks[0]), + "1" + ); + assert_eq!(total.load(Ordering::Relaxed), 3); + assert_eq!(drops.load(Ordering::Relaxed), 0); + drop(first); + assert_eq!(drops.load(Ordering::Relaxed), 1); + drop(second); + assert_eq!(drops.load(Ordering::Relaxed), 2); + Ok(()) +} + +#[test] +fn extensions_no_callbacks_for_rejected_document() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops).with_target(MacroTarget::Required))?; + let registry = builder.build(); + let error = registry + .parse("count::one[]\n\ncount::[]", &Options::default()) + .expect_err("missing target"); + assert!(matches!(error, Error::Extension(..))); + assert_eq!(total.load(Ordering::Relaxed), 0); + assert_eq!(drops.load(Ordering::Relaxed), 1); + Ok(()) +} + +#[test] +fn extensions_processor_error_stops_later_callbacks() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let error = builder + .build() + .parse( + "count::one[]\n\ncount::fail[]\n\ncount::three[]", + &Options::default(), + ) + .expect_err("processor error"); + assert_eq!( + error + .source_location() + .ok_or("missing location")? + .location + .start + .line, + 3 + ); + assert_eq!(total.load(Ordering::Relaxed), 2); + assert_eq!(drops.load(Ordering::Relaxed), 1); + Ok(()) +} + +#[test] +fn extensions_skipped_output_is_absent_from_reference_catalog() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let parsed = builder.build().parse( + ".Removed footnote:[removed]\n[#gone]\ncount::skip[]\n\nSee <> and footnote:[retained].", + &Options::default(), + )?; + assert!( + !parsed + .parsed + .document_storage() + .references + .contains_key("gone") + ); + assert_eq!(parsed.parsed.document_storage().blocks.len(), 1); + assert_eq!(parsed.parsed.document_storage().footnotes.len(), 1); + assert_eq!(parsed.parsed.document_storage().footnotes[0].number, 1); + assert!(parsed.parsed.warnings().iter().any(|warning| matches!(&warning.kind, WarningKind::UnresolvedReference {target} if target == "gone"))); + Ok(()) +} + +#[test] +fn extensions_context_limits_and_inactive_content() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops).with_contexts([MacroContext::Compound]))?; + let parsed = builder.build().parse("count::document[]\n\n====\ncount::compound[]\n====\n\nifdef::missing[]\ncount::inactive[]\nendif::[]", &Options::default())?; + assert_eq!( + paragraph_text(&parsed.parsed.document_storage().blocks[0]), + "count::document[]" + ); + assert_eq!(total.load(Ordering::Relaxed), 1); + Ok(()) +} + +#[test] +fn extensions_registry_rejects_ambiguous_names_and_replaces_explicitly() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + assert!(matches!( + builder.register(counter_macro(&total, &drops)), + Err(RegistrationError::DuplicateName(_)) + )); + builder.replace(counter_macro(&total, &drops).with_target(MacroTarget::Empty))?; + assert!( + builder + .build() + .parse("count::target[]", &Options::default()) + .is_err() + ); + for (name, reserved) in [ + ("image", true), + ("include", true), + ("bad:name", false), + ("", false), + ] { + let error = Registry::builder() + .register(BlockMacro::new(name, || Never)) + .expect_err("bad registration"); + assert_eq!( + matches!(error, RegistrationError::ReservedName(_)), + reserved + ); + } + Ok(()) +} + +struct Never; +impl BlockMacroProcessor for Never { + fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + panic!("unexpected processor invocation") + } +} + +#[test] +fn extensions_empty_or_unused_registry_preserves_document_and_warnings() -> TestResult { + let input = include_str!("../../../fixtures/tests/xref_nested_sections.adoc"); + let options = Options::default(); + let ordinary = acdc_parser::parse(input, &options)?; + for registry in [Registry::default(), support::registry()] { + let parsed = registry.parse(input, &options)?; + assert_eq!( + parsed.parsed.document_storage(), + ordinary.document_storage() + ); + assert_eq!(parsed.parsed.warnings(), ordinary.warnings()); + } + Ok(()) +} + +#[test] +fn extensions_macro_arguments_preserve_precedence_and_expand_targets() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let registry = support::registry(); + for (arguments, expected) in [ + ("", serde_json::json!({"first": "fallback"})), + ("positional", serde_json::json!({"first": "positional"})), + ( + "positional,first=named", + serde_json::json!({"first": "named"}), + ), + ("first=\"\"", serde_json::json!({"first": ""})), + ( + ",second=override", + serde_json::json!({"first": "fallback", "second": "override"}), + ), + ( + "first=\"expanded {mode}\"", + serde_json::json!({"first": "expanded chosen"}), + ), + ] { + let source = format!(":mode: chosen\n\nrecord::{{mode}}[{arguments}]"); + let parsed = registry.parse(&source, &options)?; + let output: serde_json::Value = + serde_json::from_str(¶graph_text(&parsed.parsed.document_storage().blocks[0]))?; + assert_eq!(output["target"], "chosen"); + assert_eq!(output["attributes"], expected, "{mode:?}: {arguments}"); + } + } + Ok(()) +} + +#[cfg(feature = "asg")] +#[test] +fn extensions_pending_blocks_are_rejected_by_checked_asg_exports() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("defer", || support::Defer))?; + let pending = builder.build().parse("defer::[]", &options)?; + for profile in [crate::asg::Profile::Upstream, crate::asg::Profile::Acdc] { + let error = + crate::asg::export_document_with_profile(pending.parsed.document(), profile) + .expect_err("pending requests must not be exported"); + assert!(matches!(error, crate::asg::Error::Unsupported { + path, + construct: Some("pending extension block"), + location: Some(_), + .. + } if path == "/blocks/0")); + } + assert_eq!(pending.deferred_blocks().len(), 1); + } + Ok(()) +} + +#[test] +fn extensions_deferred_requests_keep_include_context_and_placeholder_identity() -> TestResult { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/tests/includes/extensions/extensions_registered.adoc"); + let options = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let parsed = support::registry().parse_file(&path, &options)?; + let requests = parsed.deferred_blocks(); + assert_eq!(requests.len(), 2); + assert_ne!(requests[0].placeholder, requests[1].placeholder); + assert!( + requests[0] + .invocation + .location + .file + .as_ref() + .is_some_and(|file| file.ends_with("includes/extensions/extensions.adoc")) + ); + assert_eq!(requests[0].invocation.location.location.start.line, 5); + let Block::Section(section) = parsed + .parsed + .document_storage() + .blocks + .last() + .ok_or("missing section")? + else { + panic!("expected section"); + }; + let Block::Extension(last) = section.content.last().ok_or("missing deferred block")? else { + panic!("expected placeholder"); + }; + assert_eq!(last.placeholder(), Some(requests[1].placeholder)); + assert_eq!( + requests[1] + .invocation + .positional + .iter() + .map(|value| value.as_deref()) + .collect::>(), + vec![Some("one"), None, Some("three")] + ); + Ok(()) +} + +#[test] +fn extensions_output_captions_use_source_position_attributes() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let parsed = builder.build().parse( + ":example-caption: Before\n\n.Title\n[example]\ncount::one[]\n\n:example-caption: After\n\n.Title\n[example]\ncount::two[]", + &Options::default(), + )?; + // Captions are semantic data omitted from the JSON fixture format. + let captions: Vec<_> = parsed + .parsed + .document_storage() + .blocks + .iter() + .filter_map(|block| block.metadata()?.caption.as_ref()) + .collect(); + assert!( + matches!(captions[0], acdc_parser::Caption::Numbered { label, number, .. } if label == "Before" && number.is_some_and(|number| number.get() == 1)) + ); + assert!( + matches!(captions[1], acdc_parser::Caption::Numbered { label, number, .. } if label == "After" && number.is_some_and(|number| number.get() == 2)) + ); + Ok(()) +} diff --git a/acdc-parser/src/extensions/tests/queries.rs b/acdc-parser/src/extensions/tests/queries.rs new file mode 100644 index 000000000..ab85d1941 --- /dev/null +++ b/acdc-parser/src/extensions/tests/queries.rs @@ -0,0 +1,425 @@ +#![allow(clippy::expect_used, clippy::indexing_slicing)] + +use std::{ + error::Error, + path::Path, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; + +use acdc_parser::{ + Block, InlineNode, Options, SafeMode, WarningKind, + extensions::{BlockContext, Registry, TargetError}, +}; + +use super::support; + +type TestResult = Result<(), Box>; + +#[test] +fn extensions_query_targets_are_document_local_and_preserve_deferred_identity() -> TestResult { + let registry = support::registry(); + let mut first = registry.parse("defer::one[]\n\ndefer::two[]", &Options::default())?; + let second = registry.parse("defer::one[]\n\ndefer::two[]", &Options::default())?; + let target = first.deferred_blocks()[0].target().clone(); + assert_ne!(&target, second.deferred_blocks()[0].target()); + assert!(second.query().get(&target).is_none()); + assert_eq!( + first.ensure_id(second.deferred_blocks()[0].target()), + Err(TargetError::UnknownTarget) + ); + let id = first.ensure_id(&target)?.to_owned(); + assert_eq!(first.ensure_id(&target)?, id); + let query = first.query(); + let view = query.get(&target).ok_or("missing deferred target")?; + assert_eq!(view.context(), BlockContext::Extension); + assert_eq!(view.output_id(), Some(id.as_str())); + assert_eq!(first.deferred_blocks()[0].target(), &target); + assert_eq!(first.deferred_blocks().len(), 2); + Ok(()) +} + +#[test] +fn extensions_queries_and_ids_support_discrete_headings() -> TestResult { + for mode in [ + acdc_parser::CompatibilityMode::Asciidoctor, + acdc_parser::CompatibilityMode::Draft, + ] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut parsed = support::registry().parse( + "= Document\n\n[discrete]\n== A *heading*\n\nrecord::target[]", + &options, + )?; + let target = parsed + .query() + .select(BlockContext::DiscreteHeading) + .next() + .ok_or("missing discrete heading")? + .target() + .clone(); + let id = parsed.ensure_id(&target)?.to_owned(); + let query = parsed.query(); + let heading = query.get(&target).ok_or("missing heading target")?; + assert_eq!(heading.context(), BlockContext::DiscreteHeading); + assert!(matches!( + heading.block().kind(), + acdc_parser::ast::BlockKind::DiscreteHeading(_) + )); + assert_eq!(heading.output_id(), Some(id.as_str())); + assert!(parsed.finish()?.document().references().get(&id).is_some()); + } + Ok(()) +} + +#[test] +fn extensions_ids_avoid_authored_inline_and_generated_section_ids() -> TestResult { + let input = "image::one.svg[]\n\n[[_acdc_1]]\nParagraph.\n\n[#_acdc_1_2]\nSecond.\n\n== acdc 1 3\n\nSection body."; + let mut parsed = Registry::default().parse(input, &Options::default())?; + let target = parsed + .query() + .select(BlockContext::Image) + .next() + .ok_or("missing image")? + .target() + .clone(); + let before = parsed.parsed.document_storage().references.len(); + assert_eq!(parsed.ensure_id(&target)?, "_acdc_1_4"); + assert_eq!(parsed.ensure_id(&target)?, "_acdc_1_4"); + assert_eq!( + parsed.parsed.document_storage().references.len(), + before + 1 + ); + assert_eq!(parsed.parsed.warnings(), []); + Ok(()) +} + +#[test] +fn extensions_ids_preserve_existing_ids_and_query_order() -> TestResult { + let input = + "[#authored]\nimage::one.svg[]\n\nimage::two.svg[]\n\n== Heading\n\nimage::three.svg[]"; + let registry = Registry::default(); + let mut first = registry.parse(input, &Options::default())?; + let mut second = registry.parse(input, &Options::default())?; + let first_targets: Vec<_> = first + .query() + .blocks() + .map(|view| view.target().clone()) + .collect(); + let second_targets: Vec<_> = second + .query() + .blocks() + .map(|view| view.target().clone()) + .collect(); + for target in &first_targets { + first.ensure_id(target)?; + } + for target in second_targets.iter().rev() { + second.ensure_id(target)?; + } + let ids: Vec<_> = first + .query() + .blocks() + .map(|view| view.output_id().map(str::to_owned)) + .collect(); + let repeated_ids: Vec<_> = second + .query() + .blocks() + .map(|view| view.output_id().map(str::to_owned)) + .collect(); + assert_eq!(ids, repeated_ids); + assert_eq!(ids[0].as_deref(), Some("authored")); + assert_eq!(ids[2].as_deref(), Some("_heading")); + assert_eq!( + first + .query() + .blocks() + .map(|view| view.target().clone()) + .collect::>(), + first_targets + ); + assert_eq!( + first.parsed.document_storage(), + second.parsed.document_storage() + ); + Ok(()) +} + +#[test] +fn extensions_assigned_ids_register_titles_captions_and_reference_text() -> TestResult { + let input = ":figure-caption: Picture\n:refname: Early\n\n.A *formatted* title\n[reftext=\"{refname} *label*\"]\nimage::one.svg[]\n\n:refname: Late\n\nAfter."; + let mut parsed = Registry::default().parse(input, &Options::default())?; + let target = parsed + .query() + .select(BlockContext::Image) + .next() + .ok_or("missing image")? + .target() + .clone(); + let id = parsed.ensure_id(&target)?.to_owned(); + let query = parsed.query(); + let image = query.get(&target).ok_or("missing image target")?; + let reference = parsed + .parsed + .document_storage() + .references + .get(id.as_str()) + .ok_or("missing reference")?; + assert_eq!( + reference + .title + .as_ref() + .map(crate::ContentAttribute::as_inlines), + image.storage().title().map(crate::Title::as_inlines) + ); + assert_eq!( + reference.caption.as_ref(), + image + .storage() + .metadata() + .and_then(|metadata| metadata.caption.as_ref()) + ); + assert!(reference.xreflabel.as_ref().is_some_and(|label| { + label + .as_inlines() + .iter() + .any(|inline| matches!(inline, InlineNode::BoldText(_))) + })); + assert!( + matches!(reference.xreflabel.as_ref().and_then(|label| label.as_inlines().first()), Some(InlineNode::PlainText(text)) if text.content == "Early ") + ); + assert_eq!(parsed.parsed.warnings(), []); + Ok(()) +} + +#[test] +fn extensions_generated_ids_do_not_bind_existing_unresolved_references() -> TestResult { + let mut parsed = + Registry::default().parse("image::one.svg[]\n\nSee <<_acdc_1>>.", &Options::default())?; + let target = parsed + .query() + .select(BlockContext::Image) + .next() + .ok_or("missing image")? + .target() + .clone(); + assert_eq!(parsed.ensure_id(&target)?, "_acdc_1_2"); + assert!( + !parsed + .parsed + .document_storage() + .references + .contains_key("_acdc_1") + ); + assert!( + parsed + .parsed + .document_storage() + .references + .contains_key("_acdc_1_2") + ); + assert!(parsed.parsed.warnings().iter().any(|warning| matches!(&warning.kind, WarningKind::UnresolvedReference { target } if target == "_acdc_1"))); + Ok(()) +} + +#[test] +fn extensions_queries_and_ids_do_not_repeat_processors() -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(super::counter_macro(&calls, &drops))?; + let mut parsed = builder + .build() + .parse("count::one[]\n\ncount::two[]", &Options::default())?; + let targets: Vec<_> = parsed + .query() + .blocks() + .map(|view| view.target().clone()) + .collect(); + for target in &targets { + parsed.ensure_id(target)?; + parsed.ensure_id(target)?; + } + assert_eq!(parsed.query().blocks().count(), 2); + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!(drops.load(Ordering::Relaxed), 0); + drop(parsed); + assert_eq!(drops.load(Ordering::Relaxed), 1); + Ok(()) +} + +#[test] +fn extensions_query_includes_source_context_and_nested_document_sections() -> TestResult { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/tests/includes/extensions/extensions_queries.adoc"); + let options = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let parsed = support::registry().parse_file(&path, &options)?; + let query = parsed.query(); + let images: Vec<_> = query.select(BlockContext::Image).collect(); + assert_eq!(images.len(), 4); + assert!(images[0].containing_section().is_none()); + assert!(images[1].containing_section().is_some()); + assert!(images[2].containing_section().is_none()); + let source = images[3].source_location(); + assert!( + source + .file + .as_ref() + .is_some_and(|path| path.ends_with("includes/extensions/extension-query.adoc")) + ); + assert_eq!(source.location.start.line, 1); + let sections: Vec<_> = query.select(BlockContext::Section).collect(); + assert_eq!(sections.len(), 3); + assert!(sections[1].containing_section().is_none()); + assert_eq!(sections[2].containing_section(), Some(sections[0].target())); + assert_eq!(query.select(BlockContext::Example).count(), 2); + assert_eq!(query.select(BlockContext::Listing).count(), 1); + Ok(()) +} + +#[test] +fn extensions_ids_reject_blocks_without_anchor_storage() -> TestResult { + let mut parsed = + Registry::default().parse("Text.\n\n:mode: value\n\nAfter.", &Options::default())?; + let target = parsed + .query() + .select(BlockContext::DocumentAttribute) + .next() + .ok_or("missing attribute event")? + .target() + .clone(); + let before = serde_json::to_value(parsed.parsed.document_storage())?; + assert_eq!( + parsed.ensure_id(&target), + Err(TargetError::NotReferenceable) + ); + assert_eq!( + before, + serde_json::to_value(parsed.parsed.document_storage())? + ); + Ok(()) +} + +#[test] +fn extensions_ids_register_sections_with_empty_automatic_slugs() -> TestResult { + let mut parsed = + Registry::default().parse("= D\n:sectnums:\n\n== !!!\n\nBody.", &Options::default())?; + let target = parsed + .query() + .select(BlockContext::Section) + .next() + .ok_or("missing section")? + .target() + .clone(); + assert!( + parsed + .query() + .get(&target) + .ok_or("missing target")? + .output_id() + .is_none() + ); + let id = parsed.ensure_id(&target)?.to_owned(); + assert_ne!(id, ""); + let document = parsed.parsed.document_storage(); + let reference = document + .references + .get(id.as_str()) + .ok_or("missing section reference")?; + assert_eq!(reference.section_number(), Some("1")); + assert_eq!(reference.section_category(), Some("section")); + assert_eq!(document.toc_entries[0].id, id); + assert!(!document.references.contains_key("")); + assert!(matches!(&document.blocks[0], Block::Section(section) if section.id() == id)); + Ok(()) +} + +#[test] +fn extensions_section_ids_preserve_document_top_references() -> TestResult { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/tests/includes/extensions/extension-query-top.adoc"); + let mut parsed = Registry::default().parse_file(&path, &Options::default())?; + let top = parsed + .parsed + .document_storage() + .references + .get("") + .ok_or("missing document top")?; + assert_eq!(top.section_category(), None); + let before = + serde_json::json!({"title": top.title, "label": top.xreflabel, "location": top.location}); + let target = parsed + .query() + .select(BlockContext::Section) + .next() + .ok_or("missing section")? + .target() + .clone(); + parsed.ensure_id(&target)?; + let top = parsed + .parsed + .document_storage() + .references + .get("") + .ok_or("lost document top")?; + assert_eq!(top.section_category(), None); + assert_eq!( + serde_json::json!({"title": top.title, "label": top.xreflabel, "location": top.location}), + before + ); + Ok(()) +} + +#[test] +fn extensions_ids_reach_nested_containers_and_all_table_row_groups() -> TestResult { + let input = "====\nimage::example.svg[]\n====\n\n****\nimage::sidebar.svg[]\n****\n\n____\nimage::quote.svg[]\n____\n\n. Ordered\n+\nimage::ordered.svg[]\n\n[source]\n----\ncode <1>\n----\n<1> Explanation\n+\nimage::callout.svg[]\n\n[cols=\"a\",options=\"header,footer\"]\n|===\n|image::head.svg[]\n\n|image::body.svg[]\n\n|image::foot.svg[]\n|==="; + let mut parsed = Registry::default().parse(input, &Options::default())?; + let images = parsed + .query() + .select(BlockContext::Image) + .map(|view| { + let Block::Image(image) = view.storage() else { + return Err("image query returned another context"); + }; + Ok((view.target().clone(), image.source.to_string())) + }) + .collect::, _>>()?; + // Header cells contain inline text, not nested document blocks. + assert_eq!( + images + .iter() + .map(|(_, source)| source.as_str()) + .collect::>(), + [ + "example.svg", + "sidebar.svg", + "quote.svg", + "ordered.svg", + "callout.svg", + "body.svg", + "foot.svg" + ] + ); + for (target, _) in &images { + let id = parsed.ensure_id(target)?.to_owned(); + assert!( + parsed + .parsed + .document_storage() + .references + .contains_key(id.as_str()) + ); + assert_eq!( + parsed + .query() + .get(target) + .ok_or("missing image")? + .output_id(), + Some(id.as_str()) + ); + } + Ok(()) +} diff --git a/acdc-parser/src/extensions/tests/support.rs b/acdc-parser/src/extensions/tests/support.rs new file mode 100644 index 000000000..84fcbdffc --- /dev/null +++ b/acdc-parser/src/extensions/tests/support.rs @@ -0,0 +1,50 @@ +#![allow(clippy::expect_used)] + +use acdc_parser::{ + ElementAttributes, + extensions::{BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry}, +}; + +#[derive(Default)] +struct Record { + calls: usize, +} + +impl BlockMacroProcessor for Record { + fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result { + self.calls += 1; + let text = serde_json::json!({ + "call": self.calls, + "target": invocation.target, + "positional": invocation.positional, + "attributes": invocation.attributes, + "mode": invocation.document_attributes.get("mode").and_then(acdc_parser::DocumentAttributeValue::as_str), + }); + Ok(BlockMacroOutput::Paragraph(text.to_string())) + } +} + +pub(super) struct Defer; + +impl BlockMacroProcessor for Defer { + fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + Ok(BlockMacroOutput::Deferred) + } +} + +pub(super) fn registry() -> Registry { + let mut defaults = ElementAttributes::default(); + defaults.set("first".into(), "fallback".into()); + let mut builder = Registry::builder(); + builder + .register( + BlockMacro::new("record", Record::default) + .with_positional_attributes(["first", "second", "third"]) + .with_defaults(defaults), + ) + .expect("valid fixture macro"); + builder + .register(BlockMacro::new("defer", || Defer)) + .expect("valid fixture macro"); + builder.build() +} diff --git a/acdc-parser/src/extensions/traversal.rs b/acdc-parser/src/extensions/traversal.rs new file mode 100644 index 000000000..5ba35352e --- /dev/null +++ b/acdc-parser/src/extensions/traversal.rs @@ -0,0 +1,219 @@ +use crate::{Block, ColumnStyle, DelimitedBlockType, Table}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Children { + Body, + Item(usize), + Cell { + part: TablePart, + row: usize, + column: usize, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum TablePart { + Head, + Body, + Foot, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct BlockPath { + root: usize, + nested: Vec<(Children, usize)>, +} + +impl BlockPath { + pub(super) fn root(index: usize) -> Self { + Self { + root: index, + nested: Vec::new(), + } + } + + pub(super) fn child(&self, children: Children, index: usize) -> Self { + let mut path = self.clone(); + path.nested.push((children, index)); + path + } + + pub(super) fn get<'doc, 'a>(&self, blocks: &'doc [Block<'a>]) -> Option<&'doc Block<'a>> { + let mut block = blocks.get(self.root)?; + for &(children, index) in &self.nested { + block = children.get(block)?.get(index)?; + } + Some(block) + } + + pub(super) fn get_mut<'doc, 'a>( + &self, + blocks: &'doc mut [Block<'a>], + ) -> Option<&'doc mut Block<'a>> { + let mut block = blocks.get_mut(self.root)?; + for &(children, index) in &self.nested { + block = children.get_mut(block)?.get_mut(index)?; + } + Some(block) + } +} + +impl Children { + fn get<'doc, 'a>(self, block: &'doc Block<'a>) -> Option<&'doc [Block<'a>]> { + match (self, block) { + (Self::Body, Block::Section(block)) => Some(&block.content), + (Self::Body, Block::Admonition(block)) => Some(&block.blocks), + (Self::Body, Block::DelimitedBlock(block)) => compound(&block.inner), + (Self::Item(index), Block::UnorderedList(block)) => { + Some(&block.items.get(index)?.blocks) + } + (Self::Item(index), Block::OrderedList(block)) => Some(&block.items.get(index)?.blocks), + (Self::Item(index), Block::CalloutList(block)) => Some(&block.items.get(index)?.blocks), + (Self::Item(index), Block::DescriptionList(block)) => { + Some(&block.items.get(index)?.definition.as_ref()?.blocks) + } + (Self::Cell { part, row, column }, Block::DelimitedBlock(block)) => { + let DelimitedBlockType::DelimitedTable(table) = &block.inner else { + return None; + }; + let rows = match part { + TablePart::Head => table.header.as_slice(), + TablePart::Body => &table.rows, + TablePart::Foot => table.footer.as_slice(), + }; + Some(&rows.get(row)?.columns.get(column)?.content) + } + _ => None, + } + } + + fn get_mut<'doc, 'a>(self, block: &'doc mut Block<'a>) -> Option<&'doc mut Vec>> { + match (self, block) { + (Self::Body, Block::Section(block)) => Some(&mut block.content), + (Self::Body, Block::Admonition(block)) => Some(&mut block.blocks), + (Self::Body, Block::DelimitedBlock(block)) => match &mut block.inner { + DelimitedBlockType::DelimitedExample(blocks) + | DelimitedBlockType::DelimitedOpen(blocks) + | DelimitedBlockType::DelimitedSidebar(blocks) + | DelimitedBlockType::DelimitedQuote(blocks) => Some(blocks), + DelimitedBlockType::DelimitedComment(_) + | DelimitedBlockType::DelimitedListing(_) + | DelimitedBlockType::DelimitedLiteral(_) + | DelimitedBlockType::DelimitedTable(_) + | DelimitedBlockType::DelimitedPass(_) + | DelimitedBlockType::DelimitedVerse(_) + | DelimitedBlockType::DelimitedStem(_) => None, + }, + (Self::Item(index), Block::UnorderedList(block)) => { + Some(&mut block.items.get_mut(index)?.blocks) + } + (Self::Item(index), Block::OrderedList(block)) => { + Some(&mut block.items.get_mut(index)?.blocks) + } + (Self::Item(index), Block::CalloutList(block)) => { + Some(&mut block.items.get_mut(index)?.blocks) + } + (Self::Item(index), Block::DescriptionList(block)) => { + Some(&mut block.items.get_mut(index)?.definition.as_mut()?.blocks) + } + (Self::Cell { part, row, column }, Block::DelimitedBlock(block)) => { + let DelimitedBlockType::DelimitedTable(table) = &mut block.inner else { + return None; + }; + let rows = match part { + TablePart::Head => table.header.as_mut_slice(), + TablePart::Body => &mut table.rows, + TablePart::Foot => table.footer.as_mut_slice(), + }; + Some(&mut rows.get_mut(row)?.columns.get_mut(column)?.content) + } + _ => None, + } + } +} + +fn compound<'doc, 'a>(inner: &'doc DelimitedBlockType<'a>) -> Option<&'doc [Block<'a>]> { + match inner { + DelimitedBlockType::DelimitedExample(blocks) + | DelimitedBlockType::DelimitedOpen(blocks) + | DelimitedBlockType::DelimitedSidebar(blocks) + | DelimitedBlockType::DelimitedQuote(blocks) => Some(blocks), + DelimitedBlockType::DelimitedComment(_) + | DelimitedBlockType::DelimitedListing(_) + | DelimitedBlockType::DelimitedLiteral(_) + | DelimitedBlockType::DelimitedTable(_) + | DelimitedBlockType::DelimitedPass(_) + | DelimitedBlockType::DelimitedVerse(_) + | DelimitedBlockType::DelimitedStem(_) => None, + } +} + +pub(super) fn visit_children<'doc, 'a>( + block: &'doc Block<'a>, + mut visit: impl FnMut(Children, &'doc [Block<'a>]), +) { + match block { + Block::Section(block) => visit(Children::Body, &block.content), + Block::Admonition(block) => visit(Children::Body, &block.blocks), + Block::UnorderedList(block) => { + for (index, item) in block.items.iter().enumerate() { + visit(Children::Item(index), &item.blocks); + } + } + Block::OrderedList(block) => { + for (index, item) in block.items.iter().enumerate() { + visit(Children::Item(index), &item.blocks); + } + } + Block::CalloutList(block) => { + for (index, item) in block.items.iter().enumerate() { + visit(Children::Item(index), &item.blocks); + } + } + Block::DescriptionList(block) => { + for (index, item) in block.items.iter().enumerate() { + if let Some(definition) = &item.definition { + visit(Children::Item(index), &definition.blocks); + } + } + } + Block::DelimitedBlock(block) => { + if let Some(blocks) = compound(&block.inner) { + visit(Children::Body, blocks); + } + if let DelimitedBlockType::DelimitedTable(table) = &block.inner { + visit_table(table, visit); + } + } + Block::TableOfContents(_) + | Block::DiscreteHeading(_) + | Block::DocumentAttribute(_) + | Block::ThematicBreak(_) + | Block::PageBreak(_) + | Block::Paragraph(_) + | Block::Image(_) + | Block::Audio(_) + | Block::Video(_) + | Block::Comment(_) + | Block::Extension(_) => {} + } +} + +fn visit_table<'doc, 'a>( + table: &'doc Table<'a>, + mut visit: impl FnMut(Children, &'doc [Block<'a>]), +) { + for (part, rows) in [ + (TablePart::Head, table.header.as_slice()), + (TablePart::Body, table.rows.as_slice()), + (TablePart::Foot, table.footer.as_slice()), + ] { + for (row, value) in rows.iter().enumerate() { + for (column, cell) in value.columns.iter().enumerate() { + if cell.style == Some(ColumnStyle::AsciiDoc) { + visit(Children::Cell { part, row, column }, &cell.content); + } + } + } + } +} diff --git a/acdc-parser/src/grammar/attributes.rs b/acdc-parser/src/grammar/attributes.rs index b06c29a2f..d571910c1 100644 --- a/acdc-parser/src/grammar/attributes.rs +++ b/acdc-parser/src/grammar/attributes.rs @@ -106,9 +106,9 @@ pub(super) struct ResolvedContentAttribute<'a> { /// One slot of a confined attribute list, with byte offsets into its source. /// Also used by cross-references and links when their text holds attributes. #[derive(Debug)] -pub(super) struct ScannedAttribute { - pub(super) name: Option, - pub(super) value: String, +pub(crate) struct ScannedAttribute { + pub(crate) name: Option, + pub(crate) value: String, pub(super) quote: AttributeQuote, pub(super) value_start: usize, pub(super) value_end: usize, @@ -116,6 +116,10 @@ pub(super) struct ScannedAttribute { } impl ScannedAttribute { + pub(crate) fn is_unset(&self) -> bool { + self.quote == AttributeQuote::Unquoted && self.value == "None" + } + pub(super) fn resolve_content<'a>( &self, text: &'a str, @@ -481,3 +485,19 @@ pub(super) fn block_positional_style( pub(super) fn decode_anchor_shorthand_reftext(value: &str) -> String { decode_attribute_escapes(value, ']', CompatibilityMode::Draft, true).0 } + +pub(crate) fn extension_attributes( + state: &crate::grammar::ParserState<'_>, + arguments: &str, +) -> Vec { + let expanded = expand_attribute_list( + arguments, + &state.document_attributes, + state.options.compatibility_mode, + ); + scan_block_attribute_list( + &expanded.text, + state.options.compatibility_mode, + BlockAttributeMode::Macro, + ) +} diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index cc056dc95..a8f55f0f0 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -1539,6 +1539,7 @@ peg::parser! { block:( delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block } / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim } + / extension:extension_macro(start, offset, &block_metadata) { extension } / image:image(start, offset, &block_metadata) { image } / audio:audio(start, offset, &block_metadata) { audio } / video:video(start, offset, &block_metadata) { video } @@ -1596,6 +1597,7 @@ peg::parser! { ) { c }) { comment } / delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block } / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim } + / extension:extension_macro(start, offset, &block_metadata) { extension } / image:image(start, offset, &block_metadata) { image } / audio:audio(start, offset, &block_metadata) { audio } / video:video(start, offset, &block_metadata) { video } @@ -1927,6 +1929,34 @@ peg::parser! { / "mailto:" email_address() / path_match() + // Disabled extensions must not update PEG's expected-token diagnostics. + rule extensions_enabled() + = #{|_, position| if state.options.extensions.is_some() { + peg::RuleResult::Matched(position, ()) + } else { + peg::RuleResult::Failed + }} + + rule registered_macro_name() -> &'input str + = extensions_enabled() name:$(['a'..='z' | 'A'..='Z']['a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '-']*) "::" {? + let context = match state.block_context { + BlockContext::Document => crate::extensions::MacroContext::Document, + BlockContext::Compound => crate::extensions::MacroContext::Compound, + }; + if state.options.extensions.as_ref().and_then(|registry| registry.find(name)).is_some_and(|(_, descriptor)| descriptor.contexts.contains(&context)) { + Ok(name) + } else { Err("registered block macro") } + } + + rule extension_macro(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = name:registered_macro_name() target:$([^'[' | '\n' | '\r']*) + "[" arguments:attribute_list_content(BlockAttributeMode::Macro) end:position!() trailing:$([^'\n']*) { + if !trailing.trim().is_empty() { + state.add_warning(Warning::new(WarningKind::ContentRecovery { message: format!("trailing content after block macro {name}").into() }, Some(state.create_error_source_location(state.create_location(end + offset, span_end + offset))))); + } + crate::extensions::recognize(state, name, target, arguments, block_metadata.metadata.clone(), block_metadata.title.clone(), state.create_block_location(start, end, offset)) + } + rule image(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> = structural_block_boundaries(block_metadata) &media_block_ahead_true() "image::" source:source() attributes:cached_macro_attributes(block_metadata) end:position!() diff --git a/acdc-parser/src/grammar/document/references.rs b/acdc-parser/src/grammar/document/references.rs index 4ae2a52b7..01b2b1c41 100644 --- a/acdc-parser/src/grammar/document/references.rs +++ b/acdc-parser/src/grammar/document/references.rs @@ -646,6 +646,7 @@ pub(super) fn normalize_bibliography_lists<'a>(state: &ParserState<'a>, blocks: | Block::Video(_) | Block::TableOfContents(_) | Block::DocumentAttribute(_) + | Block::Extension(_) | Block::Comment(_) => {} } } diff --git a/acdc-parser/src/grammar/location_walk.rs b/acdc-parser/src/grammar/location_walk.rs index 7425fa36b..47ab89c5d 100644 --- a/acdc-parser/src/grammar/location_walk.rs +++ b/acdc-parser/src/grammar/location_walk.rs @@ -444,6 +444,10 @@ where self.inlines(block.title.inlines_mut())?; } Block::TableOfContents(block) => self.metadata(&mut block.metadata)?, + Block::Extension(block) => { + self.metadata(&mut block.metadata)?; + self.inlines(block.title.inlines_mut())?; + } Block::DocumentAttribute(_) | Block::Comment(_) => {} } Ok(()) diff --git a/acdc-parser/src/grammar/mod.rs b/acdc-parser/src/grammar/mod.rs index 40b243322..0165b1c1c 100644 --- a/acdc-parser/src/grammar/mod.rs +++ b/acdc-parser/src/grammar/mod.rs @@ -4,7 +4,7 @@ //! `inline_preprocessor`. Helpers used by one grammar live beside its PEG rules, //! grouped by purpose. Shared helpers, parser state, and source mapping stay here. -mod attributes; +pub(crate) mod attributes; mod brackets; mod character_references; mod document; diff --git a/acdc-parser/src/grammar/reference_walk.rs b/acdc-parser/src/grammar/reference_walk.rs index effe67583..6fde282f4 100644 --- a/acdc-parser/src/grammar/reference_walk.rs +++ b/acdc-parser/src/grammar/reference_walk.rs @@ -175,6 +175,7 @@ pub(crate) fn blocks<'a, V: ReferenceVisitor<'a>>( | Block::Video(_) | Block::TableOfContents(_) | Block::DocumentAttribute(_) + | Block::Extension(_) | Block::Comment(_) => {} } } diff --git a/acdc-parser/src/grammar/state.rs b/acdc-parser/src/grammar/state.rs index 44268af95..2562fe053 100644 --- a/acdc-parser/src/grammar/state.rs +++ b/acdc-parser/src/grammar/state.rs @@ -417,7 +417,7 @@ impl<'a> ParserState<'a> { /// (attribute substitution, escape unwrapping, …) and need to hand the /// result to the inline parser with the outer `'a` lifetime so that the /// resulting `InlineNode`s can be returned. - pub(super) fn intern_str(&self, s: &str) -> &'a str { + pub(crate) fn intern_str(&self, s: &str) -> &'a str { self.arena.alloc_str(s) } @@ -425,7 +425,7 @@ impl<'a> ParserState<'a> { /// into the arena; `Borrowed` values pass through unchanged (no copy) /// when their lifetime already outlives `'a`, which is the common case /// for substitution results that borrowed from the grammar input. - pub(super) fn intern_cow<'b>(&self, cow: Cow<'b, str>) -> &'a str + pub(crate) fn intern_cow<'b>(&self, cow: Cow<'b, str>) -> &'a str where 'b: 'a, { diff --git a/acdc-parser/src/lib.rs b/acdc-parser/src/lib.rs index a4eb496f6..96314202b 100644 --- a/acdc-parser/src/lib.rs +++ b/acdc-parser/src/lib.rs @@ -143,6 +143,9 @@ //! equivalent table dimension cap. //! +#[cfg(test)] +extern crate self as acdc_parser; + use std::{ cell::RefCell, path::{Path, PathBuf}, @@ -161,6 +164,7 @@ mod caption_repair; mod constants; mod document_attribute; mod error; +pub mod extensions; mod grammar; pub use grammar::footnotes::FootnoteRebuildError; mod model; @@ -380,7 +384,7 @@ pub fn parse_from_reader( let _span = tracing::info_span!("preprocess").entered(); Preprocessor::process_reader(reader, &options, Rc::clone(&warnings_handle))? }; - parse_input(result, options, None, warnings_handle) + parse_input(result, options, None, warnings_handle, None) } /// Parse `AsciiDoc` content from a string. @@ -423,6 +427,14 @@ pub fn parse_from_reader( /// Recoverable problems appear in the result's warnings. #[instrument(skip_all, fields(input_len = input.len(), safe_mode = ?options.safe_mode))] pub fn parse(input: &str, options: &Options<'_>) -> Result { + parse_with_session(input, options, None) +} + +fn parse_with_session( + input: &str, + options: &Options<'_>, + session: Option<&mut extensions::Session>, +) -> Result { let options = options .clone() .prepare_for_parse(document_attribute::InputKind::String); @@ -431,7 +443,7 @@ pub fn parse(input: &str, options: &Options<'_>) -> Result { let _span = tracing::info_span!("preprocess").entered(); Preprocessor::process(input, &options, Rc::clone(&warnings_handle))? }; - parse_input(result, options, None, warnings_handle) + parse_input(result, options, None, warnings_handle, session) } /// Parse `AsciiDoc` content from a file. @@ -463,23 +475,26 @@ pub fn parse(input: &str, options: &Options<'_>) -> Result { pub fn parse_file>( file_path: P, options: &Options<'_>, +) -> Result { + parse_file_with_session(file_path.as_ref(), options, None) +} + +fn parse_file_with_session( + file_path: &Path, + options: &Options<'_>, + session: Option<&mut extensions::Session>, ) -> Result { let options = options .clone() - .prepare_for_parse(document_attribute::InputKind::File(file_path.as_ref())); - let path = file_path.as_ref().to_path_buf(); - let raw = preprocessor::read_and_decode_file(file_path.as_ref(), None)?; + .prepare_for_parse(document_attribute::InputKind::File(file_path)); + let path = file_path.to_path_buf(); + let raw = preprocessor::read_and_decode_file(file_path, None)?; let warnings_handle: Rc> = Rc::default(); let result = { let _span = tracing::info_span!("preprocess").entered(); - Preprocessor::process_with_file( - &raw, - file_path.as_ref(), - &options, - Rc::clone(&warnings_handle), - )? + Preprocessor::process_with_file(&raw, file_path, &options, Rc::clone(&warnings_handle))? }; - parse_input(result, options, Some(path), warnings_handle) + parse_input(result, options, Some(path), warnings_handle, session) } /// Helper to convert a PEG parse error to our `SourceLocation` type, @@ -514,6 +529,7 @@ fn parse_input( mut options: Options<'_>, file_path: Option, warnings_handle: Rc>, + session: Option<&mut extensions::Session>, ) -> Result { if let Some(front_matter) = result.front_matter { options @@ -564,6 +580,12 @@ fn parse_input( let result = match grammar::document_parser::document(&owner.source, &mut state) { Ok(Ok(mut doc)) => { grammar::reference_text::finish_document(&mut state, &mut doc)?; + if let Some(session) = session + && session.process(&mut doc, &state)? + { + doc.renumber_captions(); + extensions::finalization::repair_macros(&mut doc)?; + } // Rewrite every node's location from preprocessed coordinates to the // original source (file + line + byte offset). No-op when the // preprocessor recorded no ranges (no includes/edits). diff --git a/acdc-parser/src/model/caption.rs b/acdc-parser/src/model/caption.rs index cf8a9da62..5ae919e0d 100644 --- a/acdc-parser/src/model/caption.rs +++ b/acdc-parser/src/model/caption.rs @@ -97,6 +97,7 @@ impl CaptionKind { | BlockKind::Passthrough(_) | BlockKind::Quote(_) | BlockKind::Verse(_) + | BlockKind::Extension(_) | BlockKind::Stem(_) => None, } } @@ -396,6 +397,7 @@ fn visit_captions(blocks: &[Block<'_>], visit: &mut impl FnMut(&Caption<'_>)) { | Block::Audio(_) | Block::Video(_) | Block::DocumentAttribute(_) + | Block::Extension(_) | Block::Comment(_) => {} } } @@ -469,6 +471,7 @@ fn renumber_children(block: &mut Block<'_>, counters: &mut CaptionCounters) { | Block::Audio(_) | Block::Video(_) | Block::DocumentAttribute(_) + | Block::Extension(_) | Block::Comment(_) => {} } } diff --git a/acdc-parser/src/model/mod.rs b/acdc-parser/src/model/mod.rs index 4f62d304d..4f528de6a 100644 --- a/acdc-parser/src/model/mod.rs +++ b/acdc-parser/src/model/mod.rs @@ -537,6 +537,7 @@ pub struct Comment<'a> { #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(untagged)] pub enum Block<'a> { + Extension(Box>), TableOfContents(TableOfContents<'a>), // TODO(nlopes): we shouldn't have an admonition type here, instead it should be // picked up from the style attribute from the block metadata. @@ -566,6 +567,7 @@ impl<'a> Block<'a> { #[must_use] pub fn location(&self) -> &Location { match self { + Block::Extension(e) => &e.location, Block::Section(s) => &s.location, Block::Paragraph(p) => &p.location, Block::UnorderedList(l) => &l.location, @@ -604,6 +606,7 @@ impl<'a> Block<'a> { #[must_use] pub(crate) fn metadata(&self) -> Option<&BlockMetadata<'a>> { match self { + Block::Extension(e) => Some(&e.metadata), Block::Section(block) => Some(&block.metadata), Block::DelimitedBlock(block) => Some(&block.metadata), Block::Admonition(block) => Some(&block.metadata), @@ -625,6 +628,7 @@ impl<'a> Block<'a> { /// This block's metadata, for the blocks that carry any. pub(crate) fn metadata_mut(&mut self) -> Option<&mut BlockMetadata<'a>> { match self { + Block::Extension(e) => Some(&mut e.metadata), Block::Section(block) => Some(&mut block.metadata), Block::DelimitedBlock(block) => Some(&mut block.metadata), Block::Admonition(block) => Some(&mut block.metadata), @@ -646,6 +650,7 @@ impl<'a> Block<'a> { /// The authored anchor selected as this block's cross-reference target. pub(crate) fn anchor(&self) -> Option<&Anchor<'a>> { match self { + Block::Extension(e) => e.metadata.id_anchor(), Block::Section(b) => b.metadata.id_anchor(), Block::DelimitedBlock(b) => b.metadata.id_anchor(), Block::Admonition(b) => b.metadata.id_anchor(), @@ -669,6 +674,7 @@ impl<'a> Block<'a> { /// text when an `<>` to this block has no explicit label). pub(crate) fn title(&self) -> Option<&Title<'a>> { let title = match self { + Block::Extension(e) => &e.title, Block::Section(b) => &b.title, Block::DelimitedBlock(b) => &b.title, Block::Admonition(b) => &b.title, @@ -696,6 +702,7 @@ impl Block<'_> { /// pass rewrites it). Counterpart to [`Self::location`]. pub(crate) fn location_mut(&mut self) -> &mut Location { match self { + Block::Extension(e) => &mut e.location, Block::Section(s) => &mut s.location, Block::Paragraph(p) => &mut p.location, Block::UnorderedList(l) => &mut l.location, diff --git a/acdc-parser/src/model/section.rs b/acdc-parser/src/model/section.rs index f2f53afc3..ead531c56 100644 --- a/acdc-parser/src/model/section.rs +++ b/acdc-parser/src/model/section.rs @@ -457,6 +457,10 @@ impl<'a> Section<'a> { !self.numbering.enabled && self.numbering.number.is_none() } + pub(crate) fn preserve_toc_number(&self, entry: &mut TocEntry<'_>) { + entry.set_number(self.numbering.number.clone()); + } + /// Return the assigned number without presentation punctuation or a signifier. /// /// Examples are `1`, `1.2`, `IV`, and `A.1`. @@ -641,6 +645,24 @@ fn update_section_reference( } } +/// Capture reference numbers, including numbers hidden by `sectnumlevels`. +/// The caller must run this before its first structural edit. +pub(crate) fn extension_reference_numbers( + blocks: &mut [Block<'_>], + is_book: bool, +) -> Vec { + let mut references = Vec::new(); + let mut state = NumberingState::default(); + let mut record = |_: &Section<'_>, numbers: SectionNumbers, name, _: bool| { + references.push(SectionReference { + name, + number: numbers.reference, + }); + }; + renumber_blocks(blocks, &mut state, is_book, false, true, &mut record); + references +} + /// Assign numbers after parsing, matching ordered TOC entries by source location. pub(crate) fn number_parsed_sections<'a>( blocks: &mut [Block<'a>], @@ -802,6 +824,7 @@ fn renumber_blocks<'a, F>( | Block::Image(_) | Block::Audio(_) | Block::Video(_) + | Block::Extension(_) | Block::Comment(_) => {} } } diff --git a/acdc-parser/src/options.rs b/acdc-parser/src/options.rs index c7c442972..301812018 100644 --- a/acdc-parser/src/options.rs +++ b/acdc-parser/src/options.rs @@ -106,6 +106,7 @@ pub(crate) enum FileXrefMode { #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct Options<'a> { + pub(crate) extensions: Option, /// Defaults to [`CompatibilityMode::Asciidoctor`]. Independent of ASG export. pub compatibility_mode: CompatibilityMode, /// Defaults to [`SafeMode::Secure`], which prevents include reads. @@ -226,6 +227,7 @@ impl<'a> Options<'a> { base_dir: self.base_dir, strict: self.strict, file_xref_mode: self.file_xref_mode, + extensions: self.extensions, } } @@ -253,6 +255,7 @@ impl<'a> Options<'a> { base_dir: self.base_dir, strict: self.strict, file_xref_mode: self.file_xref_mode, + extensions: self.extensions, } } } @@ -277,6 +280,7 @@ impl<'a> Options<'a> { #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct OptionsBuilder<'a> { + extensions: Option, compatibility_mode: CompatibilityMode, safe_mode: SafeMode, timings: bool, @@ -557,6 +561,7 @@ impl<'a> OptionsBuilder<'a> { base_dir: self.base_dir, strict: self.strict, file_xref_mode: self.file_xref_mode, + extensions: self.extensions, }) } } diff --git a/acdc-parser/src/parsed.rs b/acdc-parser/src/parsed.rs index 4b03a4920..1f40d54bc 100644 --- a/acdc-parser/src/parsed.rs +++ b/acdc-parser/src/parsed.rs @@ -222,11 +222,40 @@ impl ParseResult { crate::ast::DocumentRef::from(self.cell.borrow_dependent()) } - #[cfg(test)] pub(crate) fn document_storage(&self) -> &Document<'_> { self.cell.borrow_dependent() } + pub(crate) fn with_document_mut( + &mut self, + edit: impl for<'a> FnOnce(&'a OwnedInput, &mut Document<'a>) -> R, + ) -> R { + self.cell.with_dependent_mut(edit) + } + + pub(crate) fn replace_reference_warnings(&mut self, warnings: Vec) { + self.warnings.retain(|warning| { + !matches!( + warning.kind, + WarningKind::UnresolvedReference { .. } | WarningKind::DuplicateId { .. } + ) + }); + let mut combined = WarningCollection::default(); + for warning in std::mem::take(&mut self.warnings) { + combined.push(warning); + } + for mut warning in warnings { + if let Some(source) = &mut warning.location { + *source = self.source_location(&source.location); + } + if let WarningKind::DuplicateId { first, .. } = &mut warning.kind { + **first = self.source_location(&first.location); + } + combined.push_unique_from(warning, 0); + } + self.warnings = combined.into_vec(); + } + /// Borrow the preprocessed source the AST was parsed from. /// /// Note: this is the text as seen by the grammar, after include diff --git a/acdc-parser/src/proptests/invariants.rs b/acdc-parser/src/proptests/invariants.rs index ef7742786..62b5bb941 100644 --- a/acdc-parser/src/proptests/invariants.rs +++ b/acdc-parser/src/proptests/invariants.rs @@ -309,6 +309,7 @@ fn walk_block_locations(block: &Block, visitor: &mut impl FnMut(&Location, &str) | Block::Image(_) | Block::Audio(_) | Block::Video(_) + | Block::Extension(_) | Block::Comment(_) => {} } } @@ -550,6 +551,7 @@ fn verify_block_monotonic(block: &Block) { | Block::Image(_) | Block::Audio(_) | Block::Video(_) + | Block::Extension(_) | Block::Comment(_) => {} } } diff --git a/acdc-parser/src/reference_repair.rs b/acdc-parser/src/reference_repair.rs index 3df69935e..fc805f562 100644 --- a/acdc-parser/src/reference_repair.rs +++ b/acdc-parser/src/reference_repair.rs @@ -16,6 +16,7 @@ struct RebuiltReferences<'a> { occurrences: Occurrences, automatic: Vec<&'a str>, needs_document_top: bool, + preserve_numbers: bool, } impl<'a> ReferenceVisitor<'a> for RebuiltReferences<'a> { @@ -65,6 +66,9 @@ impl<'a> ReferenceVisitor<'a> for RebuiltReferences<'a> { section.heading_location.clone(), ); entry.occurrence = Some(occurrence); + if self.preserve_numbers { + section.preserve_toc_number(&mut entry); + } self.toc.push(entry); } Ok(()) @@ -204,12 +208,21 @@ impl Document<'_> { /// Returns an error without changing the document if a section has no assigned /// or explicit ID, or a document reference label lacks prepared attribute context. pub fn rebuild_references_and_toc(&mut self) -> Result<(), ReferenceRepairError> { + self.rebuild_membership(true) + } + + pub(crate) fn rebuild_extension_references(&mut self) -> Result<(), ReferenceRepairError> { + self.rebuild_membership(false) + } + + fn rebuild_membership(&mut self, renumber: bool) -> Result<(), ReferenceRepairError> { let mut rebuilt = RebuiltReferences { entries: HashMap::new(), toc: Vec::new(), occurrences: Occurrences::default(), automatic: Vec::new(), needs_document_top: false, + preserve_numbers: !renumber, }; if let Some(header) = &self.header { reference_walk::header(&mut rebuilt, header)?; @@ -261,9 +274,25 @@ impl Document<'_> { true, ) .unwrap_or_else(|never| match never {}); + if !renumber { + let previous: HashMap<_, _> = self + .references + .values() + .filter_map(|reference| { + Some((reference.occurrence.as_ref()?, reference.section.as_ref()?)) + }) + .collect(); + for reference in rebuilt.entries.values_mut() { + if let Some(occurrence) = &reference.occurrence { + reference.section = previous.get(occurrence).map(|section| (*section).clone()); + } + } + } self.references = rebuilt.entries; self.toc_entries = rebuilt.toc; - self.renumber_sections(); + if renumber { + self.renumber_sections(); + } Ok(()) } } diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs new file mode 100644 index 000000000..85ff4d8a8 --- /dev/null +++ b/acdc-parser/tests/extensions.rs @@ -0,0 +1,83 @@ +use acdc_parser::{ + CompatibilityMode, Error, Options, ParseResult, + ast::{BlockKind, InlineKind}, + extensions::{ + BlockContext, BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry, + }, +}; + +type TestResult = Result<(), Box>; + +struct Defer; +impl BlockMacroProcessor for Defer { + fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + Ok(BlockMacroOutput::Deferred) + } +} + +#[test] +fn extensions_finish_checks_pending_requests_and_returns_normal_parse_result() -> TestResult { + fn require_send(_: impl Send) {} + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("request", || Defer))?; + let pending = builder.build().parse("request::[]", &options)?; + let error = pending + .finish() + .err() + .ok_or("expected unresolved request")?; + assert!(matches!(error, Error::Extension(..))); + assert_eq!( + error + .source_location() + .map(|source| source.location.start.line), + Some(1) + ); + let parsed: ParseResult = Registry::default() + .parse("Ordinary content.", &options)? + .finish()?; + require_send(parsed); + } + Ok(()) +} + +#[test] +fn extensions_typed_queries_preserve_prepared_reference_labels() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = Registry::default().parse(":label: Early\n\n.A *formatted* title\n[reftext='{label} *label*']\nimage::one.svg[]\n\n:label: Late", &options)?; + let target = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")? + .target() + .clone(); + let id = result.ensure_id(&target)?.to_owned(); + let query = result.query(); + let image = query.get(&target).ok_or("target")?; + assert!(matches!(image.block().kind(), BlockKind::Image(_))); + assert!(image.title().is_some_and(|title| { + title + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + })); + assert!(image.attributes().is_some()); + let parsed = result.finish()?; + let label = parsed + .document() + .references() + .get(&id) + .ok_or("reference")? + .xreflabel() + .ok_or("label")?; + assert!( + label + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + ); + assert_eq!(parsed.warnings(), []); + } + Ok(()) +} diff --git a/converters/html/src/delimited.rs b/converters/html/src/delimited.rs index 62e1c5bf8..0e021a265 100644 --- a/converters/html/src/delimited.rs +++ b/converters/html/src/delimited.rs @@ -473,7 +473,7 @@ impl<'a, W: Write> HtmlVisitor<'a, '_, W> { | BlockKind::Comment(_) => { return Err(unsupported_delimited_block(block)); } - _ => return Err(unsupported_delimited_block(block)), + BlockKind::Extension(_) | _ => return Err(unsupported_delimited_block(block)), } Ok(()) } diff --git a/converters/html/src/html_visitor.rs b/converters/html/src/html_visitor.rs index 722627b69..bcc14de48 100644 --- a/converters/html/src/html_visitor.rs +++ b/converters/html/src/html_visitor.rs @@ -780,7 +780,7 @@ impl<'a, W: Write> BlockVisitor<'a> for HtmlVisitor<'a, '_, W> { | BlockKind::Stem(_) | BlockKind::Table(_) | BlockKind::DelimitedComment(_) => self.visit_delimited_block_ref(context, block), - _ => { + BlockKind::Extension(_) | _ => { self.warn_unhandled_block(); Ok(()) } diff --git a/converters/manpage/src/manpage_visitor.rs b/converters/manpage/src/manpage_visitor.rs index 6692df47a..15b7cd0d3 100644 --- a/converters/manpage/src/manpage_visitor.rs +++ b/converters/manpage/src/manpage_visitor.rs @@ -318,7 +318,7 @@ impl<'a, W: Write> BlockVisitor<'a> for ManpageVisitor<'a, '_, W> { | BlockKind::Table(_) | BlockKind::Stem(_) | BlockKind::DelimitedComment(_) => self.render_delimited_block(traversal, block), - _ => { + BlockKind::Extension(_) | _ => { self.visit_unhandled_block(traversal, block); Ok(()) } diff --git a/converters/markdown/src/markdown_visitor.rs b/converters/markdown/src/markdown_visitor.rs index a92041fb4..450c23e4e 100644 --- a/converters/markdown/src/markdown_visitor.rs +++ b/converters/markdown/src/markdown_visitor.rs @@ -3201,7 +3201,7 @@ impl<'a, W: Write> BlockVisitor<'a> for MarkdownVisitor<'a, '_, W> { | BlockKind::Quote(_) | BlockKind::Verse(_) | BlockKind::Stem(_) => self.visit_compound_block(traversal, block), - _ => { + BlockKind::Extension(_) | _ => { self.visit_unhandled_block(traversal, block); Ok(()) } diff --git a/converters/pdf/src/visitor.rs b/converters/pdf/src/visitor.rs index a6e3042da..8dd166090 100644 --- a/converters/pdf/src/visitor.rs +++ b/converters/pdf/src/visitor.rs @@ -238,7 +238,7 @@ impl<'a> BlockVisitor<'a> for PdfVisitor<'a, '_, '_> { | BlockKind::Table(_) | BlockKind::Stem(_) | BlockKind::DelimitedComment(_) => self.visit_delimited_block(traversal, block), - _ => { + BlockKind::Extension(_) | _ => { self.warn_unsupported_parser_variant("block", None); Ok(()) } diff --git a/converters/terminal/src/terminal_visitor.rs b/converters/terminal/src/terminal_visitor.rs index 33d8a7cf0..2ecccac45 100644 --- a/converters/terminal/src/terminal_visitor.rs +++ b/converters/terminal/src/terminal_visitor.rs @@ -298,7 +298,7 @@ impl<'a, W: Write> BlockVisitor<'a> for TerminalVisitor<'a, '_, W> { | BlockKind::Table(_) | BlockKind::Stem(_) | BlockKind::DelimitedComment(_) => self.render_delimited_block(traversal, block), - _ => { + BlockKind::Extension(_) | _ => { self.visit_unhandled_block(traversal, block); Ok(()) } From 402a49f7048f83b187c83b856289a1094d299b19 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Wed, 11 Nov 2026 13:49:36 +0100 Subject: [PATCH 02/55] feat(parser): add ordered tree processors and checked document edits Run document-local tree processors in registration order through a scoped editor. Build literal paragraphs and lists, insert content, replace pending requests, and remove sections while preserving stable target handles. Repair references, TOC membership, scoped footnotes, and diagnostics without rerunning callbacks or renumbering surviving sections and captions. Cover the public finalization and HTML conversion paths in both compatibility modes. Validation: 12,416 workspace tests and 118 doctests passed; strict Clippy, formatting, feature-off parser/HTML checks, and whitespace checks passed. 1 workspace test skipped; 5 doctests ignored. Refs: SC-256 --- ARCHITECTURE.adoc | 7 +- acdc-parser/CHANGELOG.md | 17 +- acdc-parser/README.adoc | 11 +- acdc-parser/README.md | 11 +- .../extensions/extension-tree-captions.adoc | 29 + .../extensions/extension-tree-error.adoc | 3 + .../extensions/extension-tree-nested.adoc | 37 + .../extensions/extension-tree-numbering.adoc | 25 + acdc-parser/src/extensions/builder.rs | 101 +++ acdc-parser/src/extensions/editor.rs | 280 ++++++++ acdc-parser/src/extensions/mod.rs | 49 +- acdc-parser/src/extensions/query.rs | 63 +- acdc-parser/src/extensions/registry.rs | 41 +- acdc-parser/src/extensions/session.rs | 9 +- acdc-parser/src/extensions/tests/mod.rs | 3 + .../src/extensions/tests/tree_processors.rs | 659 ++++++++++++++++++ acdc-parser/src/extensions/traversal.rs | 43 ++ acdc-parser/src/extensions/tree_processor.rs | 47 ++ acdc-parser/tests/extensions.rs | 146 +++- .../html/tests/typed_document_entrypoints.rs | 77 +- 20 files changed, 1624 insertions(+), 34 deletions(-) create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extension-tree-captions.adoc create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extension-tree-error.adoc create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extension-tree-nested.adoc create mode 100644 acdc-parser/fixtures/tests/includes/extensions/extension-tree-numbering.adoc create mode 100644 acdc-parser/src/extensions/builder.rs create mode 100644 acdc-parser/src/extensions/editor.rs create mode 100644 acdc-parser/src/extensions/tests/tree_processors.rs create mode 100644 acdc-parser/src/extensions/tree_processor.rs diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc index fcb59e3eb..1558ebfe4 100644 --- a/ARCHITECTURE.adoc +++ b/ARCHITECTURE.adoc @@ -92,11 +92,12 @@ The parser owns an optional registry of block-macro descriptors and factories. Recognition records invocations and their source-position attributes without calling extension code. Once the complete document is accepted, the host runs macros once in document order, then repairs prepared captions and catalogs. +Tree processors run once in registration order through a scoped editor. Queries return the same typed views as ordinary parser consumers, plus stable -handles for ID assignment. Reference and footnote repair reuse the shared prepared -content services. The host allocates generated literal text without reparsing it -or storing backend markup. +handles for checked edits. Reference and footnote repair reuse the shared prepared +content services. Extension edits preserve surviving numbering. The host allocates +generated text; builders do not reparse it or store backend markup. The working session retains deferred requests and document-local processors. Its checked `finish()` operation rejects unresolved requests and returns the diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 30d70a9ca..35945eb81 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -185,13 +185,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ordered, unordered, and description list items in both compatibility modes, matching Asciidoctor. Only a standalone `+` acts as a list continuation. -- Applications can register block macros with `extensions::Registry`. Each - document has fresh processor state. Typed queries cover nested containers and - discrete headings. Stable target handles support collision-free ID assignment. - Generated paragraphs contain literal text. Call `ExtensionParseResult::finish()` - before conversion or checked ASG export; unresolved requests return a located - error. Callbacks run after parsing and cannot change later includes or - conditionals, unlike source-changing Asciidoctor extensions. +- Applications can register block macros and ordered tree processors with + `extensions::Registry`. Each document has fresh processor state. Typed queries + cover nested containers and discrete headings. Stable target handles support + ID assignment, literal paragraphs and lists, placeholder replacement and + section removal. Edits repair references, TOC and scoped footnotes while + preserving surviving section and caption numbers. + Call `ExtensionParseResult::finish()` before conversion or checked ASG export; + unresolved requests return a located error. Callbacks run after parsing and + cannot change later includes or conditionals, unlike source-changing + Asciidoctor extensions. - Faster parsing of paragraphs, mixed ASCII and Unicode text, formatting, inline passthroughs, and duplicated ordinary table cells (`3*|text`) in both diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 08aa1fa08..a7da280fa 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2055,17 +2055,18 @@ to preserve their isolation. The fixture runner's case names are unchanged. [#registered-extensions] == Registered extensions -Applications can register block macros with +Applications can register block macros and ordered tree processors with `extensions::Registry`. Each parse creates fresh processor instances. Callbacks run once after the document is accepted and cannot change later includes, conditionals, or parsing. This differs from source-changing Asciidoctor extensions. Both compatibility modes support registrations. Use `query()` to inspect typed block, content, attribute, and caption views. -Document-local `TargetId` handles identify targets independently of their output -IDs. Use `ensure_id()` to preserve existing IDs or assign collision-free IDs -without rerunning macro processors. Generated paragraphs contain literal text -and are not reparsed. +Document-local `TargetId` handles survive insertions and placeholder replacement; +removed handles cannot bind to another block. The scoped `DocumentEditor` builds +literal paragraphs and lists, assigns IDs, replaces requests, and removes sections. +Edits repair catalogs and scoped footnotes while preserving surviving section and +caption numbers. Generated text is literal and is not reparsed. Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used for conversion or serialization. It rejects unresolved deferred requests at their diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 4c21df371..f3a4dc479 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1699,17 +1699,18 @@ to preserve their isolation. The fixture runner's case names are unchanged. ## Registered extensions -Applications can register block macros with +Applications can register block macros and ordered tree processors with `extensions::Registry`. Each parse creates fresh processor instances. Callbacks run once after the document is accepted and cannot change later includes, conditionals, or parsing. This differs from source-changing Asciidoctor extensions. Both compatibility modes support registrations. Use `query()` to inspect typed block, content, attribute, and caption views. -Document-local `TargetId` handles identify targets independently of their output -IDs. Use `ensure_id()` to preserve existing IDs or assign collision-free IDs -without rerunning macro processors. Generated paragraphs contain literal text -and are not reparsed. +Document-local `TargetId` handles survive insertions and placeholder replacement; +removed handles cannot bind to another block. The scoped `DocumentEditor` builds +literal paragraphs and lists, assigns IDs, replaces requests, and removes sections. +Edits repair catalogs and scoped footnotes while preserving surviving section and +caption numbers. Generated text is literal and is not reparsed. Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used for conversion or serialization. It rejects unresolved deferred requests at their diff --git a/acdc-parser/fixtures/tests/includes/extensions/extension-tree-captions.adoc b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-captions.adoc new file mode 100644 index 000000000..709505dc4 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-captions.adoc @@ -0,0 +1,29 @@ +[#gone] +== Removed + +.First example +==== +Removed +==== + +== Kept + +[#survivor] +.Second example +==== +Kept +==== + +:example-caption: Early + +[#custom] +.Custom example +[example,caption="Custom "] +defer::custom[] + +[#automatic] +.New example +[example] +defer::automatic[] + +:example-caption: Late diff --git a/acdc-parser/fixtures/tests/includes/extensions/extension-tree-error.adoc b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-error.adoc new file mode 100644 index 000000000..eb85ae1d8 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-error.adoc @@ -0,0 +1,3 @@ +Included content. + +defer::fail[] diff --git a/acdc-parser/fixtures/tests/includes/extensions/extension-tree-nested.adoc b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-nested.adoc new file mode 100644 index 000000000..23e1c0389 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-nested.adoc @@ -0,0 +1,37 @@ +== Outer + +* List item ++ +==== +defer::list[] +==== + +term:: Description ++ +defer::description[] + +[NOTE] +==== +defer::admonition[] +==== + +____ +defer::quote[] +____ + +[cols="a",options="footer"] +|=== +a| +[#cell-remove] +== Removed cell section + +defer::cell-remove[] + +[#cell-keep] +== Kept cell section + +[#cell-keep-content] +defer::cell-keep[] + +a|defer::footer[] +|=== diff --git a/acdc-parser/fixtures/tests/includes/extensions/extension-tree-numbering.adoc b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-numbering.adoc new file mode 100644 index 000000000..b4fb22595 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/extension-tree-numbering.adoc @@ -0,0 +1,25 @@ += Editor probe +:sectnums: +:toc: + +[#gone] +== Remove + +[[inline-gone]]Removed footnote:[removed]. See <>. + +[#figure-gone] +.Removed figure +image::removed.svg[] + +=== Removed child + +Content. + +[#stay] +== Keep + +[#figure-stay] +.Kept figure +image::kept.svg[] + +Kept footnote:[kept]. See <> and <>. diff --git a/acdc-parser/src/extensions/builder.rs b/acdc-parser/src/extensions/builder.rs new file mode 100644 index 000000000..37fe220ad --- /dev/null +++ b/acdc-parser/src/extensions/builder.rs @@ -0,0 +1,101 @@ +use bumpalo::Bump; + +use crate::{ + Anchor, Block, BlockMetadata, CaptionKind, InlineNode, ListItem, Location, Paragraph, Plain, + Title, UnorderedList, +}; + +/// Ordinary content whose strings are allocated by the document host. +/// +/// Text is literal. Converters apply the block's normal output policies. +/// Construction does not invoke inline parsing, attribute substitution, or +/// extension callbacks. +#[derive(Debug)] +pub struct BlockBuilder { + content: Content, + pub(super) id: Option, +} + +#[derive(Debug)] +enum Content { + Paragraph(String), + UnorderedList(Vec), +} + +impl BlockBuilder { + pub(super) fn caption_kind(&self, style: Option<&str>) -> Option { + match &self.content { + Content::Paragraph(_) => CaptionKind::for_style(style), + Content::UnorderedList(_) => None, + } + } + + /// Build a paragraph of literal text. + #[must_use] + pub fn paragraph(text: impl Into) -> Self { + Self { + content: Content::Paragraph(text.into()), + id: None, + } + } + + /// Build an unordered list whose items contain literal text. + #[must_use] + pub fn unordered_list(items: impl IntoIterator>) -> Self { + Self { + content: Content::UnorderedList(items.into_iter().map(Into::into).collect()), + id: None, + } + } + + /// Request an explicit output ID. The editor rejects empty or duplicate IDs. + #[must_use] + pub fn with_id(mut self, id: impl Into) -> Self { + self.id = Some(id.into()); + self + } + + pub(super) fn build<'a>( + self, + arena: &'a Bump, + location: Location, + mut metadata: BlockMetadata<'a>, + title: Title<'a>, + ) -> Block<'a> { + if let Some(id) = self.id { + metadata.id = Some(Anchor::new(arena.alloc_str(&id), location.clone())); + } + let plain = |text: &str| { + vec![InlineNode::PlainText(Plain { + content: arena.alloc_str(text), + location: location.clone(), + escaped: true, + })] + }; + match self.content { + Content::Paragraph(text) => { + let mut block = Paragraph::new(plain(&text), location); + block.metadata = metadata; + block.title = title; + Block::Paragraph(block) + } + Content::UnorderedList(items) => Block::UnorderedList(UnorderedList { + title, + metadata, + items: items + .into_iter() + .map(|text| ListItem { + level: 1, + marker: "*", + checked: None, + principal: plain(&text), + blocks: Vec::new(), + location: location.clone(), + }) + .collect(), + marker: "*", + location, + }), + } + } +} diff --git a/acdc-parser/src/extensions/editor.rs b/acdc-parser/src/extensions/editor.rs new file mode 100644 index 000000000..dc98e1293 --- /dev/null +++ b/acdc-parser/src/extensions/editor.rs @@ -0,0 +1,280 @@ +use crate::{Block, BlockMetadata, Caption, Error, SourceLocation, Title}; + +use super::{ + BlockBuilder, DeferredBlock, DocumentQuery, ExtensionParseResult, TargetId, + traversal::BlockPath, +}; + +/// Scoped access to queries, builders, and checked structural edits. +/// +/// Every edit repairs catalogs before the next query. Surviving targets keep +/// their handles and section/caption numbers; removed handles never become live +/// again, even if a new block uses the same output ID. Footnotes are compacted. +pub struct DocumentEditor<'doc> { + result: &'doc mut ExtensionParseResult, +} + +impl<'doc> DocumentEditor<'doc> { + pub(super) const fn new(result: &'doc mut ExtensionParseResult) -> Self { + Self { result } + } + + #[must_use] + pub fn query(&self) -> DocumentQuery<'_> { + self.result.query() + } + + #[cfg(test)] + pub(super) fn document_storage(&self) -> &crate::Document<'_> { + self.result.parsed.document_storage() + } + + /// Pending requests whose placeholders are still in the document. + #[must_use] + pub fn deferred_blocks(&self) -> &[DeferredBlock] { + self.result.deferred_blocks() + } + + /// Assign or return an output ID without changing block identity or numbering. + /// + /// # Errors + /// Rejects foreign, removed, or unreferenceable targets. + pub fn ensure_id(&mut self, target: &TargetId) -> Result<&str, Error> { + let location = self.location(target); + self.result + .ensure_id(target) + .map_err(|error| Error::Extension(Box::new(location), error.to_string())) + } + + /// Insert ordinary content immediately before a target in its own container. + /// + /// The new block uses the target's source location and receives a new handle. + /// + /// # Errors + /// Rejects foreign/removed targets and empty or duplicate requested IDs. + pub fn insert_before( + &mut self, + target: &TargetId, + content: BlockBuilder, + ) -> Result { + let path = self.path(target)?; + self.validate_id(target, &content, false)?; + self.prepare_edit(); + let location = self.location(target); + self.result.parsed.with_document_mut(|owner, document| { + let block = content.build( + &owner.arena, + location.location.clone(), + BlockMetadata::default(), + Title::default(), + ); + let (blocks, position) = path.container_mut(&mut document.blocks).ok_or_else(|| { + Error::Extension(Box::new(location.clone()), "target is absent".into()) + })?; + blocks.insert(position, block); + Ok::<(), Error>(()) + })?; + let new_target = self + .result + .targets + .get_mut() + .and_then(|index| index.insert_before(target)) + .ok_or_else(|| self.error(target, "target is absent"))?; + self.result.repair_after_edit()?; + Ok(new_target) + } + + /// Replace a pending placeholder, retaining its handle, source, title, and metadata. + /// A builder-supplied ID overrides the placeholder's ID. + /// + /// The request is consumed. The replacement invokes no parsing or callbacks. + /// + /// # Errors + /// Rejects targets that are not pending placeholders and invalid requested IDs. + pub fn replace_placeholder( + &mut self, + target: &TargetId, + content: BlockBuilder, + ) -> Result<(), Error> { + let path = self.path(target)?; + if !self + .result + .deferred_blocks() + .iter() + .any(|request| request.target() == target) + { + return Err(self.error(target, "target is not a pending placeholder")); + } + self.validate_id(target, &content, true)?; + self.prepare_edit(); + let caption_kind = self + .query() + .get(target) + .and_then(|view| view.storage().metadata()) + .and_then(|metadata| content.caption_kind(metadata.style)); + let numbered_kind = caption_kind.filter(|kind| { + self.query().get(target).is_some_and(|view| { + let Block::Extension(extension) = view.storage() else { + return false; + }; + !extension.title.is_empty() + && matches!( + Caption::resolve( + &extension.metadata, + &extension.invocation.document_attributes, + *kind + ), + Caption::Numbered { .. } + ) + }) + }); + let caption_number = + numbered_kind.and_then(|kind| self.result.targets.get_mut()?.next_caption(kind)); + let location = self.location(target); + self.result.parsed.with_document_mut(|owner, document| { + let block = path.get_mut(&mut document.blocks).ok_or_else(|| { + Error::Extension(Box::new(location.clone()), "target is absent".into()) + })?; + let Block::Extension(extension) = block else { + return Err(Error::Extension( + Box::new(location.clone()), + "target is not a placeholder".into(), + )); + }; + let mut metadata = std::mem::take(&mut extension.metadata); + if let Some(kind) = caption_kind { + metadata.caption = Some(Caption::resolve( + &metadata, + &extension.invocation.document_attributes, + kind, + )); + if let Some(Caption::Numbered { number, .. }) = &mut metadata.caption { + *number = caption_number; + } + } + let title = std::mem::take(&mut extension.title); + *block = content.build(&owner.arena, extension.location.clone(), metadata, title); + Ok(()) + })?; + self.result + .session + .deferred + .retain(|request| request.target() != target); + self.result.repair_after_edit() + } + + /// Remove a section and its entire subtree, including pending placeholders. + /// + /// The host applies no empty-section policy; the processor decides what to remove. + /// + /// # Errors + /// Rejects foreign/removed targets and targets that are not sections. + pub fn remove_section(&mut self, target: &TargetId) -> Result<(), Error> { + let path = self.path(target)?; + if !matches!( + path.get(&self.result.parsed.document_storage().blocks), + Some(Block::Section(_)) + ) { + return Err(self.error(target, "target is not a section")); + } + self.remove(target, &path) + } + + /// Remove a pending placeholder and consume its request. + /// + /// # Errors + /// Rejects targets that are not pending placeholders. + pub fn discard_placeholder(&mut self, target: &TargetId) -> Result<(), Error> { + let path = self.path(target)?; + if !self + .result + .deferred_blocks() + .iter() + .any(|request| request.target() == target) + { + return Err(self.error(target, "target is not a pending placeholder")); + } + self.remove(target, &path) + } + + fn remove(&mut self, target: &TargetId, path: &BlockPath) -> Result<(), Error> { + self.prepare_edit(); + let location = self.location(target); + self.result.parsed.with_document_mut(|_, document| { + let (blocks, position) = path.container_mut(&mut document.blocks).ok_or_else(|| { + Error::Extension(Box::new(location.clone()), "target is absent".into()) + })?; + blocks.remove(position); + Ok::<(), Error>(()) + })?; + if let Some(index) = self.result.targets.get_mut() { + index.remove(target); + self.result + .session + .deferred + .retain(|request| index.entry(request.target()).is_some()); + } + self.result.repair_after_edit() + } + + fn validate_id( + &self, + target: &TargetId, + content: &BlockBuilder, + replacing: bool, + ) -> Result<(), Error> { + if let Some(id) = &content.id { + if id.is_empty() { + return Err(self.error(target, "output ID must not be empty")); + } + let current = self.query().get(target).and_then(|view| view.output_id()); + if self + .result + .parsed + .document_storage() + .references + .contains_key(id.as_str()) + && !(replacing && current == Some(id.as_str())) + { + return Err(self.error(target, &format!("output ID is already in use: {id}"))); + } + } + Ok(()) + } + + fn path(&self, target: &TargetId) -> Result { + self.result + .target_index() + .entry(target) + .map(|entry| entry.path.clone()) + .ok_or_else(|| { + self.error( + target, + "target does not belong to this document or is no longer present", + ) + }) + } + + fn prepare_edit(&mut self) { + if let Some(index) = self.result.targets.get_mut() { + self.result + .parsed + .with_document_mut(|_, document| index.prepare_edit(document)); + } + } + + fn location(&self, target: &TargetId) -> SourceLocation { + self.query().get(target).map_or_else( + || { + self.result + .parsed + .source_location(&self.result.parsed.document_storage().location) + }, + |view| view.source_location(), + ) + } + + fn error(&self, target: &TargetId, message: &str) -> Error { + Error::Extension(Box::new(self.location(target)), message.to_owned()) + } +} diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index f5c71b252..fcdefa975 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -1,4 +1,4 @@ -//! Registered block macros with document-local queries and processor state. +//! Registered block macros and ordered tree processors with fresh document sessions. //! //! ``` //! use acdc_parser::{Options, extensions::{ @@ -49,8 +49,51 @@ //! preserves existing IDs and updates the reference catalog; it does not change //! block order or rerun processors. Deferred requests expose the same target handles. //! +//! Tree processors run after block macros and can replace pending requests with +//! ordinary content. Builders accept literal text; markup and substitutions are +//! not run again. +//! +//! ``` +//! use acdc_parser::{Error, Options, extensions::{ +//! BlockBuilder, BlockMacro, BlockMacroOutput, BlockMacroProcessor, +//! DocumentEditor, MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, +//! }}; +//! +//! struct Request; +//! impl BlockMacroProcessor for Request { +//! fn process(&mut self, _: &MacroInvocation<'_>) -> Result { +//! Ok(BlockMacroOutput::Deferred) +//! } +//! } +//! struct Fill; +//! impl TreeProcessor for Fill { +//! fn process(&mut self, document: &mut DocumentEditor<'_>) -> Result<(), Error> { +//! let targets: Vec<_> = document.deferred_blocks().iter() +//! .map(|request| request.target().clone()).collect(); +//! for target in targets { +//! document.replace_placeholder(&target, BlockBuilder::unordered_list(["One", "Two"]))?; +//! } +//! Ok(()) +//! } +//! } +//! let mut builder = Registry::builder(); +//! builder.register(BlockMacro::new("request", || Request))?; +//! builder.register_tree_processor(TreeProcessorRegistration::new("fill", || Fill))?; +//! let result = builder.build().parse("request::[]", &Options::default())?; +//! assert!(result.deferred_blocks().is_empty()); +//! # Ok::<(), Box>(()) +//! ``` +//! +//! Each tree processor runs once in registration order and sees earlier edits. +//! Queries cannot remain borrowed across an edit. Surviving handles remain valid; +//! removed handles never resolve to another block. Section removal repairs TOC and +//! reference catalogs, preserves surviving section/caption numbers, and compacts +//! footnotes. Replacing a placeholder preserves its handle, metadata, and source. + mod block_macro; +mod builder; mod deferred; +mod editor; pub(crate) mod finalization; mod query; mod recognition; @@ -58,15 +101,19 @@ mod registry; mod session; mod target; mod traversal; +mod tree_processor; pub use block_macro::{ BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroContext, MacroInvocation, MacroTarget, }; +pub use builder::BlockBuilder; pub use deferred::{DeferredBlock, ExtensionBlock, PlaceholderId}; +pub use editor::DocumentEditor; pub use query::{BlockContext, BlockView, DocumentQuery}; pub use registry::{RegistrationError, Registry, RegistryBuilder}; pub use session::ExtensionParseResult; pub use target::{TargetError, TargetId}; +pub use tree_processor::{TreeProcessor, TreeProcessorRegistration}; pub(crate) use recognition::recognize; pub(crate) use session::Session; diff --git a/acdc-parser/src/extensions/query.rs b/acdc-parser/src/extensions/query.rs index 326592b08..052980aca 100644 --- a/acdc-parser/src/extensions/query.rs +++ b/acdc-parser/src/extensions/query.rs @@ -1,4 +1,7 @@ -use std::collections::{HashMap, HashSet}; +use std::{ + collections::{HashMap, HashSet}, + num::NonZeroU32, +}; use crate::{ Block, CaptionKind, DelimitedBlockType, Document, InlineMacro, InlineNode, ParseResult, @@ -176,6 +179,17 @@ impl TargetIndex { }); } + pub(super) fn next_caption(&mut self, kind: CaptionKind) -> Option { + let counter = self.caption_high_water.as_mut()?.get_mut(match kind { + CaptionKind::Example => 0, + CaptionKind::Figure => 1, + CaptionKind::Listing => 2, + CaptionKind::Table => 3, + })?; + *counter = counter.saturating_add(1); + NonZeroU32::new(*counter) + } + pub(super) fn reserve_warnings(&mut self, parsed: &ParseResult) { self.unresolved_targets .extend(parsed.warnings().iter().filter_map(|warning| { @@ -186,6 +200,52 @@ impl TargetIndex { } })); } + pub(super) fn insert_before(&mut self, at: &TargetId) -> Option { + let position = *self.slots.get(at.slot)?.as_ref()?; + let entry = self.entry(at)?; + let path = entry.path.clone(); + let section = entry.section.clone(); + for entry in &mut self.entries { + entry.path.shift_siblings(&path, true); + } + let target = TargetId { + document: self.document.clone(), + slot: self.slots.len(), + }; + self.slots.push(None); + self.entries.insert( + position, + Entry { + target: target.clone(), + path, + section, + }, + ); + self.reindex(); + Some(target) + } + + pub(super) fn remove(&mut self, at: &TargetId) { + let Some(entry) = self.entry(at) else { + return; + }; + let path = entry.path.clone(); + self.entries.retain(|entry| !entry.path.is_within(&path)); + for entry in &mut self.entries { + entry.path.shift_siblings(&path, false); + } + self.reindex(); + } + + fn reindex(&mut self) { + self.slots.fill(None); + for (position, entry) in self.entries.iter().enumerate() { + if let Some(slot) = self.slots.get_mut(entry.target.slot) { + *slot = Some(position); + } + } + } + pub(super) fn new(parsed: &ParseResult, session: &Session) -> Self { let unresolved_targets = parsed .warnings() @@ -344,7 +404,6 @@ impl<'doc> BlockView<'doc> { crate::ast::BlockRef::from(self.block) } - #[cfg(test)] pub(super) const fn storage(&self) -> &'doc Block<'doc> { self.block } diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index f6c571164..23e231ba2 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, path::Path, sync::Arc}; use crate::{Error, Options, ParseResult}; -use super::{BlockMacro, ExtensionParseResult, Session}; +use super::{BlockMacro, DocumentEditor, ExtensionParseResult, Session, TreeProcessorRegistration}; /// A registration rejected before any document is parsed. #[derive(Debug, thiserror::Error, PartialEq, Eq)] @@ -16,6 +16,8 @@ pub enum RegistrationError { DuplicateName(String), #[error("block macro is not registered: {0}")] UnknownName(String), + #[error("tree processor is already registered: {0}")] + DuplicateTreeProcessor(String), } /// Builds a registry without modifying existing registry snapshots. @@ -23,9 +25,32 @@ pub enum RegistrationError { pub struct RegistryBuilder { macros: Vec, names: HashMap, + trees: Vec, } impl RegistryBuilder { + /// Register a tree processor after the existing tree processors. + /// + /// Names match `[A-Za-z][A-Za-z0-9_-]*` and are independent of macro names. + /// + /// # Errors + /// Rejects invalid names and duplicate tree processor registrations. + pub fn register_tree_processor( + &mut self, + registration: TreeProcessorRegistration, + ) -> Result<&mut Self, RegistrationError> { + validate_identifier(®istration.name)?; + if self + .trees + .iter() + .any(|entry| entry.name == registration.name) + { + return Err(RegistrationError::DuplicateTreeProcessor(registration.name)); + } + self.trees.push(registration); + Ok(self) + } + /// Register a macro after the existing registrations. /// /// Names match `[A-Za-z][A-Za-z0-9_-]*`. Built-in macro names are reserved. @@ -63,6 +88,7 @@ impl RegistryBuilder { Registry(Arc::new(RegistryData { macros: self.macros, names: self.names, + trees: self.trees, })) } } @@ -92,6 +118,7 @@ fn validate_identifier(name: &str) -> Result<(), RegistrationError> { struct RegistryData { macros: Vec, names: HashMap, + trees: Vec, } /// A cheap-to-clone, immutable collection of extension factories. @@ -106,13 +133,15 @@ impl Registry { #[must_use] pub fn is_empty(&self) -> bool { - self.0.macros.is_empty() + self.0.macros.is_empty() && self.0.trees.is_empty() } /// Parse with fresh processors and retain this document's deferred requests. /// /// Macro processors run after the complete document is accepted. The host - /// repairs captions and catalogs. Callbacks cannot change source processing. + /// repairs captions and catalogs, then tree processors run once in + /// registration order, with catalog repair after each edit. Callbacks cannot + /// change source processing. /// An empty registry uses the ordinary parser path. /// /// # Errors @@ -154,6 +183,11 @@ impl Registry { if result.session.processed_blocks { result.repair_after_edit()?; } + let mut processors = std::mem::take(&mut result.session.tree_processors); + for processor in &mut processors { + processor.process(&mut DocumentEditor::new(&mut result))?; + } + result.session.tree_processors = processors; Ok(result) } @@ -172,6 +206,7 @@ impl Registry { .iter() .map(|entry| (entry.factory)()) .collect(), + self.0.trees.iter().map(|entry| (entry.factory)()).collect(), ) } } diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index 19a227c73..c42a44af0 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -7,11 +7,12 @@ use crate::{ use super::{ BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, PlaceholderId, TargetId, - query::TargetIndex, target::DocumentIdentity, + TreeProcessor, query::TargetIndex, target::DocumentIdentity, }; pub(crate) struct Session { processors: Vec>, + pub(super) tree_processors: Vec>, pub(super) deferred: Vec, pub(super) processed_blocks: bool, identity: OnceCell, @@ -88,9 +89,13 @@ impl ExtensionParseResult { } impl Session { - pub(super) fn new(processors: Vec>) -> Self { + pub(super) fn new( + processors: Vec>, + tree_processors: Vec>, + ) -> Self { Self { processors, + tree_processors, deferred: Vec::new(), processed_blocks: false, identity: OnceCell::new(), diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index 68175c5ac..a23d8d809 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -24,6 +24,9 @@ mod support; #[path = "queries.rs"] mod queries; +#[path = "tree_processors.rs"] +mod tree_processors; + type TestResult = Result<(), Box>; struct Counter { diff --git a/acdc-parser/src/extensions/tests/tree_processors.rs b/acdc-parser/src/extensions/tests/tree_processors.rs new file mode 100644 index 000000000..128d3988f --- /dev/null +++ b/acdc-parser/src/extensions/tests/tree_processors.rs @@ -0,0 +1,659 @@ +use std::{ + cell::Cell, + rc::Rc, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; + +use acdc_parser::{ + Block, Error, InlineMacro, InlineNode, Options, SafeMode, WarningKind, + extensions::{ + BlockBuilder, BlockContext, BlockMacro, DocumentEditor, MacroTarget, Registry, TargetId, + TreeProcessor, TreeProcessorRegistration, + }, +}; + +use super::{TestResult, paragraph_text, support}; + +struct Fresh { + local: Rc>, + calls: Arc, + drops: Arc, + fail: bool, +} + +impl TreeProcessor for Fresh { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + self.calls.fetch_add(1, Ordering::Relaxed); + self.local.set(self.local.get() + 1); + let request = editor.deferred_blocks().first().expect("pending request"); + if self.fail { + return Err(Error::Extension( + Box::new(request.invocation.location.clone()), + "deliberate tree failure".into(), + )); + } + let target = request.target().clone(); + editor.replace_placeholder( + &target, + BlockBuilder::paragraph(self.local.get().to_string()), + ) + } +} + +impl Drop for Fresh { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::Relaxed); + } +} + +#[test] +fn extensions_tree_processors_are_fresh_local_and_retained_until_result_drop() -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let owned_calls = Arc::clone(&calls); + let owned_drops = Arc::clone(&drops); + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("defer", || support::Defer))?; + builder.register_tree_processor(TreeProcessorRegistration::new("fresh", move || Fresh { + local: Rc::new(Cell::new(0)), + calls: Arc::clone(&owned_calls), + drops: Arc::clone(&owned_drops), + fail: false, + }))?; + let registry = builder.build(); + assert!(!registry.is_empty()); + let first = registry.parse("defer::[]", &Options::default())?; + let second = registry.clone().parse("defer::[]", &Options::default())?; + assert_eq!( + paragraph_text(&first.parsed.document_storage().blocks[0]), + "1" + ); + assert_eq!( + paragraph_text(&second.parsed.document_storage().blocks[0]), + "1" + ); + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!(drops.load(Ordering::Relaxed), 0); + drop(first); + drop(second); + assert_eq!(drops.load(Ordering::Relaxed), 2); + Ok(()) +} + +#[test] +fn extensions_tree_errors_stop_later_processors_at_included_request() -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder + .register(BlockMacro::new("defer", || support::Defer).with_target(MacroTarget::Required))?; + for name in ["failure", "later"] { + let calls = Arc::clone(&calls); + let drops = Arc::clone(&drops); + builder.register_tree_processor(TreeProcessorRegistration::new(name, move || Fresh { + local: Rc::new(Cell::new(0)), + calls: Arc::clone(&calls), + drops: Arc::clone(&drops), + fail: true, + }))?; + } + let registry = builder.build(); + let options = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let error = registry + .parse_file( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures/tests/includes/extensions/extension-tree-error.adoc"), + &options, + ) + .expect_err("tree processor error"); + assert_eq!(calls.load(Ordering::Relaxed), 1); + assert_eq!(drops.load(Ordering::Relaxed), 2); + assert_eq!( + error + .source_location() + .expect("request location") + .location + .start + .line, + 3 + ); + assert!( + error + .source_location() + .and_then(|location| location.file.as_ref()) + .is_some_and(|file| file.ends_with("extension-tree-error.adoc")) + ); + assert!(registry.parse("defer::[]", &Options::default()).is_err()); + assert_eq!(calls.load(Ordering::Relaxed), 1); + assert_eq!(drops.load(Ordering::Relaxed), 4); + Ok(()) +} + +struct CheckedEdits; + +impl TreeProcessor for CheckedEdits { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let target = editor + .query() + .select(BlockContext::Paragraph) + .next() + .expect("paragraph") + .target() + .clone(); + let before = serde_json::to_string(editor.document_storage()).expect("document JSON"); + let foreign = Registry::default().parse("Foreign", &Options::default())?; + let foreign_target = foreign + .query() + .blocks() + .next() + .expect("foreign") + .target() + .clone(); + assert!(editor.remove_section(&target).is_err()); + assert!( + editor + .replace_placeholder(&target, BlockBuilder::paragraph("bad")) + .is_err() + ); + assert!(editor.discard_placeholder(&target).is_err()); + assert!( + editor + .insert_before(&foreign_target, BlockBuilder::paragraph("bad")) + .is_err() + ); + assert!( + editor + .insert_before(&target, BlockBuilder::paragraph("bad").with_id("")) + .is_err() + ); + assert!( + editor + .insert_before(&target, BlockBuilder::paragraph("bad").with_id("existing")) + .is_err() + ); + assert_eq!( + serde_json::to_string(editor.document_storage()).expect("document JSON"), + before + ); + let new = editor.insert_before( + &target, + BlockBuilder::paragraph("*literal* <&> {counter:x}").with_id("new"), + )?; + assert_eq!( + paragraph_text(editor.query().get(&new).expect("inserted").storage()), + "*literal* <&> {counter:x}" + ); + assert!(editor.document_storage().references.contains_key("new")); + Ok(()) + } +} + +#[test] +fn extensions_tree_only_registry_preserves_parsing_and_checks_edits_before_mutation() -> TestResult +{ + let mut builder = Registry::builder(); + builder.register_tree_processor(TreeProcessorRegistration::new("checked", || CheckedEdits))?; + assert!( + builder + .register_tree_processor(TreeProcessorRegistration::new("checked", || CheckedEdits)) + .is_err() + ); + assert!( + builder + .register_tree_processor(TreeProcessorRegistration::new("bad:name", || CheckedEdits)) + .is_err() + ); + let result = builder + .build() + .parse("[#existing]\nOriginal", &Options::default())?; + assert_eq!(result.parsed.document_storage().blocks.len(), 2); + Ok(()) +} + +struct FillNested; + +impl TreeProcessor for FillNested { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let targets: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + for target in &targets { + let created = editor.insert_before(target, BlockBuilder::paragraph("Inserted"))?; + let id = editor.ensure_id(&created)?.to_owned(); + assert_eq!( + editor.query().get(&created).expect("inserted").output_id(), + Some(id.as_str()) + ); + editor.replace_placeholder(target, BlockBuilder::paragraph("Filled"))?; + } + let sections: Vec<_> = editor + .query() + .select(BlockContext::Section) + .filter(|view| view.output_id() == Some("cell-remove")) + .map(|view| view.target().clone()) + .collect(); + for section in sections { + editor.remove_section(§ion)?; + } + assert_eq!( + targets + .iter() + .filter(|target| editor.query().get(target).is_some()) + .count(), + 6 + ); + Ok(()) + } +} + +#[test] +fn extensions_tree_edits_follow_list_compound_and_table_cell_containers() -> TestResult { + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("defer", || support::Defer))?; + builder.register_tree_processor(TreeProcessorRegistration::new("nested", || FillNested))?; + let result = builder.build().parse( + include_str!("../../../fixtures/tests/includes/extensions/extension-tree-nested.adoc"), + &Options::default(), + )?; + assert!(result.deferred_blocks().is_empty()); + assert_eq!( + result + .query() + .select(BlockContext::Paragraph) + .filter(|view| paragraph_text(view.storage()) == "Filled") + .count(), + 6 + ); + assert!( + !result + .parsed + .document_storage() + .references + .contains_key("cell-remove") + ); + let query = result.query(); + let cell = query + .select(BlockContext::Paragraph) + .find(|view| view.output_id() == Some("cell-keep-content")) + .expect("kept cell"); + assert_eq!( + cell.containing_section() + .and_then(|target| query.get(target)) + .and_then(|view| view.output_id()), + Some("cell-keep") + ); + Ok(()) +} + +struct Producer(Arc); + +impl TreeProcessor for Producer { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + self.0.fetch_add(1, Ordering::Relaxed); + let requests: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| { + ( + request.target().clone(), + request.invocation.target == "discard", + ) + }) + .collect(); + for (target, discard) in requests { + let target = ⌖ + if discard { + editor.discard_placeholder(target)?; + } else { + let inserted = editor.insert_before( + target, + BlockBuilder::paragraph("Produced").with_id("produced"), + )?; + assert_eq!(editor.ensure_id(&inserted)?, "produced"); + assert!(editor.query().get(target).is_some()); + } + } + Ok(()) + } +} + +struct Consumer(Arc); + +impl TreeProcessor for Consumer { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + self.0.fetch_add(1, Ordering::Relaxed); + let selection: Vec<_> = editor + .query() + .select(BlockContext::Paragraph) + .map(|view| paragraph_text(view.storage())) + .collect(); + let targets: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + for target in targets { + editor.replace_placeholder(&target, BlockBuilder::unordered_list(selection.clone()))?; + } + assert!(editor.deferred_blocks().is_empty()); + Ok(()) + } +} + +struct Remove(Arc); + +struct RemoveFirstAndAssign; + +impl TreeProcessor for RemoveFirstAndAssign { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let first = editor + .query() + .select(BlockContext::Section) + .next() + .expect("first") + .target() + .clone(); + editor.remove_section(&first)?; + let unnamed = editor + .query() + .select(BlockContext::Section) + .find(|view| view.output_id().is_none()) + .expect("unnamed child") + .target() + .clone(); + let id = editor.ensure_id(&unnamed)?.to_owned(); + assert_eq!( + editor.document_storage().references[id.as_str()].section_number(), + Some("2.1") + ); + Ok(()) + } +} + +#[test] +fn extensions_tree_removal_preserves_duplicate_and_hidden_section_numbers() -> TestResult { + let mut builder = Registry::builder(); + builder.register_tree_processor(TreeProcessorRegistration::new("remove", || { + RemoveFirstAndAssign + }))?; + let result = builder.build().parse("= Guide\n:sectnums:\n:sectnumlevels: 1\n:idprefix:\n\n[#duplicate]\n== First\n\n[#duplicate]\n== Second\n\n=== !!!\n\nSee <>.", &Options::default())?; + let document = result.parsed.document_storage(); + assert_eq!(document.references["duplicate"].section_number(), Some("2")); + assert_eq!(document.toc_entries.len(), 2); + assert_eq!(document.toc_entries[0].number(), Some("2")); + assert_eq!(document.toc_entries[1].number(), None); + assert!( + !result + .parsed + .warnings() + .iter() + .any(|warning| matches!(warning.kind, WarningKind::DuplicateId { .. })) + ); + Ok(()) +} + +struct RemoveAndFill; + +impl TreeProcessor for RemoveAndFill { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + Remove(Arc::new(AtomicUsize::new(0))).process(editor)?; + let targets: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + for target in targets { + editor.replace_placeholder(&target, BlockBuilder::paragraph("Generated"))?; + } + Ok(()) + } +} + +#[test] +fn extensions_generated_captions_keep_source_labels_and_advance_past_removed_ordinals() -> TestResult +{ + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("defer", || support::Defer))?; + builder.register_tree_processor(TreeProcessorRegistration::new("fill", || RemoveAndFill))?; + let result = builder.build().parse( + include_str!("../../../fixtures/tests/includes/extensions/extension-tree-captions.adoc"), + &Options::default(), + )?; + let references = &result.parsed.document_storage().references; + assert!(matches!(&references["automatic"].caption, + Some(acdc_parser::Caption::Numbered { label, number: Some(number), .. }) + if label == "Early" && number.get() == 3)); + assert!( + matches!(&references["custom"].caption, + Some(acdc_parser::Caption::CustomContent(label)) if matches!(label.as_inlines(), [InlineNode::RawText(text)] if text.content == "Custom ")), + "{:?}", + references["custom"].caption + ); + assert!(matches!(&references["survivor"].caption, + Some(acdc_parser::Caption::Numbered { number: Some(number), .. }) if number.get() == 2)); + Ok(()) +} + +impl TreeProcessor for Remove { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + self.0.fetch_add(1, Ordering::Relaxed); + let targets: Vec<_> = editor + .query() + .select(BlockContext::Section) + .filter(|view| view.output_id() == Some("gone")) + .map(|view| view.target().clone()) + .collect(); + for target in targets { + editor.remove_section(&target)?; + assert!(editor.query().get(&target).is_none()); + } + Ok(()) + } +} + +#[test] +fn extensions_tree_order_and_snapshot_selection() -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("defer", || support::Defer))?; + for name in ["producer", "consumer", "remover"] { + let calls = Arc::clone(&calls); + match name { + "producer" => { + builder + .register_tree_processor(TreeProcessorRegistration::new(name, move || { + Producer(Arc::clone(&calls)) + }))?; + } + "consumer" => { + builder + .register_tree_processor(TreeProcessorRegistration::new(name, move || { + Consumer(Arc::clone(&calls)) + }))?; + } + _ => { + builder + .register_tree_processor(TreeProcessorRegistration::new(name, move || { + Remove(Arc::clone(&calls)) + }))?; + } + } + } + let result = builder.build().parse("[#gone]\n== Remove\n\nRemoved\n\n[#stay]\n== Keep\n\n.Title\n[#snapshot]\n[role=kept]\ndefer::content[]\n\ndefer::discard[]", &Options::default())?; + assert_eq!(calls.load(Ordering::Relaxed), 3); + assert!(result.deferred_blocks().is_empty()); + let query = result.query(); + let view = query + .select(BlockContext::UnorderedList) + .next() + .ok_or("missing replacement")?; + assert_eq!(view.output_id(), Some("snapshot")); + assert!( + view.storage() + .metadata() + .ok_or("missing metadata")? + .roles + .contains(&"kept") + ); + let Block::UnorderedList(list) = view.storage() else { + panic!("expected list") + }; + let items: Vec<_> = list + .items + .iter() + .flat_map(|item| item.principal.iter()) + .filter_map(|inline| { + if let InlineNode::PlainText(text) = inline { + Some(text.content) + } else { + None + } + }) + .collect(); + assert_eq!(items, ["Removed", "Produced"]); + assert!( + !result + .parsed + .document_storage() + .references + .contains_key("gone") + ); + assert_eq!(result.parsed.document_storage().toc_entries.len(), 1); + Ok(()) +} + +struct CaptureAndRemove; + +impl TreeProcessor for CaptureAndRemove { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let gone = editor + .query() + .select(BlockContext::Section) + .find(|view| view.output_id() == Some("gone")) + .expect("gone") + .target() + .clone(); + let targets: Vec = editor + .query() + .blocks() + .map(|view| view.target().clone()) + .collect(); + editor.remove_section(&gone)?; + assert!(editor.deferred_blocks().is_empty()); + let stay = editor + .query() + .select(BlockContext::Section) + .next() + .expect("stay") + .target() + .clone(); + editor.insert_before(&stay, BlockBuilder::paragraph("New owner").with_id("gone"))?; + assert!(editor.query().get(&targets[0]).is_none()); + assert!(editor.query().get(&targets[1]).is_none()); + assert!(editor.ensure_id(&targets[0]).is_err()); + assert_eq!( + editor.query().get(&targets[2]).expect("stay").output_id(), + Some("stay") + ); + assert_eq!( + paragraph_text( + editor + .query() + .get(&targets[3]) + .expect("surviving paragraph") + .storage() + ), + "Survives" + ); + Ok(()) + } +} + +#[test] +fn extensions_removed_handles_do_not_rebind_and_surviving_paths_shift() -> TestResult { + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("defer", || support::Defer))?; + builder.register_tree_processor(TreeProcessorRegistration::new("capture", || { + CaptureAndRemove + }))?; + let result = builder.build().parse( + "[#gone]\n== Remove\n\ndefer::pending[]\n\n[#stay]\n== Keep\n\nSurvives", + &Options::default(), + )?; + assert_eq!( + result + .query() + .select(BlockContext::Paragraph) + .next() + .expect("new owner") + .output_id(), + Some("gone") + ); + Ok(()) +} + +#[test] +fn extensions_removal_repairs_catalogs_without_renumbering_survivors() -> TestResult { + let mut builder = Registry::builder(); + builder.register_tree_processor(TreeProcessorRegistration::new("remove", || { + Remove(Arc::new(AtomicUsize::new(0))) + }))?; + let result = builder.build().parse( + include_str!("../../../fixtures/tests/includes/extensions/extension-tree-numbering.adoc"), + &Options::default(), + )?; + let document = result.parsed.document_storage(); + assert_eq!(document.toc_entries.len(), 1); + assert_eq!(document.toc_entries[0].number(), Some("2")); + let section = result + .query() + .select(BlockContext::Section) + .next() + .ok_or("missing section")?; + let Block::Section(section) = section.storage() else { + panic!("expected section") + }; + assert_eq!(section.number(), Some("2")); + assert_eq!(document.references["stay"].section_number(), Some("2")); + assert!(!document.references.contains_key("gone")); + assert!(!document.references.contains_key("inline-gone")); + assert!(!document.references.contains_key("figure-gone")); + assert!(!document.references.contains_key("_removed_child")); + assert_eq!( + document.references["figure-stay"].caption, + result + .query() + .select(BlockContext::Image) + .next() + .and_then(|view| view + .storage() + .metadata() + .and_then(|metadata| metadata.caption.as_ref())) + .cloned() + ); + assert!(matches!(document.references["figure-stay"].caption, + Some(acdc_parser::Caption::Numbered { number: Some(number), .. }) if number.get() == 2)); + assert_eq!(document.footnotes.len(), 1); + assert_eq!(document.footnotes[0].number, 1); + assert!(result.parsed.warnings().iter().any(|warning| matches!(&warning.kind, WarningKind::UnresolvedReference { target } if target == "gone"))); + assert!(!result.parsed.warnings().iter().any(|warning| matches!(&warning.kind, WarningKind::UnresolvedReference { target } if target == "only-in-removed"))); + let mut footnotes = Vec::new(); + for block in §ion.content { + if let Block::Paragraph(paragraph) = block { + for inline in ¶graph.content { + if let InlineNode::Macro(InlineMacro::Footnote(note)) = inline { + footnotes.push(note.number); + } + } + } + } + assert_eq!(footnotes, [1]); + Ok(()) +} diff --git a/acdc-parser/src/extensions/traversal.rs b/acdc-parser/src/extensions/traversal.rs index 5ba35352e..71f996053 100644 --- a/acdc-parser/src/extensions/traversal.rs +++ b/acdc-parser/src/extensions/traversal.rs @@ -25,6 +25,49 @@ pub(super) struct BlockPath { } impl BlockPath { + pub(super) fn container_mut<'doc, 'a>( + &self, + blocks: &'doc mut Vec>, + ) -> Option<(&'doc mut Vec>, usize)> { + let Some((&(children, index), parents)) = self.nested.split_last() else { + return Some((blocks, self.root)); + }; + let mut parent = blocks.get_mut(self.root)?; + for &(children, index) in parents { + parent = children.get_mut(parent)?.get_mut(index)?; + } + Some((children.get_mut(parent)?, index)) + } + + pub(super) fn is_within(&self, parent: &Self) -> bool { + self.root == parent.root && self.nested.starts_with(&parent.nested) + } + + pub(super) fn shift_siblings(&mut self, at: &Self, insert: bool) { + let index = if let Some((&(children, position), parents)) = at.nested.split_last() { + if self.root != at.root || !self.nested.starts_with(parents) { + return; + } + let Some((own_children, own_position)) = self.nested.get_mut(parents.len()) else { + return; + }; + if *own_children != children || *own_position < position { + return; + } + own_position + } else { + if self.root < at.root { + return; + } + &mut self.root + }; + if insert { + *index += 1; + } else { + *index -= 1; + } + } + pub(super) fn root(index: usize) -> Self { Self { root: index, diff --git a/acdc-parser/src/extensions/tree_processor.rs b/acdc-parser/src/extensions/tree_processor.rs new file mode 100644 index 000000000..b23deec1e --- /dev/null +++ b/acdc-parser/src/extensions/tree_processor.rs @@ -0,0 +1,47 @@ +use std::{fmt, sync::Arc}; + +use crate::Error; + +use super::DocumentEditor; + +/// A document-local processor invoked once after block macros finish. +/// +/// Processors run in registration order. Each sees earlier edits; later edits +/// do not repeat an earlier processor's selection or side effects. +pub trait TreeProcessor { + /// Inspect and edit the accepted document through the host. + /// + /// # Errors + /// Return an error to stop processing and discard the document result. + fn process(&mut self, document: &mut DocumentEditor<'_>) -> Result<(), Error>; +} + +/// An immutable factory for a fresh tree processor in each document session. +#[derive(Clone)] +pub struct TreeProcessorRegistration { + pub(super) name: String, + pub(super) factory: Arc Box + Send + Sync>, +} + +impl TreeProcessorRegistration { + /// Factories can share resources; their document-local processors need not be + /// `Send` or `Sync`. + pub fn new( + name: impl Into, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Self { + Self { + name: name.into(), + factory: Arc::new(move || Box::new(factory())), + } + } +} + +impl fmt::Debug for TreeProcessorRegistration { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TreeProcessorRegistration") + .field("name", &self.name) + .finish_non_exhaustive() + } +} diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index 85ff4d8a8..988d89e21 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -1,8 +1,9 @@ use acdc_parser::{ CompatibilityMode, Error, Options, ParseResult, - ast::{BlockKind, InlineKind}, + ast::{BlockKind, ElementIdRef, FootnoteDefinitionRef, InlineKind, ReferenceTargetRef}, extensions::{ - BlockContext, BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry, + BlockBuilder, BlockContext, BlockMacro, BlockMacroOutput, BlockMacroProcessor, + DocumentEditor, MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, }, }; @@ -15,6 +16,32 @@ impl BlockMacroProcessor for Defer { } } +struct Fill; +impl TreeProcessor for Fill { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let targets: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + for target in targets { + assert!(matches!( + editor.query().get(&target).map(|view| view.block().kind()), + Some(BlockKind::Extension(_)) + )); + editor.replace_placeholder( + &target, + BlockBuilder::unordered_list(["*literal* <&>", "{counter:x}"]), + )?; + assert!(matches!( + editor.query().get(&target).map(|view| view.block().kind()), + Some(BlockKind::UnorderedList(_)) + )); + } + Ok(()) + } +} + #[test] fn extensions_finish_checks_pending_requests_and_returns_normal_parse_result() -> TestResult { fn require_send(_: impl Send) {} @@ -34,9 +61,37 @@ fn extensions_finish_checks_pending_requests_and_returns_normal_parse_result() - .map(|source| source.location.start.line), Some(1) ); - let parsed: ParseResult = Registry::default() - .parse("Ordinary content.", &options)? + + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("request", || Defer))?; + builder.register_tree_processor(TreeProcessorRegistration::new("fill", || Fill))?; + let parsed: ParseResult = builder + .build() + .parse(".A *title*\n[#list]\nrequest::[]", &options)? .finish()?; + let block = parsed.document().blocks().next().ok_or("list")?; + assert_eq!(block.id().map(ElementIdRef::as_str), Some("list")); + assert!(block.title().is_some_and(|title| { + title + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + })); + let BlockKind::UnorderedList(list) = block.kind() else { + return Err("list kind".into()); + }; + let texts: Vec<_> = list + .items() + .filter_map(|item| { + item.principal().inlines().find_map(|inline| { + if let InlineKind::Plain(text) = inline.kind() { + Some(text.text()) + } else { + None + } + }) + }) + .collect(); + assert_eq!(texts, ["*literal* <&>", "{counter:x}"]); require_send(parsed); } Ok(()) @@ -81,3 +136,86 @@ fn extensions_typed_queries_preserve_prepared_reference_labels() -> TestResult { } Ok(()) } + +struct RemoveFirst; +impl TreeProcessor for RemoveFirst { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let target = editor + .query() + .select(BlockContext::Section) + .find(|view| view.output_id() == Some("gone")) + .map(|view| view.target().clone()); + if let Some(target) = target { + editor.remove_section(&target)?; + } + Ok(()) + } +} + +#[test] +fn extensions_removal_preserves_cell_footnote_owners_and_prepared_numbers() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut builder = Registry::builder(); + builder + .register_tree_processor(TreeProcessorRegistration::new("remove", || RemoveFirst))?; + let source = "= Notes\n:sectnums:\n\n[#gone]\n== Removed\n\nfootnote:same[Outer definition <> [[inside]]]\n\n[#keep]\n== Kept\n\nfootnote:same[] and <>.\n\n[cols=a]\n|===\n|Cell footnote:same[Cell definition]\n|===\n"; + assert!( + acdc_parser::parse(source, &options)? + .document() + .references() + .get("inside") + .is_some() + ); + let parsed = builder.build().parse(source, &options)?.finish()?; + assert!(parsed.warnings().iter().any(|warning| matches!( + &warning.kind, + acdc_parser::WarningKind::UnresolvedReference { target } if target == "gone" + ))); + let document = parsed.document(); + assert_eq!(document.footnotes().count(), 1); + assert!(document.references().get("inside").is_some()); + assert_eq!( + document + .references() + .get("keep") + .and_then(ReferenceTargetRef::section_number), + Some("2") + ); + let section = document + .blocks() + .find_map(|block| { + if let BlockKind::Section(section) = block.kind() { + Some(section) + } else { + None + } + }) + .ok_or("kept section")?; + assert_eq!(section.number(), Some("2")); + let table = section + .blocks() + .find_map(|block| { + if let BlockKind::Table(table) = block.kind() { + Some(table) + } else { + None + } + }) + .ok_or("table")?; + let cell = table + .rows() + .next() + .and_then(|row| row.cells().next()) + .ok_or("cell")?; + assert_eq!(cell.footnotes().count(), 1); + assert_ne!( + cell.footnotes().next().map(FootnoteDefinitionRef::number), + document + .footnotes() + .next() + .map(FootnoteDefinitionRef::number) + ); + } + Ok(()) +} diff --git a/converters/html/tests/typed_document_entrypoints.rs b/converters/html/tests/typed_document_entrypoints.rs index 8603f6847..0b7bba31e 100644 --- a/converters/html/tests/typed_document_entrypoints.rs +++ b/converters/html/tests/typed_document_entrypoints.rs @@ -1,11 +1,17 @@ -//! Conversion entry points accept parsed and caller-constructed typed documents. +//! Conversion entry points accept parsed, constructed, and extension-generated documents. use std::path::Path; use acdc_converters_core::{Converter as _, Diagnostics, Options, WarningSource}; use acdc_converters_html::{Converter, RenderOptions}; use acdc_parser::{ - Block, Document, InlineNode, Location, Paragraph, Plain, ast::DocumentRef, parse, + Block, CompatibilityMode, Document, Error, InlineNode, Location, Paragraph, Plain, + ast::DocumentRef, + extensions::{ + BlockBuilder, BlockMacro, BlockMacroOutput, BlockMacroProcessor, DocumentEditor, + MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, + }, + parse, }; #[test] @@ -49,3 +55,70 @@ fn parsed_and_constructed_documents_share_conversion_entrypoints() } Ok(()) } + +struct ListRequest; + +impl BlockMacroProcessor for ListRequest { + fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + Ok(BlockMacroOutput::Deferred) + } +} + +struct FillList; + +impl TreeProcessor for FillList { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let targets: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + for target in targets { + editor.replace_placeholder( + &target, + BlockBuilder::unordered_list(["*literal* <&>", "{counter:x}"]), + )?; + } + Ok(()) + } +} + +#[test] +fn extension_generated_lists_preserve_metadata_references_and_literal_text() +-> Result<(), Box> { + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("request", || ListRequest))?; + builder.register_tree_processor(TreeProcessorRegistration::new("fill", || FillList))?; + let registry = builder.build(); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let converter = Converter::new( + Options::builder().embedded(true).build(), + acdc_parser::Options::builder().with_compatibility_mode(mode), + )?; + let parsed = registry + .parse( + ".Generated *title*\n[#generated]\nrequest::[]\n\nSee <>.", + converter.parser_options(), + )? + .finish()?; + let output = converter.convert_to_string( + parsed.document(), + &RenderOptions { + embedded: true, + ..RenderOptions::default() + }, + )?; + for fragment in [ + "id=\"generated\"", + "Generated title", + "href=\"#generated\"", + "*literal* <&>", + "{counter:x}", + ] { + assert!(output.contains(fragment), "{mode:?}: missing {fragment}"); + } + assert!(!output.contains("&lt;")); + assert!(parsed.warnings().is_empty(), "{:?}", parsed.warnings()); + } + Ok(()) +} From ae70f478dbf7a6678b769a204629733862b3289f Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 12 Nov 2026 09:31:44 +0100 Subject: [PATCH 03/55] refactor(parser): make preprocessing resumable across includes Retain conditional and comment state between input advances and preserve include source maps and fast bulk reads. Part of SC-535. --- acdc-parser/src/preprocessor/cursor.rs | 357 ++++++++++++++++++ acdc-parser/src/preprocessor/include.rs | 157 ++++---- .../src/preprocessor/include_budget_tests.rs | 129 +++++++ acdc-parser/src/preprocessor/mod.rs | 333 +++------------- 4 files changed, 610 insertions(+), 366 deletions(-) create mode 100644 acdc-parser/src/preprocessor/cursor.rs diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs new file mode 100644 index 000000000..fdf99e662 --- /dev/null +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -0,0 +1,357 @@ +use std::{borrow::Cow, iter::Peekable, str::Lines}; + +use bumpalo::Bump; + +use crate::{Error, Options}; + +use super::{ + CommentScanner, ConditionalFrame, DirectiveContext, Preprocessor, PreprocessorResult, + PreprocessorState, SkimmedFrontMatter, SourceLineOrigin, SourceOrigin, attribute, + consume_front_matter, has_attribute_continuation, has_include_directive_shape, + include::{IncludeResult, IncludeScope}, + is_escaped_directive, skim_front_matter, +}; + +/// Retains source-reader state between advances. A later directive is not +/// processed until the caller advances to its line. +pub(super) struct InputCursor<'input> { + preprocessor: Preprocessor, + source_origin: Option, + arena: &'input Bump, + lines: Peekable>, + line_number: usize, + out: PreprocessorState<'input>, + scanner: CommentScanner, + conditionals: Vec>, + front_matter: Option, + include: Option>, +} + +struct IncludeFrame<'input> { + result: IncludeResult, + cursor: Box>, + input_line: usize, + scope: Option, +} + +impl<'input> InputCursor<'input> { + pub(super) fn new( + preprocessor: &Preprocessor, + input: &'input str, + source_origin: Option<&SourceOrigin>, + options: &mut Options<'_>, + line_origins: Vec, + front_matter: Option, + arena: &'input Bump, + ) -> Self { + let mut lines = input.lines().peekable(); + let mut line_number = 1; + let front_matter = consume_front_matter( + &mut lines, + &mut line_number, + preprocessor.include_context.depth == 0, + front_matter, + ); + if let Some(value) = &front_matter { + options + .document_attributes + .set_text("front-matter".into(), value.clone().into()); + } + let mut out = PreprocessorState::new(input, source_origin, line_origins); + out.record_leveloffset(options); + Self { + preprocessor: preprocessor.clone(), + source_origin: source_origin.cloned(), + arena, + lines, + line_number, + out, + scanner: CommentScanner::new( + crate::grammar::setext::is_enabled(options.compatibility_mode), + preprocessor.include_context.block_context.clone(), + options.compatibility_mode, + ), + conditionals: Vec::new(), + front_matter, + include: None, + } + } + + pub(super) fn advance(&mut self, options: &mut Options<'_>) -> Result { + if let Some(mut include) = self.include.take() { + if include.cursor.advance(options)? { + self.include = Some(include); + } else { + let result = include.cursor.read_all(options)?; + self.finish_include( + include.result, + result, + include.input_line, + include.scope, + options, + )?; + } + return Ok(true); + } + let Some(line) = self.lines.next() else { + return Ok(false); + }; + self.process_line(line, options)?; + self.line_number += 1; + Ok(true) + } + + fn process_line(&mut self, line: &'input str, options: &mut Options<'_>) -> Result<(), Error> { + if self.conditionals.last().is_none_or(|frame| frame.active) + && self.scanner.preserves_comment_line(line) + { + self.out.push_source_line(line, self.line_number); + self.scanner.record(line, &options.document_attributes); + return Ok(()); + } + let origin = self.out.origin_of_line(self.line_number); + let ctx = DirectiveContext { + input_line: self.line_number, + source_line: origin.line, + current_offset: origin.offset, + source_origin: self.source_origin.as_ref(), + }; + if self.preprocessor.process_conditional_line( + line, + &ctx, + &options.document_attributes, + &mut self.conditionals, + &mut self.out, + &mut self.scanner, + )? || self.conditionals.last().is_some_and(|frame| !frame.active) + { + return Ok(()); + } + if self.scanner.allows_attribute_entries() && has_attribute_continuation(line) { + let start_line = self.line_number; + let (content, continuation_lines) = + Preprocessor::process_continuation(line, &mut self.lines, &mut self.line_number); + attribute::parse_line(options, &content)?; + self.out.record_leveloffset(options); + self.out.push_source_line(line, start_line); + for (offset, continued) in continuation_lines.into_iter().enumerate() { + self.out + .push_source_line(continued, start_line + 1 + offset); + } + self.scanner.record(line, &options.document_attributes); + return Ok(()); + } else if self.scanner.allows_attribute_entries() && line.starts_with(':') { + attribute::parse_line(options, line.trim())?; + } + self.out.record_leveloffset(options); + if self.scanner.at_table_delimiter(line) || self.scanner.at_verbatim_delimiter(line) { + self.out.push_source_line(line, self.line_number); + } else if line.starts_with("//") { + if self.scanner.drops(line) { + return Ok(()); + } + self.out.push_source_line(line, self.line_number); + } else if line.ends_with(']') && !line.starts_with('[') && line.contains("::") { + return self.process_directive_line(line, options); + } else { + self.out.push_source_line(line, self.line_number); + } + self.scanner.record(line, &options.document_attributes); + Ok(()) + } + + fn process_directive_line( + &mut self, + line: &'input str, + options: &mut Options<'_>, + ) -> Result<(), Error> { + if is_escaped_directive(line) { + self.out.note_source_line(self.line_number); + self.out.push_line(Cow::Borrowed(&line[1..])); + self.scanner + .record(&line[1..], &options.document_attributes); + } else if has_include_directive_shape(line) { + self.process_include_line(line, options)?; + } else { + self.out.push_source_line(line, self.line_number); + self.scanner.record(line, &options.document_attributes); + } + Ok(()) + } + + fn process_include_line( + &mut self, + line: &'input str, + options: &mut Options<'_>, + ) -> Result<(), Error> { + let origin = self.out.origin_of_line(self.line_number); + let ctx = DirectiveContext { + input_line: self.line_number, + source_line: origin.line, + current_offset: origin.offset, + source_origin: self.source_origin.as_ref(), + }; + let blocked = if options.include_loader.provider().is_none() + && options.safe_mode != crate::SafeMode::Secure + { + Some("include not read because include loading is disabled".to_owned()) + } else { + self.preprocessor + .include_context + .blocked_limit(options.safe_mode) + .map(|limit| { + if limit == 0 { + "include not read because maximum include depth is zero".to_owned() + } else { + format!("maximum include depth of {limit} exceeded") + } + }) + }; + if let Some(message) = blocked { + self.preprocessor.recover_content_at( + message, + Preprocessor::create_source_location(ctx.source_line, ctx.current_file()), + ); + self.out.push_source_line(line, self.line_number); + self.scanner.record(line, &options.document_attributes); + return Ok(()); + } + self.out.flush_run(); + let Some(mut included) = self.preprocessor.process_include( + line, + ctx.source_line, + ctx.current_offset, + ctx.source_origin, + options, + super::IncludeContext { + block_context: self.scanner.block_context(), + ..self.preprocessor.include_context.clone() + }, + )? + else { + self.out.push_source_line(line, self.line_number); + self.scanner.record(line, &options.document_attributes); + return Ok(()); + }; + if let Some(input) = included.input.take() { + if let Some(attributes) = input.attributes { + options.document_attributes = attributes; + } + let normalized = Preprocessor::normalize(&included.content); + let text = self.arena.alloc_str(&normalized); + let front_matter = options + .document_attributes + .contains_key("skip-front-matter") + .then(|| skim_front_matter(text.lines())) + .flatten(); + let preprocessor = Preprocessor::nested(&self.preprocessor.warnings, input.context); + let cursor = Self::new( + &preprocessor, + text, + Some(&input.source_origin), + options, + input.line_origins, + front_matter, + self.arena, + ); + self.include = Some(IncludeFrame { + result: included, + cursor: Box::new(cursor), + input_line: self.line_number, + scope: input.scope, + }); + } else { + self.accept_include(included, self.line_number, options); + } + Ok(()) + } + + fn accept_include(&mut self, mut included: IncludeResult, line: usize, options: &Options<'_>) { + if let Some(context) = included.comment_context.take() { + self.scanner.record_preprocessed(&included.content, context); + } else { + self.scanner + .record_expansion(&included.content, &options.document_attributes); + } + Preprocessor::handle_include_result(included, &mut self.out, line); + } + + fn finish_include( + &mut self, + mut included: IncludeResult, + mut result: PreprocessorResult<'_>, + line: usize, + scope: Option, + options: &mut Options<'_>, + ) -> Result<(), Error> { + if let Some(scope) = scope { + scope.finish(&mut result, &mut options.document_attributes)?; + } + included.content = result.text.into_owned(); + included.leveloffset_ranges = result.leveloffset_ranges; + included.leveloffset_scopes = result.leveloffset_scopes; + included.source_ranges = result.source_ranges; + included.included_files.extend(result.included_files); + included.conditionals = result.conditionals; + included.comment_context = Some(result.comment_context); + self.accept_include(included, line, options); + Ok(()) + } + + fn skip_unchanged_include(&mut self, options: &Options<'_>) { + if self.preprocessor.include_context.depth == 0 + || self.line_number != 1 + || self.front_matter.is_some() + || self + .preprocessor + .nested_attributes_must_propagate(self.out.input) + { + return; + } + let Some(scanner) = self.preprocessor.try_pass_through( + self.out.input, + crate::grammar::setext::is_enabled(options.compatibility_mode), + options, + ) else { + return; + }; + for line in self.lines.by_ref() { + self.out.note_source_line(self.line_number); + self.out.byte_offset += line.len() + 1; + self.line_number += 1; + } + self.out.output.push(Cow::Borrowed(self.out.input)); + self.scanner = scanner; + } + + pub(super) fn read_all( + mut self, + options: &mut Options<'_>, + ) -> Result, Error> { + self.skip_unchanged_include(options); + loop { + if let Some(include) = self.include.take() { + let result = include.cursor.read_all(options)?; + self.finish_include( + include.result, + result, + include.input_line, + include.scope, + options, + )?; + } else if !self.advance(options)? { + break; + } + } + let file = self.source_origin.as_ref().and_then(SourceOrigin::as_path); + for frame in self.conditionals { + self.preprocessor.recover_content_at( + "conditional directive has no matching endif", + Preprocessor::create_source_location(frame.opening_line, file), + ); + } + Ok(self + .out + .into_result(self.front_matter, self.scanner.block_context())) + } +} diff --git a/acdc-parser/src/preprocessor/include.rs b/acdc-parser/src/preprocessor/include.rs index 87d124487..bf203d82e 100644 --- a/acdc-parser/src/preprocessor/include.rs +++ b/acdc-parser/src/preprocessor/include.rs @@ -76,7 +76,6 @@ use peg::include_parser; use std::{ cell::RefCell, collections::HashSet, - mem::take, path::{Component, Path, PathBuf}, rc::Rc, str::FromStr, @@ -87,7 +86,7 @@ use url::Url; use crate::{ CompatibilityMode, DocumentAttributeAssignment, DocumentAttributeValue, DocumentAttributes, IncludeSourceErrorKind, IncludeSourceProvider, IncludeSourceTarget, Location, Options, - Preprocessor, SafeMode, Warning, + SafeMode, Warning, document_attribute::{AttributeDeclaration, RawAttributeValue}, error::{Error, SourceLocation}, model::{LeveloffsetRange, Position, SourceRange}, @@ -378,8 +377,48 @@ pub(super) struct IncludeResult { pub(crate) source_ranges: Vec, pub(crate) included_files: HashSet, pub(crate) conditionals: Vec, - pub(crate) document_attributes: Option>, pub(super) comment_context: Option, + pub(super) input: Option, +} + +#[derive(Debug)] +pub(super) struct IncludeInput { + pub(super) source_origin: SourceOrigin, + pub(super) line_origins: Vec, + pub(super) context: IncludeContext, + pub(super) attributes: Option>, + pub(super) scope: Option, +} + +#[derive(Debug)] +pub(super) struct IncludeScope { + current: DocumentAttributeAssignment<'static>, + previous: DocumentAttributeAssignment<'static>, + mode: CompatibilityMode, + prefix: String, + suffix: String, +} + +impl IncludeScope { + pub(super) fn finish( + self, + result: &mut super::PreprocessorResult<'_>, + attributes: &mut DocumentAttributes<'_>, + ) -> Result<(), Error> { + let mut scanner = CommentScanner::new( + crate::grammar::setext::is_enabled(self.mode), + std::mem::take(&mut result.comment_context), + self.mode, + ); + scanner.record_expansion("\n\n", attributes); + if scanner.block_context().allows_scope_entry() { + Include::restore_leveloffset(attributes, self.previous, self.mode)?; + } + scanner.record(&self.suffix[2..], attributes); + result.comment_context = scanner.block_context(); + Include::wrap_leveloffset(result, self.current, attributes, &self.prefix, &self.suffix); + Ok(()) + } } enum UrlReadError { @@ -424,8 +463,8 @@ impl IncludeResult { source_ranges: Vec::new(), included_files: HashSet::new(), conditionals: Vec::new(), - document_attributes: None, comment_context: None, + input: None, } } @@ -446,8 +485,8 @@ impl IncludeResult { source_ranges: Vec::new(), included_files: HashSet::new(), conditionals: Vec::new(), - document_attributes: None, comment_context: None, + input: None, } } @@ -462,8 +501,8 @@ impl IncludeResult { source_ranges: Vec::new(), included_files: HashSet::new(), conditionals: Vec::new(), - document_attributes: None, comment_context: None, + input: None, } } } @@ -869,16 +908,22 @@ impl<'a> Include<'a> { source_ranges: Vec::new(), included_files: HashSet::new(), conditionals: Vec::new(), - document_attributes: None, comment_context: None, + input: None, }; if is_asciidoc { - self.preprocess_selected_asciidoc( - &mut included, - source_origin, - line_origins, - scoped_options, - )?; + included.input = Some(self.prepare_input(source_origin, line_origins, scoped_options)); + let full = match &self.selection { + ContentSelection::All => true, + ContentSelection::Lines(_) => false, + ContentSelection::Tags(filters) => super::tag::selects_all(filters), + }; + if full + && !self.opts.iter().any(|option| option == "partial") + && let Some(name) = source_origin.include_name() + { + included.included_files.insert(name); + } } else { included.source_ranges = Self::source_ranges_for_lines(&included.content, &line_origins, source_origin); @@ -909,31 +954,32 @@ impl<'a> Include<'a> { Ok(Some(options)) } - fn preprocess_selected_asciidoc( + fn prepare_input( &self, - included: &mut IncludeResult, source_origin: &SourceOrigin, line_origins: Vec, scoped_options: Option>>, - ) -> Result<(), Error> { + ) -> IncludeInput { let mut context = self.context.clone(); let scope = scoped_options.as_ref().map(|options| { let prefix = self.leveloffset_prefix(); let mut scanner = CommentScanner::new( crate::grammar::setext::is_enabled(self.options.compatibility_mode), - take(&mut context.block_context), + std::mem::take(&mut context.block_context), self.options.compatibility_mode, ); scanner.record_expansion(&prefix, &options.document_attributes); context.block_context = scanner.block_context(); - ( - Self::leveloffset_assignment(&options.document_attributes), + IncludeScope { + current: Self::leveloffset_assignment(&options.document_attributes), + previous: Self::leveloffset_assignment(&self.options.document_attributes), + mode: self.options.compatibility_mode, prefix, - format!( + suffix: format!( "\n\n{}", Self::leveloffset_control(&self.options.document_attributes) ), - ) + } }); if let Some(depth) = self.depth { let limit = context.depth.saturating_add(1).saturating_add(depth); @@ -942,64 +988,21 @@ impl<'a> Include<'a> { context.local_depth_limit = Some(depth); } } - let mut preprocessed = Preprocessor::nested(&self.warnings, context) - .process_mapped( - take(&mut included.content), - source_origin, - scoped_options.map_or_else(|| self.options.clone(), |options| *options), - line_origins, - ) - .inspect_err(|_| { - tracing::error!("failed to process included content"); - })?; - if let Some((current, prefix, suffix)) = scope { - let mut scanner = CommentScanner::new( - crate::grammar::setext::is_enabled(self.options.compatibility_mode), - preprocessed.result.comment_context, - self.options.compatibility_mode, - ); - scanner.record_expansion("\n\n", &preprocessed.document_attributes); - if scanner.block_context().allows_scope_entry() { - self.restore_leveloffset(&mut preprocessed.document_attributes)?; - } - scanner.record(&suffix[2..], &preprocessed.document_attributes); - preprocessed.result.comment_context = scanner.block_context(); - Self::wrap_leveloffset( - &mut preprocessed.result, - current, - &preprocessed.document_attributes, - &prefix, - &suffix, - ); + IncludeInput { + source_origin: source_origin.clone(), + line_origins, + context, + attributes: scoped_options.map(|options| options.document_attributes.into_static()), + scope, } - included.content = preprocessed.result.text.into_owned(); - included.leveloffset_ranges = preprocessed.result.leveloffset_ranges; - included.leveloffset_scopes = preprocessed.result.leveloffset_scopes; - included.source_ranges = preprocessed.result.source_ranges; - included.included_files = preprocessed.result.included_files; - included.conditionals = preprocessed.result.conditionals; - included.document_attributes = Some(preprocessed.document_attributes); - included.comment_context = Some(preprocessed.result.comment_context); - let full = match &self.selection { - ContentSelection::All => true, - ContentSelection::Lines(_) => false, - ContentSelection::Tags(filters) => super::tag::selects_all(filters), - }; - if full - && !self.opts.iter().any(|option| option == "partial") - && let Some(name) = source_origin.include_name() - { - included.included_files.insert(name); - } - Ok(()) } fn restore_leveloffset( - &self, - attributes: &mut DocumentAttributes<'static>, + attributes: &mut DocumentAttributes<'_>, + previous: DocumentAttributeAssignment<'static>, + mode: CompatibilityMode, ) -> Result<(), Error> { - let previous = Self::leveloffset_assignment(&self.options.document_attributes); - if self.options.compatibility_mode == CompatibilityMode::Draft { + if mode == CompatibilityMode::Draft { // Restore the already accepted snapshot without interpreting its text again. attributes.normalize_assignment("leveloffset".into(), previous); return Ok(()); @@ -1020,11 +1023,7 @@ impl<'a> Include<'a> { value, ignored_value: None, }; - super::attribute::apply_declaration( - &declaration, - attributes, - self.options.compatibility_mode, - ) + super::attribute::apply_declaration(&declaration, attributes, mode) } fn leveloffset_assignment( diff --git a/acdc-parser/src/preprocessor/include_budget_tests.rs b/acdc-parser/src/preprocessor/include_budget_tests.rs index 1e9ce9561..0cec7c6a7 100644 --- a/acdc-parser/src/preprocessor/include_budget_tests.rs +++ b/acdc-parser/src/preprocessor/include_budget_tests.rs @@ -105,6 +105,135 @@ fn assert_budget_error(result: Result, file: &str, line: u32) -> Ok(()) } +#[test] +fn resumable_input_applies_changes_before_later_conditionals_and_includes() -> TestResult { + let sources = Sources::new(&[("body.adoc", "Included.")]); + let mut options = sources.options()?; + let preprocessor = Preprocessor::new(&options, Rc::default()); + let arena = bumpalo::Bump::new(); + let source = SourceOrigin::entry_file( + &std::env::temp_dir().join("acdc-include-budget/entry.adoc"), + options.base_dir.as_deref(), + )?; + let input = "configure::[]\n\nifdef::enabled[]\ninclude::body.adoc[]\nendif::[]"; + let mut cursor = cursor::InputCursor::new( + &preprocessor, + input, + Some(&source), + &mut options, + Vec::new(), + None, + &arena, + ); + assert!(cursor.advance(&mut options)?); + assert_eq!(sources.opened(), Vec::::new()); + options + .document_attributes + .set_text("enabled".into(), "".into()); + let result = cursor.read_all(&mut options)?; + assert_eq!(result.text, "configure::[]\n\nIncluded."); + assert_eq!(sources.opened(), ["body.adoc"]); + assert!( + result + .conditionals + .first() + .ok_or("missing conditional")? + .is_active() + ); + let offset = result.text.find("Included.").ok_or("missing include")?; + let range = SourceRange::find_containing(&result.source_ranges, offset) + .ok_or("missing include source range")?; + assert_eq!( + range.file.as_deref().and_then(Path::file_name), + Some(std::ffi::OsStr::new("body.adoc")) + ); + assert_eq!(range.start_line, 1); + Ok(()) +} + +#[test] +fn resumable_input_does_not_open_a_later_include_before_advancing() -> TestResult { + let sources = Sources::new(&[("first.adoc", "First."), ("next.adoc", "Next.")]); + let mut options = sources.options()?; + let preprocessor = Preprocessor::new(&options, Rc::default()); + let arena = bumpalo::Bump::new(); + let source = SourceOrigin::entry_file( + &std::env::temp_dir().join("acdc-include-budget/entry.adoc"), + options.base_dir.as_deref(), + )?; + let mut cursor = cursor::InputCursor::new( + &preprocessor, + "include::first.adoc[]\ninclude::next.adoc[]", + Some(&source), + &mut options, + Vec::new(), + None, + &arena, + ); + assert_eq!(sources.opened(), Vec::::new()); + assert!(cursor.advance(&mut options)?); + assert_eq!(sources.opened(), ["first.adoc"]); + let result = cursor.read_all(&mut options)?; + assert_eq!(result.text, "First.\nNext."); + assert_eq!(sources.opened(), ["first.adoc", "next.adoc"]); + Ok(()) +} + +#[test] +fn resumable_input_pauses_inside_an_include_and_preserves_nested_source_chains() -> TestResult { + for mode in [ + crate::CompatibilityMode::Draft, + crate::CompatibilityMode::Asciidoctor, + ] { + let sources = Sources::new(&[ + ( + "outer.adoc", + "configure::[]\nifdef::enabled[]\ninclude::child.adoc[]\nendif::[]", + ), + ("child.adoc", "Nested."), + ("after.adoc", "After."), + ]); + let mut options = sources + .options()? + .into_builder() + .with_compatibility_mode(mode) + .build()?; + let preprocessor = Preprocessor::new(&options, Rc::default()); + let arena = bumpalo::Bump::new(); + let source = SourceOrigin::entry_file( + &std::env::temp_dir().join("acdc-include-budget/entry.adoc"), + options.base_dir.as_deref(), + )?; + let mut cursor = cursor::InputCursor::new( + &preprocessor, + "include::outer.adoc[]\ninclude::after.adoc[]", + Some(&source), + &mut options, + Vec::new(), + None, + &arena, + ); + assert!(cursor.advance(&mut options)?); + assert!(cursor.advance(&mut options)?); + assert_eq!(sources.opened(), ["outer.adoc"]); + options + .document_attributes + .set_text("enabled".into(), "".into()); + let result = cursor.read_all(&mut options)?; + assert_eq!(result.text, "configure::[]\nNested.\nAfter."); + assert_eq!(sources.opened(), ["outer.adoc", "child.adoc", "after.adoc"]); + let offset = result + .text + .find("Nested.") + .ok_or("missing nested content")?; + let range = SourceRange::find_containing(&result.source_ranges, offset) + .ok_or("missing nested source range")?; + assert_eq!(range.file_chain, ["outer.adoc", "child.adoc"]); + assert_eq!(range.start_line, 1); + } + Ok(()) +} + #[test] fn include_budget_is_shared_by_siblings_and_counts_utf8_bytes() -> TestResult { let sources = Sources::new(&[("a.log", "é"), ("b.log", "bbb")]); diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index 32c4ee62d..ef37b0881 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -24,6 +24,7 @@ use crate::{ mod attribute; mod comment; mod conditional; +mod cursor; mod include; #[cfg(test)] mod include_budget_tests; @@ -97,11 +98,6 @@ impl PreprocessorResult<'_> { } } -struct NestedPreprocessorResult { - result: PreprocessorResult<'static>, - document_attributes: DocumentAttributes<'static>, -} - #[derive(Debug)] struct SkimmedFrontMatter { value: String, @@ -751,7 +747,7 @@ fn decode_bytes(bytes: &[u8], encoding: Option<&str>, source: &str) -> Result>, include_context: IncludeContext, @@ -1363,83 +1359,6 @@ impl Preprocessor { Ok(false) } - fn process_directive_line<'input>( - &self, - line: &'input str, - ctx: &DirectiveContext<'_>, - options: &mut Options, - out: &mut PreprocessorState<'input>, - scanner: &mut CommentScanner, - ) -> Result<(), Error> { - if is_escaped_directive(line) { - out.note_source_line(ctx.input_line); - out.push_line(Cow::Borrowed(&line[1..])); - scanner.record(&line[1..], &options.document_attributes); - } else if has_include_directive_shape(line) { - // Disabled loading preserves the directive, except in Secure mode, - // which produces a link fallback without reading the target. - if options.include_loader.provider().is_none() - && options.safe_mode != crate::SafeMode::Secure - { - self.recover_content_at( - "include not read because include loading is disabled", - Self::create_source_location(ctx.source_line, ctx.current_file()), - ); - out.push_source_line(line, ctx.input_line); - scanner.record(line, &options.document_attributes); - return Ok(()); - } - if let Some(limit) = self.include_context.blocked_limit(options.safe_mode) { - let message = if limit == 0 { - "include not read because maximum include depth is zero".to_owned() - } else { - format!("maximum include depth of {limit} exceeded") - }; - self.recover_content_at( - message, - Self::create_source_location(ctx.source_line, ctx.current_file()), - ); - out.push_source_line(line, ctx.input_line); - scanner.record(line, &options.document_attributes); - return Ok(()); - } - // Included content carries its own source ranges; close the main-file - // run first so it does not overlap them. - out.flush_run(); - if let Some(mut include_result) = self.process_include( - line, - ctx.source_line, - ctx.current_offset, - ctx.source_origin, - options, - IncludeContext { - block_context: scanner.block_context(), - ..self.include_context.clone() - }, - )? { - if let Some(context) = include_result.comment_context.take() { - // The child has already resolved attribute-driven styles - // in source order. Replaying with caller values can differ. - scanner.record_preprocessed(&include_result.content, context); - } else { - scanner.record_expansion(&include_result.content, &options.document_attributes); - } - let document_attributes = include_result.document_attributes.take(); - Self::handle_include_result(include_result, out, ctx.input_line); - if let Some(document_attributes) = document_attributes { - options.document_attributes = document_attributes; - } - } else { - out.push_source_line(line, ctx.input_line); - scanner.record(line, &options.document_attributes); - } - } else { - out.push_source_line(line, ctx.input_line); - scanner.record(line, &options.document_attributes); - } - Ok(()) - } - #[tracing::instrument(skip_all, fields(input_len = input.len(), safe_mode = ?options.safe_mode))] fn process_inner<'input>( &self, @@ -1478,81 +1397,11 @@ impl Preprocessor { &normalized, source_origin, options, - setext, Vec::new(), front_matter, ) } - /// Preprocess a compacted include selection whose lines retain coordinates - /// in the original target. - fn process_mapped( - &self, - mut input: String, - source_origin: &SourceOrigin, - mut options: Options<'_>, - line_origins: Vec, - ) -> Result { - let normalized = Preprocessor::normalize(&input); - let setext = crate::grammar::setext::is_enabled(options.compatibility_mode); - let front_matter = options - .document_attributes - .contains_key("skip-front-matter") - .then(|| skim_front_matter(normalized.lines())) - .flatten(); - if front_matter.is_none() - && !self.nested_attributes_must_propagate(&normalized) - && let Some(scanner) = self.try_pass_through(&normalized, setext, &options) - { - let source_ranges = { - let normalized_ref = normalized.as_ref(); - let mut state = - PreprocessorState::new(normalized_ref, Some(source_origin), line_origins); - for (idx, line) in normalized_ref.lines().enumerate() { - state.note_source_line(idx + 1); - state.byte_offset += line.len() + 1; - } - state.flush_run(); - state.source_ranges - }; - let leveloffset_ranges = Self::initial_leveloffset_ranges(normalized.len(), &options); - let result = PreprocessorResult { - text: Cow::Owned(match normalized { - Cow::Borrowed(text) => { - let len = text.len(); - input.truncate(len); - input - } - Cow::Owned(text) => text, - }), - leveloffset_ranges, - leveloffset_scopes: Vec::new(), - source_ranges, - included_files: HashSet::new(), - conditionals: Vec::new(), - front_matter: None, - comment_context: scanner.block_context(), - }; - return Ok(NestedPreprocessorResult { - result, - document_attributes: options.document_attributes.into_static(), - }); - } - - let result = self.process_slow_path( - &normalized, - Some(source_origin), - &mut options, - setext, - line_origins, - front_matter, - )?; - Ok(NestedPreprocessorResult { - result: result.into_owned(), - document_attributes: options.document_attributes.into_static(), - }) - } - /// Rebuild a document that contains at least one preprocessor trigger. /// /// Keep this out of line so the much larger include/conditional machinery @@ -1564,133 +1413,20 @@ impl Preprocessor { normalized: &Cow<'input, str>, source_origin: Option<&SourceOrigin>, options: &mut Options<'_>, - setext: bool, line_origins: Vec, front_matter: Option, ) -> Result, Error> { - // Slow path: at least one trigger fires (include, conditional, - // multi-line attribute continuation, or escaped directive). Rebuild - // line-by-line. The output is materialized before `normalized` drops, - // whether normalization borrowed the caller's input or created a buffer. - let normalized_ref = normalized.as_ref(); - - let mut lines = normalized_ref.lines().peekable(); - let mut line_number = 1; - let mut out = PreprocessorState::new(normalized_ref, source_origin, line_origins); - out.record_leveloffset(options); - // Tracks verbatim-block and previous-line context so adjacent line - // comments can be dropped (matching asciidoctor's reader). See - // `comment::CommentScanner`. - let mut scanner = CommentScanner::new( - setext, - self.include_context.block_context.clone(), - options.compatibility_mode, - ); - let mut conditional_stack: Vec> = Vec::new(); - let captured_front_matter = consume_front_matter( - &mut lines, - &mut line_number, - self.include_context.depth == 0, + let arena = bumpalo::Bump::new(); + cursor::InputCursor::new( + self, + normalized.as_ref(), + source_origin, + options, + line_origins, front_matter, - ); - if let Some(value) = &captured_front_matter { - options - .document_attributes - .set_text("front-matter".into(), value.clone().into()); - } - - while let Some(line) = lines.next() { - // Keep raw comment lines and their source coordinates before - // considering directives or folding attribute continuations. - if conditional_stack.last().is_none_or(|frame| frame.active) - && scanner.preserves_comment_line(line) - { - out.push_source_line(line, line_number); - scanner.record(line, &options.document_attributes); - line_number += 1; - continue; - } - let origin = out.origin_of_line(line_number); - let ctx = DirectiveContext { - input_line: line_number, - source_line: origin.line, - current_offset: origin.offset, - source_origin, - }; - if self.process_conditional_line( - line, - &ctx, - &options.document_attributes, - &mut conditional_stack, - &mut out, - &mut scanner, - )? { - line_number += 1; - continue; - } - - if conditional_stack.last().is_some_and(|frame| !frame.active) { - line_number += 1; - continue; - } - - if scanner.allows_attribute_entries() && has_attribute_continuation(line) { - // Apply the joined value here, but emit the source lines - // unchanged: the grammar joins them again, so locations inside - // the entry stay in source coordinates. - let continuation_start_line = line_number; - let (attribute_content, continuation_lines) = - Self::process_continuation(line, &mut lines, &mut line_number); - attribute::parse_line(options, attribute_content.as_str())?; - out.record_leveloffset(options); - out.push_source_line(line, continuation_start_line); - for (offset, continued) in continuation_lines.into_iter().enumerate() { - out.push_source_line(continued, continuation_start_line + 1 + offset); - } - scanner.record(line, &options.document_attributes); - // `process_continuation` advanced `line_number` over the absorbed - // continuation lines but not the attribute line itself; the `continue` - // below skips the loop-tail increment, so account for it here to keep - // `line_number` aligned with the source for everything that follows. - line_number += 1; - continue; - } else if scanner.allows_attribute_entries() && line.starts_with(':') { - attribute::parse_line(options, line.trim())?; - } - out.record_leveloffset(options); - // Only emitted lines establish table/verbatim context; fences in - // excluded conditionals cannot affect the following content. - if scanner.at_table_delimiter(line) || scanner.at_verbatim_delimiter(line) { - out.push_source_line(line, line_number); - } else if line.starts_with("//") { - if scanner.drops(line) { - // Drop the adjacent comment; don't `record` it, so a run of - // comments after content is dropped together. The dropped line - // breaks source-line continuity, closing the current run when - // the next content line is emitted. - line_number += 1; - continue; - } - out.push_source_line(line, line_number); - } else if line.ends_with(']') && !line.starts_with('[') && line.contains("::") { - self.process_directive_line(line, &ctx, options, &mut out, &mut scanner)?; - line_number += 1; - continue; - } else { - out.push_source_line(line, line_number); - } - scanner.record(line, &options.document_attributes); - line_number += 1; - } - - let file = source_origin.and_then(SourceOrigin::as_path); - for frame in conditional_stack { - self.recover_content_at( - "conditional directive has no matching endif", - Self::create_source_location(frame.opening_line, file), - ); - } - Ok(out.into_result(captured_front_matter, scanner.block_context())) + &arena, + ) + .read_all(options) } fn initial_leveloffset_ranges(len: usize, options: &Options<'_>) -> Vec { @@ -1829,10 +1565,29 @@ mod tests { ); } + #[test] + fn disabled_include_keeps_slow_path_newline_normalization() -> Result<(), Error> { + for mode in [ + crate::CompatibilityMode::Asciidoctor, + crate::CompatibilityMode::Draft, + ] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(crate::SafeMode::Safe) + .with_include_loader(crate::IncludeLoader::Disabled) + .build()?; + let result = + Preprocessor::process("include::missing.adoc[]\n\n", &options, Rc::default())?; + assert_eq!(result.text, "include::missing.adoc[]"); + } + Ok(()) + } + #[test] fn mapped_include_fast_path_preserves_normalization() -> Result<(), Error> { - let options = Options::default(); - let preprocessor = Preprocessor::new(&options, Rc::default()); + let mut options = Options::default(); + let preprocessor = + Preprocessor::nested(&Rc::default(), IncludeContext::root(&options).nested()); let origin = SourceOrigin::Memory { base_dir: None }; for (input, expected) in [ ("", ""), @@ -1842,13 +1597,19 @@ mod tests { ("a \n", "a"), ("é\r\nb\r\n", "é\nb"), ] { - let result = preprocessor.process_mapped( - input.to_owned(), - &origin, - options.clone(), + let arena = bumpalo::Bump::new(); + let normalized = Preprocessor::normalize(input); + let result = cursor::InputCursor::new( + &preprocessor, + &normalized, + Some(&origin), + &mut options, Vec::new(), - )?; - assert_eq!(result.result.text, expected, "{input:?}"); + None, + &arena, + ) + .read_all(&mut options)?; + assert_eq!(result.text, expected, "{input:?}"); } Ok(()) } @@ -1877,8 +1638,8 @@ mod tests { source_ranges: Vec::new(), included_files: HashSet::new(), conditionals: Vec::new(), - document_attributes: None, comment_context: None, + input: None, }; Preprocessor::handle_regular_include_result(included, &mut state); assert_eq!(state.byte_offset, following_offset, "{content:?}"); @@ -2403,7 +2164,6 @@ endif::inner[]"; &source, None, &mut slow_options, - crate::grammar::setext::is_enabled(options.compatibility_mode), Vec::new(), None, )?; @@ -2450,7 +2210,6 @@ endif::inner[]"; &Cow::Borrowed(source.as_str()), None, &mut slow_options, - crate::grammar::setext::is_enabled(options.compatibility_mode), Vec::new(), None, )?; From 4ef9d655de5d08320713cd6cf3ca2bd16749261a Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 12 Nov 2026 09:33:38 +0100 Subject: [PATCH 04/55] refactor(parser): drive accepted document blocks outside PEG Reuse existing block rules through a top-level cursor and finalize the accepted tree outside the document grammar. Part of SC-535. Nested source-order integration remains open. --- acdc-parser/src/grammar/document.rs | 3 + .../src/grammar/document/coordinator.rs | 100 ++++++++ acdc-parser/src/grammar/document/finish.rs | 182 +++++++++++++ acdc-parser/src/grammar/document/peg.rs | 241 +++--------------- acdc-parser/src/grammar/document/tests.rs | 198 ++++++++------ acdc-parser/src/grammar/mod.rs | 2 +- acdc-parser/src/lib.rs | 2 +- acdc-parser/src/proptests/invariants.rs | 2 +- 8 files changed, 455 insertions(+), 275 deletions(-) create mode 100644 acdc-parser/src/grammar/document/coordinator.rs create mode 100644 acdc-parser/src/grammar/document/finish.rs diff --git a/acdc-parser/src/grammar/document.rs b/acdc-parser/src/grammar/document.rs index eaf0d31f4..e93742e5f 100644 --- a/acdc-parser/src/grammar/document.rs +++ b/acdc-parser/src/grammar/document.rs @@ -2,8 +2,10 @@ mod author; mod callouts; +mod coordinator; mod delimited; mod doctype; +mod finish; mod header; pub(super) mod lists; mod manpage; @@ -16,6 +18,7 @@ mod sections; mod table; mod verbatim; +pub(crate) use coordinator::document; pub(crate) use peg::document_parser; #[cfg(test)] diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs new file mode 100644 index 000000000..c7ed5d67d --- /dev/null +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -0,0 +1,100 @@ +//! Ordered construction at accepted block boundaries. + +use crate::{ + Block, Document, DocumentAttributes, Error, + grammar::{ParserState, helpers::PositionWithOffset}, +}; + +use super::{document_parser, finish, header::ParsedHeader, metadata::order_block_prefix_events}; + +type RecognitionError = peg::error::ParseError; + +pub(super) struct DocumentPrefix<'a> { + pub(super) start: PositionWithOffset, + pub(super) header: ParsedHeader<'a>, + pub(super) attributes: Option>, + pub(super) comments: Vec>, + pub(super) body_offset: usize, +} + +pub(super) struct BlockStep<'a> { + pub(super) block: Option>, + pub(super) trailing: Vec>, + pub(super) end: usize, + pub(super) complete: bool, +} + +impl<'a> BlockStep<'a> { + pub(super) fn block(block: Block<'a>, end: usize) -> Self { + Self { + block: Some(block), + trailing: Vec::new(), + end, + complete: false, + } + } + + pub(super) fn end(trailing: Vec>, end: usize) -> Self { + Self { + block: None, + trailing, + end, + complete: true, + } + } +} + +pub(super) struct BlockCursor { + offset: usize, +} + +impl BlockCursor { + pub(super) fn new(offset: usize) -> Self { + Self { offset } + } + + pub(super) fn advance<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + ) -> Result, Error>, RecognitionError> { + let step = document_parser::next_block(input, state, self.offset)?; + if let Ok(step) = &step { + self.offset = step.end; + } + Ok(step) + } +} + +pub(crate) fn document<'a>( + input: &'a str, + state: &mut ParserState<'a>, +) -> Result, Error>, RecognitionError> { + let prefix = match document_parser::document_prefix(input, state)? { + Ok(prefix) => prefix, + Err(error) => return Ok(Err(error)), + }; + let mut cursor = BlockCursor::new(prefix.body_offset); + let mut blocks = prefix.comments; + let end = loop { + let step = match cursor.advance(input, state)? { + Ok(step) => step, + Err(error) => return Ok(Err(error)), + }; + if let Some(block) = step.block { + blocks.push(block); + } + if step.complete { + blocks.extend(step.trailing); + break step.end; + } + }; + Ok(finish::finish( + state, + prefix.start, + end, + prefix.header, + prefix.attributes, + order_block_prefix_events(blocks), + )) +} diff --git a/acdc-parser/src/grammar/document/finish.rs b/acdc-parser/src/grammar/document/finish.rs new file mode 100644 index 000000000..c1887c886 --- /dev/null +++ b/acdc-parser/src/grammar/document/finish.rs @@ -0,0 +1,182 @@ +//! Finalization over the accepted document tree. + +use std::collections::{HashMap, HashSet}; + +use crate::{ + Block, Document, DocumentAttributes, Error, Header, Location, Position, Warning, WarningKind, + grammar::{ParserState, helpers::PositionWithOffset}, + model::{caption, section}, +}; + +use super::{ + doctype::is_book_doctype, + header::ParsedHeader, + references::{ + CrossReferenceUse, ReferenceCatalog, collect_header_references, collect_references, + finalize_inline_semantics, normalize_bibliography_lists, register_document_references, + resolve_source_target, resolve_xref_target, + }, +}; + +pub(super) fn finish<'a>( + state: &mut ParserState<'a>, + start: PositionWithOffset, + end: usize, + parsed_header: ParsedHeader<'a>, + attributes: Option>, + mut blocks: Vec>, +) -> Result, Error> { + let attributes = attributes.unwrap_or_else(|| state.take_untitled_header_attributes()); + let ParsedHeader { + mut header, + untitled_location: untitled_header_location, + } = parsed_header; + warn_section_levels(state, header.as_ref(), &blocks); + normalize_bibliography_lists(state, &mut blocks); + crate::grammar::reference_text::resolve_tree(state, &mut header, &mut blocks)?; + super::table::finalize_footnotes(&mut blocks); + caption::renumber_captions(&mut blocks); + + let header_has_anchor = header + .as_ref() + .is_some_and(|header| header.metadata.id.is_some() || !header.metadata.anchors.is_empty()); + let mut references = ReferenceCatalog { + entries: HashMap::with_capacity(state.toc_entries.len() + usize::from(header_has_anchor)), + next_suffix: HashMap::new(), + natural_targets: HashMap::new(), + }; + let mut xrefs = Vec::new(); + if let Some(header) = &header { + collect_header_references(state, header, &attributes, &mut references, &mut xrefs); + } + collect_references(state, &mut blocks, &mut references, &mut xrefs); + section::number_parsed_sections( + &mut blocks, + &mut state.toc_entries, + &mut references.entries, + is_book_doctype(&attributes), + ); + + let mut document = Document { + header, + untitled_header_location, + location: document_location(state, start, end), + attributes, + blocks, + footnotes: state.footnote_tracker.borrow().footnotes.clone(), + toc_entries: state.toc_entries.clone(), + references: references.entries, + }; + register_document_references( + state, + &mut document, + &xrefs, + &mut references.natural_targets, + )?; + let reference_ids = document.references.keys().copied().collect::>(); + validate_references( + state, + &mut document, + xrefs, + &reference_ids, + &references.natural_targets, + ); + finalize_inline_semantics( + state, + &mut document, + &reference_ids, + &references.natural_targets, + )?; + Ok(document) +} + +fn document_location(state: &ParserState<'_>, start: PositionWithOffset, end: usize) -> Location { + let mut end = end.min(state.input.len()); + while end < state.input.len() && !state.input.is_char_boundary(end) { + end += 1; + } + if end != 0 { + end = crate::grammar::utf8_utils::safe_decrement_offset(state.input, end); + } + // Whitespace-only input can put the start beyond the last content byte. + let absolute_end = end.max(start.offset); + let (start_position, end_position) = + if state.input.is_empty() || (start.offset == 0 && absolute_end == 0) { + (Position::new(1, 0), Position::new(1, 0)) + } else { + ( + start.position, + state.line_map.offset_to_position(absolute_end, state.input), + ) + }; + Location { + absolute_start: start.offset, + absolute_end, + start: start_position, + end: end_position, + } +} + +fn warn_section_levels(state: &ParserState<'_>, header: Option<&Header<'_>>, blocks: &[Block<'_>]) { + if state.toc_entries.is_empty() { + return; + } + let mut anchored = header.is_some_and(|header| !header.title.is_empty()); + let mut seen_section = false; + for block in blocks { + if let Block::Section(section) = block { + // Without a title or preamble, the first section establishes the base level. + if !anchored { + break; + } + if section.level > 1 { + state.add_warning(Warning::new( + WarningKind::SectionLevelOutOfSequence { + expected: 1, + got: section.level, + }, + Some(state.create_error_source_location(section.location.clone())), + )); + } + seen_section = true; + } else if !seen_section && !matches!(block, Block::Comment(_)) { + anchored = true; + } + } +} + +fn validate_references<'a>( + state: &ParserState<'a>, + document: &mut Document<'a>, + xrefs: Vec>, + reference_ids: &HashSet<&'a str>, + natural_targets: &HashMap<&'a str, &'a str>, +) { + for xref in xrefs { + let source_target = resolve_source_target(state, xref.target, xref.source_syntax); + let target = source_target.unwrap_or_else(|| { + resolve_xref_target( + xref.target, + xref.resolve_natural_target, + reference_ids, + natural_targets, + ) + }); + let local = source_target.is_some() || xref.source_syntax.target_is_local(target); + if local + && xref.automatic + && let Some(reference) = document.references.get_mut(target) + && reference.is_bibliography() + { + reference.automatic_citation = true; + } + if local && !reference_ids.contains(target) { + state.add_warning(Warning::new( + WarningKind::UnresolvedReference { + target: target.to_owned(), + }, + Some(state.create_error_source_location(xref.location)), + )); + } + } +} diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index a8f55f0f0..ee4c030d8 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -6,9 +6,9 @@ use crate::{ Anchor, Attribution, Audio, Author, Block, BlockMetadata, CalloutList, CalloutListItem, CalloutMarker, CiteTitle, Comment, CommentKind, CompatibilityMode, DelimitedBlock, DelimitedBlockType, DescriptionList, DescriptionListDefinition, DescriptionListItem, - DescriptionListTerm, DiscreteHeading, Document, DocumentAttribute, DocumentAttributes, Error, - Header, Image, InlineNode, ListItem, ListItemCheckedStatus, Location, OrderedList, PageBreak, - Paragraph, Plain, Position, Section, Source, Subtitle, TableOfContents, ThematicBreak, Title, + DescriptionListTerm, DiscreteHeading, DocumentAttribute, DocumentAttributes, Error, Header, + Image, InlineNode, ListItem, ListItemCheckedStatus, Location, OrderedList, PageBreak, + Paragraph, Plain, Section, Source, Subtitle, TableOfContents, ThematicBreak, Title, UnorderedList, Video, Warning, WarningKind, document_attribute::{ AttributeDeclaration, RawAttributeValue, join_wrapped_value, starts_like_entry_name, @@ -21,6 +21,7 @@ use crate::{ }, document::{ author::{derive_author_attrs, register_author_attrs}, + coordinator::{BlockStep, DocumentPrefix}, delimited::{DelimitedKind, DelimitedParams, build_delimited_block}, doctype::{is_book_doctype, is_manpage_doctype}, header::{ParsedHeader, header_span, merge_header_metadata}, @@ -42,12 +43,7 @@ use crate::{ thematic_break_anchors, }, paragraph::{ParagraphParams, build_paragraph, paragraph_text_end}, - references::{ - ParsedSectionHeader, ReferenceCatalog, collect_header_references, - collect_references, finalize_inline_semantics, normalize_bibliography_lists, - register_document_references, register_section_header, resolve_source_target, - resolve_xref_target, - }, + references::{ParsedSectionHeader, register_section_header}, revision::{IgnoredRevisionFields, RevisionInfo, process_revision_info}, sections::{apply_leveloffset, expected_child_level}, table::{ @@ -64,16 +60,9 @@ use crate::{ setext, state::{BlockContext, UntitledHeaderEntries}, }, - model::{ - ListLevel, SectionKind, SectionLevel, Substitution, caption, section, substitution::HEADER, - }, -}; -use std::{ - borrow::Cow, - collections::{HashMap, HashSet}, - ops::Range, - rc::Rc, + model::{ListLevel, SectionKind, SectionLevel, Substitution, substitution::HEADER}, }; +use std::{borrow::Cow, ops::Range, rc::Rc}; peg::parser! { pub(crate) grammar document_parser(state: &mut ParserState<'input>) for str { @@ -84,193 +73,43 @@ peg::parser! { inject span_start(_input, l, _r) -> usize { l } inject span_end(_input, _l, r) -> usize { r } - // The document location excludes leading and trailing empty lines. - pub(crate) rule document() -> Result, Error> - = eol()* start:position() comments_before_header:(comment:leading_comment() eol()* { comment })* header_result:header() prepare_manpage_front_matter() header_attributes:header_attribute_snapshot() blocks:blocks(0, None, None) end:position!() (eol()* / ![_]) { - let ParsedHeader { header, untitled_location: untitled_header_location } = header_result?; - let header_attributes = header_attributes.unwrap_or_else(|| state.take_untitled_header_attributes()); - let mut blocks: Vec> = comments_before_header.into_iter().collect::, Error>>()?.into_iter().chain(blocks?).collect(); - - // Ensure end offset is on a valid UTF-8 boundary - let mut document_end_offset = end; - if document_end_offset > state.input.len() { - document_end_offset = state.input.len(); - } - // If not on a boundary, round forward to the next boundary - while document_end_offset < state.input.len() && !state.input.is_char_boundary(document_end_offset) { - document_end_offset += 1; - } - let document_end_offset = if document_end_offset == 0 { - 0 - } else { - crate::grammar::utf8_utils::safe_decrement_offset(state.input, document_end_offset) - }; - - // Ensure the invariant: absolute_start <= absolute_end - let (absolute_start, absolute_end) = if start.offset > document_end_offset { - // This can happen with whitespace-only input where eol()* consumes all content - // In this case, treat as an empty document at the start position - (start.offset, start.offset) - } else { - (start.offset, document_end_offset) - }; + #[no_eof] + pub(in crate::grammar::document) rule document_prefix() -> Result, Error> + = eol()* start:position() + comments:(comment:leading_comment() eol()* { comment })* + header:header() prepare_manpage_front_matter() + attributes:header_attribute_snapshot() body_offset:position!() + { + Ok(DocumentPrefix { + start, + header: header?, + attributes, + comments: comments.into_iter().collect::>()?, + body_offset, + }) + } - // Special case for truly empty input: TCK expects column 0 - // Only for zero-byte input, not whitespace-only - let (start_position, end_position) = if state.input.is_empty() || (absolute_start == 0 && absolute_end == 0) { - // Whitespace-only documents should use column 1 - (Position::new(1, 0), Position::new(1, 0)) + // Jump to an accepted boundary without rescanning or copying its prefix. + rule resume_at(offset: usize) + = #{|input, _| { + if input.is_char_boundary(offset) { + peg::RuleResult::Matched(offset, ()) } else { - ( - start.position, - state.line_map.offset_to_position(absolute_end, state.input) - ) - }; - - // Warn when a top-level section skips level 1 (e.g. a document that - // jumps straight to `=== Heading`). Matches asciidoctor's "section - // title out of sequence" check. - // - // The document root sits at level 0 — so every top-level section is - // expected at level 1 — once it is "anchored" by a document title or - // by preamble body content (a paragraph, list, ...) before the first - // section. When anchored, asciidoctor flags *each* top-level section - // deeper than level 1 (not just the first). A document that opens - // directly with a section (no title, no preamble) is not anchored: - // that first section sets the base level and neither it nor its - // same-or-shallower siblings are out of sequence. Comments are - // transparent and never anchor. Sections nested under another section - // are validated separately, in the `section` rule itself. - // - // `toc_entries` is populated while parsing and is empty exactly when - // the document has no sections — checking it first lets section-less - // documents skip the body scan entirely. Otherwise we walk only the - // top-level blocks (preamble + sibling sections, never nested content) - // and stop at the first section in the un-anchored case. - if !state.toc_entries.is_empty() { - let mut anchored = header.as_ref().is_some_and(|h| !h.title.is_empty()); - let mut seen_section = false; - for block in &blocks { - if let Block::Section(section) = block { - if !anchored { - // Un-anchored leading section: it establishes the base - // level, so neither it nor its siblings can be out of - // sequence. Nothing left to check. - break; - } - if section.level > 1 { - let location = state - .create_error_source_location(section.location.clone()); - state.add_warning(Warning::new( - WarningKind::SectionLevelOutOfSequence { - expected: 1, - got: section.level, - }, - Some(location), - )); - } - seen_section = true; - } else if !seen_section && !matches!(block, Block::Comment(_)) { - // Preamble content before the first section anchors the - // document at level 0. - anchored = true; - } - } - } - - // Assign caption ordinals over the finished tree. Numbering here cannot be - // disturbed by PEG backtracking, and it runs before the reference catalog so that - // catalog can later carry a target's caption label and ordinal. - normalize_bibliography_lists(state, &mut blocks); - let mut header = header; - crate::grammar::reference_text::resolve_tree(state, &mut header, &mut blocks)?; - crate::grammar::document::table::finalize_footnotes(&mut blocks); - caption::renumber_captions(&mut blocks); - - let header_has_anchor = header.as_ref().is_some_and(|header| { - header.metadata.id.is_some() || !header.metadata.anchors.is_empty() - }); - let mut references = ReferenceCatalog { - entries: HashMap::with_capacity(state.toc_entries.len() + usize::from(header_has_anchor)), - next_suffix: HashMap::new(), - natural_targets: HashMap::new(), - }; - let mut xrefs = Vec::new(); - if let Some(header) = &header { - collect_header_references(state, header, &header_attributes, &mut references, &mut xrefs); - } - collect_references(state, &mut blocks, &mut references, &mut xrefs); - let is_book = is_book_doctype(&header_attributes); - section::number_parsed_sections( - &mut blocks, - &mut state.toc_entries, - &mut references.entries, - is_book, - ); - let toc_entries = state.toc_entries.clone(); - - let mut document = Document { - header, - untitled_header_location, - // Source remapping assigns each boundary its own file after parsing. - // A document can start in the entry file and end in an included file. - location: Location { - absolute_start, - absolute_end, - start: start_position, - end: end_position, - }, - attributes: header_attributes, - blocks, - footnotes: state.footnote_tracker.borrow().footnotes.clone(), - toc_entries, - references: references.entries, - }; - register_document_references(state, &mut document, &xrefs, &mut references.natural_targets)?; - let reference_ids = document.references.keys().copied().collect::>(); - - // An internal `<>` whose target is absent from the catalog is an - // unresolved (broken) reference. Inter-document/external targets - // (those addressing another resource) are not validated here. - for xref in xrefs { - let source_target = resolve_source_target(state, xref.target, xref.source_syntax); - let target = source_target.unwrap_or_else(|| resolve_xref_target( - xref.target, - xref.resolve_natural_target, - &reference_ids, - &references.natural_targets, - )); - let target_is_local = source_target.is_some() - || xref.source_syntax.target_is_local(target); - if target_is_local && xref.automatic - && let Some(reference) = document.references.get_mut(target) - && reference.is_bibliography() - { - reference.automatic_citation = true; - } - if target_is_local && !reference_ids.contains(target) - { - let source_location = state.create_error_source_location(xref.location); - state.add_warning(Warning::new( - WarningKind::UnresolvedReference { - target: target.to_string(), - }, - Some(source_location), - )); - } + peg::RuleResult::Failed } - finalize_inline_semantics( - state, - &mut document, - &reference_ids, - &references.natural_targets, - )?; - Ok(document) - } + }} - // When the header reads entries among the first block's metadata, the - // body applies them, so the snapshot waits for the last one. See - // `untitled_header_entries`. + #[no_eof] + pub(in crate::grammar::document) rule next_block(offset: usize) -> Result, Error> + = resume_at(offset) step:( + !trailing_block_metadata_match() block:block(0, None, None) end:position!() + { block.map(|block| BlockStep::block(block, end)) } + / trailing:trailing_block_metadata(0)? end:position!() eol()* ![_] + { trailing.transpose().map(|blocks| BlockStep::end(blocks.unwrap_or_default(), end)) } + ) { step } + + // Header entries among the first block's metadata are applied by the body. + // Defer the snapshot until those entries have been processed. rule header_attribute_snapshot() -> Option> = { if state.untitled_header_entries.is_some() { diff --git a/acdc-parser/src/grammar/document/tests.rs b/acdc-parser/src/grammar/document/tests.rs index 6f1d4a365..8c769b6b8 100644 --- a/acdc-parser/src/grammar/document/tests.rs +++ b/acdc-parser/src/grammar/document/tests.rs @@ -1,4 +1,7 @@ -use super::{document_parser, paragraph::paragraph_text_end}; +use super::{ + coordinator::BlockCursor, document as parse_document, document_parser, + paragraph::paragraph_text_end, +}; use crate::{ Anchor, AttributeValue, Block, CommentKind, CompatibilityMode, DelimitedBlock, DelimitedBlockType, Document, Error, Image, InlineMacro, InlineNode, Location, Options, Plain, @@ -8,6 +11,59 @@ use crate::{ parse, }; +#[test] +fn block_cursor_does_not_apply_later_attributes_before_advancing() +-> Result<(), Box> { + let input = "before\n\n:later: value\n\n{later}"; + let mut state = ParserState::new_for_test(input); + let prefix = document_parser::document_prefix(input, &mut state)??; + let mut cursor = BlockCursor::new(prefix.body_offset); + + let first = cursor.advance(input, &mut state)??; + assert!(matches!(first.block, Some(Block::Paragraph(_)))); + assert!(!first.complete); + assert_eq!(state.document_attributes.text("later"), None); + + let assignment = cursor.advance(input, &mut state)??; + assert!(matches!( + assignment.block, + Some(Block::DocumentAttribute(_)) + )); + assert_eq!(state.document_attributes.text("later"), Some("value")); + + let last = cursor.advance(input, &mut state)??; + let Some(Block::Paragraph(paragraph)) = last.block else { + return Err("expected the final paragraph".into()); + }; + assert!( + matches!(paragraph.content.as_slice(), [InlineNode::PlainText(plain)] if plain.content == "value") + ); + assert!(cursor.advance(input, &mut state)??.complete); + Ok(()) +} + +#[test] +fn block_cursor_applies_a_committed_change_to_the_next_block() +-> Result<(), Box> { + let input = "before\n\n{extension-value}"; + let mut state = ParserState::new_for_test(input); + let prefix = document_parser::document_prefix(input, &mut state)??; + let mut cursor = BlockCursor::new(prefix.body_offset); + let first = cursor.advance(input, &mut state)??; + assert!(first.block.is_some()); + + std::rc::Rc::make_mut(&mut state.document_attributes) + .set_text("extension-value".into(), "after".into()); + let second = cursor.advance(input, &mut state)??; + let Some(Block::Paragraph(paragraph)) = second.block else { + return Err("expected a paragraph after the committed change".into()); + }; + assert!( + matches!(paragraph.content.as_slice(), [InlineNode::PlainText(plain)] if plain.content == "after") + ); + Ok(()) +} + #[test] fn paragraph_runs_stop_before_line_boundaries_and_anchor_openers() { for (source, start, end) in [ @@ -45,7 +101,7 @@ v2.9, 01-09-2024: Fall incarnation :sectanchors: :url-repo: https://my-git-repo.com"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let header = result.header.expect("document has a header"); assert_eq!(header.title.len(), 1); assert_eq!( @@ -272,7 +328,7 @@ Roberto Avanzi v2.0, 2026-01-15: rel :foo: bar"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let header = result.header.expect("document has a header"); assert_eq!(header.authors.len(), 1); assert_eq!(header.authors[0].first_name, "Roberto"); @@ -290,7 +346,7 @@ v2.0, 2026-01-15: rel fn test_authorcount_defaults_to_zero_without_author() -> Result<(), Error> { let input = "= T\n\nbody"; let mut state = ParserState::new_for_test(input); - document_parser::document(input, &mut state)??; + parse_document(input, &mut state)??; assert_eq!(state.document_attributes.text("authorcount"), Some("0")); Ok(()) } @@ -400,7 +456,7 @@ fn test_title_only_document_is_doctitle() -> Result<(), Error> { // single-line `= Doc Title\n` source. let input = "= Doc Title"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let header = doc.header.expect("title-only doc should have a header"); assert_eq!(header.title.len(), 1); assert_eq!( @@ -638,7 +694,7 @@ fn test_toc_simple() -> Result<(), Error> { let input = "= Document Title\n\n== Section 1\n\nSome content.\n\n== Section 2\n\nMore content."; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; assert_eq!(result.toc_entries.len(), 2); assert_eq!(result.toc_entries[0].level, 1); @@ -653,7 +709,7 @@ fn test_toc_simple() -> Result<(), Error> { fn test_toc_tree() -> Result<(), Error> { let input = "= Document Title\n\n== Section A\n\nContent A.\n\n=== Section A.1\n\nContent A.1\n\n== Section B\n\nContent B."; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; assert_eq!(result.toc_entries.len(), 3); assert_eq!(result.toc_entries[0].id, "_section_a"); @@ -669,7 +725,7 @@ fn test_section_kind_classifies_special_sections() -> Result<(), Error> { // handles any suppression inherited from a special parent. let input = "= Title\n\n[preface]\n== Introduction\n\nintro\n\n=== Features\n\nfeatures\n\n== Real Chapter\n\ntext"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let mut sections = Vec::new(); fn collect<'a, 'b>(blocks: &'b [Block<'a>], out: &mut Vec<&'b Section<'a>>) { @@ -700,7 +756,7 @@ fn test_section_kind_appendix() -> Result<(), Error> { // `[appendix]` is classified as Appendix; its plain subsection is Normal. let input = "= Title\n:doctype: book\n\n[appendix]\n== App\n\napp\n\n=== App Sub\n\nsub"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; assert_eq!(result.toc_entries.len(), 2); assert_eq!(result.toc_entries[0].kind, SectionKind::Appendix); @@ -713,7 +769,7 @@ fn test_section_kind_appendix() -> Result<(), Error> { fn test_toc_empty_document() -> Result<(), Error> { let input = "= Document Title\n\nJust some content without sections."; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; assert_eq!(result.toc_entries.len(), 0); Ok(()) } @@ -727,7 +783,7 @@ fn test_setext_document_title() -> Result<(), Error> { Some content. "; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let header = result.header.expect("document has a header"); assert_eq!(header.title.len(), 1); assert!( @@ -747,7 +803,7 @@ Section One Content. "; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let section = result.blocks.iter().find_map(|b| { if let Block::Section(s) = b { @@ -788,7 +844,7 @@ Section One Content here. "; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let header = result.header.expect("document has a header"); assert!( @@ -838,7 +894,7 @@ Section C Content C. "; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let header = result.header.expect("document has a header"); assert!( @@ -894,7 +950,7 @@ fn test_setext_all_underline_characters() -> Result<(), Error> { // Test level 1 with - let input = "= Doc\n\nLevel One\n---------\n\nContent.\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let section = result .blocks .iter() @@ -911,7 +967,7 @@ fn test_setext_all_underline_characters() -> Result<(), Error> { // Test level 2 with ~ let input = "= Doc\n\nLevel Two\n~~~~~~~~~\n\nContent.\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let section = result .blocks .iter() @@ -928,7 +984,7 @@ fn test_setext_all_underline_characters() -> Result<(), Error> { // Test level 3 with ^ let input = "= Doc\n\nLevel Three\n^^^^^^^^^^^\n\nContent.\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let section = result .blocks .iter() @@ -945,7 +1001,7 @@ fn test_setext_all_underline_characters() -> Result<(), Error> { // Test level 4 with + let input = "= Doc\n\nLevel Four\n++++++++++\n\nContent.\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let section = result .blocks .iter() @@ -967,7 +1023,7 @@ fn test_setext_all_underline_characters() -> Result<(), Error> { fn test_setext_manpage_style_document() -> Result<(), Error> { let input = "gitdatamodel(7)\n===============\n\nNAME\n----\ngitdatamodel - Git's core data model\n\nSYNOPSIS\n--------\ngitdatamodel\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let header = result.header.expect("document has a header"); assert!( @@ -1073,7 +1129,7 @@ fn test_index_term_flow() -> Result<(), Error> { let input = "= Test\n\nThis is about ((Arthur)) the king.\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let paragraph = result .blocks @@ -1111,7 +1167,7 @@ fn test_index_term_concealed() -> Result<(), Error> { let input = "= Test\n\n(((Sword, Broadsword)))This is a concealed index term.\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let paragraph = result .blocks @@ -1168,7 +1224,7 @@ fn test_macro_attributes_allow_literal_special_chars() -> Result<(), Error> { let input = "image::photo.jpg[Diablo 4 picture of Lilith.]"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let img = get_image(&result); assert_eq!( img.alt @@ -1186,7 +1242,7 @@ fn test_macro_attributes_allow_literal_special_chars() -> Result<(), Error> { // Test .role as literal text (not a shorthand) let input = "image::photo.jpg[.role]"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let img = get_image(&result); assert_eq!( img.alt @@ -1208,7 +1264,7 @@ fn test_macro_attributes_allow_literal_special_chars() -> Result<(), Error> { // Test #id as literal text (not a shorthand) let input = "image::photo.jpg[Issue #42]"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let img = get_image(&result); assert_eq!( img.alt @@ -1229,7 +1285,7 @@ fn test_macro_attributes_allow_literal_special_chars() -> Result<(), Error> { let input = "image::photo.jpg[role=thumbnail]"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let img = get_image(&result); assert_eq!( img.metadata.roles.as_slice(), @@ -1245,7 +1301,7 @@ fn test_macro_attributes_allow_literal_special_chars() -> Result<(), Error> { fn test_block_macro_uses_last_closing_bracket() -> Result<(), Error> { let input = "image::foo.svg[role=inline][100,100]\n\n[.lead]\nHello\n"; let mut state = ParserState::new_for_test(input); - let result = document_parser::document(input, &mut state)??; + let result = parse_document(input, &mut state)??; let image = result.blocks.iter().find_map(|block| { if let Block::Image(image) = block { @@ -1355,7 +1411,7 @@ fn test_grammar_warning_falls_back_to_entry_file() { fn test_first_section_not_level_1_emits_warning() -> Result<(), Error> { let input = "= Doc Title\n\n=== Starts at level 2\n\nContent\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); let warning = warnings .iter() @@ -1382,7 +1438,7 @@ fn test_first_section_not_level_1_emits_warning() -> Result<(), Error> { fn test_level0_appendix_level2_subsection_no_warning() -> Result<(), Error> { let input = "= Book\n:doctype: book\n\n= Part One\n\n== Chapter\n\nbody\n\n[appendix]\n= App Part\n\nintro\n\n=== First Subsection\n\nbody\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -1398,7 +1454,7 @@ fn test_level0_preface_level2_subsection_no_warning() -> Result<(), Error> { let input = "= Book\n:doctype: book\n\n[preface]\n= Preface\n\nintro\n\n=== Background\n\nbody\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -1416,7 +1472,7 @@ fn test_level0_preface_level2_subsection_no_warning() -> Result<(), Error> { fn test_level0_appendix_level3_child_still_warns() -> Result<(), Error> { let input = "= Book\n:doctype: book\n\n= Part One\n\n== Chapter\n\nbody\n\n[appendix]\n= App Part\n\nintro\n\n==== Too Deep\n\nbody\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( warnings.iter().any(|w| matches!( @@ -1438,7 +1494,7 @@ fn test_level0_appendix_level3_child_still_warns() -> Result<(), Error> { fn test_titleless_preamble_then_deep_section_emits_warning() -> Result<(), Error> { let input = "term:: desc\n\n===== Deep\n\ntext\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( warnings.iter().any(|w| matches!( @@ -1459,7 +1515,7 @@ fn test_titleless_preamble_then_deep_section_emits_warning() -> Result<(), Error fn test_titleless_bare_deep_section_no_warning() -> Result<(), Error> { let input = "===== Deep\n\ntext\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -1477,7 +1533,7 @@ fn test_titleless_bare_deep_section_no_warning() -> Result<(), Error> { fn test_multiple_top_level_sections_each_warn() -> Result<(), Error> { let input = "= Doc Title\n\n===== One\n\ntext\n\n===== Two\n\ntext\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); let count = warnings .iter() @@ -1504,7 +1560,7 @@ fn test_multiple_top_level_sections_each_warn() -> Result<(), Error> { fn test_bare_deep_section_siblings_no_warning() -> Result<(), Error> { let input = "===== One\n\ntext\n\n===== Two\n\ntext\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -1524,7 +1580,7 @@ fn test_comment_style_block_dropped() -> Result<(), Error> { let input = "[comment]\n--\nhidden\n\n== Hidden heading\n--\n\n[comment]\nhidden para.\n\nVisible.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; assert_eq!(doc.blocks.len(), 3); // The open block: a `--`-delimited DelimitedComment (no leftover @@ -1565,7 +1621,7 @@ fn test_comment_style_block_dropped() -> Result<(), Error> { fn test_comment_style_on_listing_renders() -> Result<(), Error> { let input = "[comment]\n----\nvisible\n----\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; assert_eq!(doc.blocks.len(), 1); assert!( matches!( @@ -1584,7 +1640,7 @@ fn test_comment_style_on_listing_renders() -> Result<(), Error> { fn test_unresolved_reference_warns() -> Result<(), Error> { let input = "A paragraph.\n\nSee <>.\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( warnings.iter().any(|w| matches!( @@ -1602,7 +1658,7 @@ fn test_unresolved_reference_warns() -> Result<(), Error> { fn test_inline_anchor_reference_resolves() -> Result<(), Error> { let input = "Some text [[here]] in a paragraph.\n\nSee <>.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; assert!(doc.references.contains_key("here")); let warnings = state.warnings.borrow(); assert!( @@ -1623,7 +1679,7 @@ fn test_formatted_inline_ids_resolve_cross_references() -> Result<(), Error> { See <>, <>, <>, <>, <>, <>, <>, and <>. "#; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; for id in [ "bold-id", @@ -1665,7 +1721,7 @@ link:https://example.net[,id=bare-id] After: <>, <>, <>, and <>. "; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; for id in ["link-id", "url-id", "mailto-id", "bare-id"] { let Some(reference) = doc.references.get(id) else { @@ -1693,7 +1749,7 @@ link:https://example.org[Second,id=duplicate] link:https://example.net[Text,positional-id] "; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; assert_eq!( doc.references @@ -1715,7 +1771,7 @@ link:https://example.net[Text,positional-id] fn test_callout_item_inline_anchor_resolves() -> Result<(), Error> { let input = "----\ncode <1>\n----\n<1> Note with an [[cnote]] anchor.\n\nSee <>.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; assert!(doc.references.contains_key("cnote")); let warnings = state.warnings.borrow(); assert!( @@ -1731,7 +1787,7 @@ fn test_callout_item_inline_anchor_resolves() -> Result<(), Error> { fn test_callout_item_explicit_continuation_attaches_block() -> Result<(), Error> { let input = "----\nfirst <1>\nsecond <2>\n----\n<1> First explanation.\n+\nAttached paragraph.\n<2> Second explanation.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let list = doc .blocks .iter() @@ -1881,7 +1937,7 @@ fn nested_list_principals_keep_plus_prefixed_text( fn test_titled_block_collected_in_references() -> Result<(), Error> { let input = "[[data-table]]\n.Important Data\n[cols=\"1,1\"]\n|===\n| a | b\n|===\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let entry = doc .references .get("data-table") @@ -1902,7 +1958,7 @@ fn test_titled_block_collected_in_references() -> Result<(), Error> { fn natural_title_cross_references_resolve_to_section_ids() -> Result<(), Error> { let input = "Generated: <>.\n\nCustom: <>.\n\nExplicit: <>.\n\nExplicit title: <>.\n\nMissing: <>.\n\n== Syntax Highlighting\n\n[#explicit-id]\n== Explicit Title\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let xrefs = doc .blocks .iter() @@ -1950,7 +2006,7 @@ fn named_section_reftext_populates_catalog_toc_and_warnings() -> Result<(), Box> { let input = include_str!("../../../fixtures/tests/named_section_reftext_cross_references.adoc"); let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let reference = doc.references.get("id").ok_or("missing id reference")?; assert!( matches!( @@ -2041,7 +2097,7 @@ fn passthrough_xref_warnings_use_restored_targets_and_source_locations() -> Resu fn compat_mode_skips_natural_title_cross_reference_resolution() -> Result<(), Error> { let input = "= Document\n:compat-mode:\n\nNatural: <>.\n\nExplicit: <<_syntax_highlighting>>.\n\n== Syntax Highlighting\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let targets = doc .blocks .iter() @@ -2081,7 +2137,7 @@ fn compat_mode_skips_natural_title_cross_reference_resolution() -> Result<(), Er fn compat_mode_natural_reference_resolution_follows_source_position() -> Result<(), Error> { let input = "Before set: <>.\n\n:compat-mode:\n\nAfter set: <>.\n\n:compat-mode!:\n\nAfter unset: <>.\n\n== First Natural\n\n== Second Natural\n\n== Third Natural\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let targets = doc .blocks .iter() @@ -2123,7 +2179,7 @@ fn compat_mode_natural_reference_resolution_follows_source_position() -> Result< fn interdocument_xref_macro_targets_are_not_naturally_resolved() -> Result<(), Error> { let input = "Empty: xref:Other.adoc[].\n\nExplicit: xref:Other.adoc[Other].\n\nShorthand: <>.\n\nFragment: xref:Foo#Bar[].\n\n== Other.adoc\n\n== Foo#Bar\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let targets = doc .blocks .iter() @@ -2155,7 +2211,7 @@ fn interdocument_xref_macro_targets_are_not_naturally_resolved() -> Result<(), E fn natural_title_cross_references_resolve_setext_section_ids() -> Result<(), Error> { let input = "See <>.\n\nSetext Title\n------------\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let xrefs = doc .blocks .iter() @@ -2180,7 +2236,7 @@ fn natural_title_cross_references_resolve_setext_section_ids() -> Result<(), Err fn captioned_references_keep_source_order_xrefstyle_and_target_caption() -> Result<(), Error> { let input = "= Caption references\n:xrefstyle: short\n\nShort: <>.\n\n:table-caption: ReferenceTable\n:xrefstyle: full\n\nFull: <>.\n\n:xrefstyle: basic\n\nBasic: <>.\n\n:table-caption:\n:xrefstyle: short\n\nNumber only: <>.\n\n:table-caption!:\n\nTarget label: <>.\n\n:table-caption: TargetTable\n\n[[figure-target]]\n.A figure\nimage::figure.svg[]\n\n[[table-target]]\n.A table\n|===\n|Cell\n|===\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let xrefs = doc .blocks .iter() @@ -2250,7 +2306,7 @@ fn captioned_references_keep_source_order_xrefstyle_and_target_caption() -> Resu fn test_titled_single_line_admonition_keeps_reference_title() -> Result<(), Error> { let input = "[[notice]]\n.Admonition *Title*\nNOTE: note\n\nSee <>.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let entry = doc .references .get("notice") @@ -2289,7 +2345,7 @@ fn test_titled_single_line_admonition_keeps_reference_title() -> Result<(), Erro fn test_untitled_block_in_references_without_reftext() -> Result<(), Error> { let input = "[[untitled]]\n[cols=\"1,1\"]\n|===\n| a | b\n|===\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let entry = doc .references .get("untitled") @@ -2309,7 +2365,7 @@ fn test_untitled_block_in_references_without_reftext() -> Result<(), Error> { fn test_duplicate_id_keeps_first_reference_text() -> Result<(), Error> { let input = "[[dup]]\n.Titled Block\n====\nbody\n====\n\nA [#dup]*bold* span.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let entry = doc .references .get("dup") @@ -2334,7 +2390,7 @@ fn test_duplicate_id_keeps_first_reference_text() -> Result<(), Error> { fn test_reference_label_is_parsed_as_inlines() -> Result<(), Error> { let input = "Some [[labelled,*Bold* label]]text.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let label = doc .references .get("labelled") @@ -2361,7 +2417,7 @@ fn test_reference_label_is_parsed_as_inlines() -> Result<(), Error> { fn test_reference_label_restores_passthrough_syntax() -> Result<(), Error> { let input = "Some [[labelled,+++Label+++]]text.\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let label = doc .references .get("labelled") @@ -2384,7 +2440,7 @@ fn test_reference_label_restores_passthrough_syntax() -> Result<(), Error> { fn test_nested_passthrough_retains_substitution_policy() -> Result<(), Error> { let input = "*before +++nested+++ after*\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; assert!( matches!( &doc.blocks[..], @@ -2415,7 +2471,7 @@ fn test_nested_passthrough_retains_substitution_policy() -> Result<(), Error> { fn test_non_standard_author_line_emits_warning() -> Result<(), Error> { let input = "= Doc Title\nAuthor: Roberto Avanzi (Lead), Ruud Derwig\n:foo: bar\n\nBody.\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); let warning = warnings .iter() @@ -2440,7 +2496,7 @@ fn test_non_standard_author_line_emits_warning() -> Result<(), Error> { fn test_legacy_float_discrete_heading_warns() -> Result<(), Error> { let input = "== Parent\n\n[float]\n==== Floating\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( warnings @@ -2463,7 +2519,7 @@ fn test_no_legacy_float_warning() -> Result<(), Error> { "= Doc\n\n[#f,float]\n=== Ordinary Section\n", ] { let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -2481,7 +2537,7 @@ fn test_no_legacy_float_warning() -> Result<(), Error> { fn test_standard_author_line_no_warning() -> Result<(), Error> { let input = "= Doc Title\nRoberto Avanzi\n:foo: bar\n\nBody.\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -2500,7 +2556,7 @@ fn test_incomplete_final_row_emits_dropping_warning() -> Result<(), Error> { // The lone `|g` on line 5 cannot complete a 3-column row. let input = "[cols=\"3*\"]\n|===\n|a |b |c\n|d |e |f\n|g\n|===\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); let warning = warnings .iter() @@ -2519,7 +2575,7 @@ fn test_incomplete_final_row_emits_dropping_warning() -> Result<(), Error> { fn test_first_section_without_doc_title_does_not_warn() -> Result<(), Error> { let input = "=== No title above me\n\nContent\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -2535,7 +2591,7 @@ fn test_first_section_without_doc_title_does_not_warn() -> Result<(), Error> { fn test_first_section_level_1_no_warning() -> Result<(), Error> { let input = "= Doc Title\n\n== Good\n\n=== Nested\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -2553,7 +2609,7 @@ fn test_first_section_level_1_no_warning() -> Result<(), Error> { fn test_unterminated_pipe_table_emits_warning() -> Result<(), Error> { let input = "|===\n| A | B\n| C | D\n"; let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); let warning = warnings @@ -2590,7 +2646,7 @@ fn test_unterminated_pipe_table_emits_warning() -> Result<(), Error> { fn test_unterminated_excl_table_emits_warning() -> Result<(), Error> { let input = "!===\n! A ! B\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( warnings.iter().any(|w| matches!( @@ -2618,7 +2674,7 @@ fn test_warning_in_ascii_cell_points_at_inner_token() -> Result<(), Error> { // 6: `|===` let input = "[cols=\"1a\"]\n|===\na|\n!===\n! Inner A ! Inner B\n|===\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); let warning = warnings .iter() @@ -2645,7 +2701,7 @@ fn test_warning_in_ascii_cell_points_at_inner_token() -> Result<(), Error> { fn test_terminated_table_does_not_warn() -> Result<(), Error> { let input = "|===\n| A | B\n|===\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings @@ -2664,7 +2720,7 @@ fn test_terminated_table_does_not_warn() -> Result<(), Error> { fn test_unterminated_pipe_table_with_no_content_emits_warning() -> Result<(), Error> { let input = "|===\n"; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( warnings.iter().any(|w| matches!( @@ -2720,7 +2776,7 @@ fn test_unterminated_delimited_blocks_emit_warning() -> Result<(), Error> { for (block, want_kind, want_delim) in cases { let input = &format!("para\n\n{block}"); let mut state = ParserState::new_for_test(input); - let doc = document_parser::document(input, &mut state)??; + let doc = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( warnings.iter().any(|w| matches!( @@ -2749,7 +2805,7 @@ fn test_unterminated_delimited_blocks_emit_warning() -> Result<(), Error> { fn test_terminated_delimited_block_no_warning() -> Result<(), Error> { let input = "====\ntext\n===="; let mut state = ParserState::new_for_test(input); - let _ = document_parser::document(input, &mut state)??; + let _ = parse_document(input, &mut state)??; let warnings = state.warnings.borrow(); assert!( !warnings diff --git a/acdc-parser/src/grammar/mod.rs b/acdc-parser/src/grammar/mod.rs index 0165b1c1c..bdedcdebf 100644 --- a/acdc-parser/src/grammar/mod.rs +++ b/acdc-parser/src/grammar/mod.rs @@ -29,7 +29,7 @@ mod utf8_utils; pub(crate) use attributes::{ BlockAttributeMode, block_attribute_line, block_attribute_style, style_overrides_block_form, }; -pub(crate) use document::document_parser; +pub(crate) use document::{document as parse_document, document_parser}; pub(crate) use inline_preprocessor::{ InlinePreprocessorParserState, ProcessedContent, inline_preprocessing, }; diff --git a/acdc-parser/src/lib.rs b/acdc-parser/src/lib.rs index 96314202b..ea9164b4e 100644 --- a/acdc-parser/src/lib.rs +++ b/acdc-parser/src/lib.rs @@ -577,7 +577,7 @@ fn parse_input( if state.document_attributes.contains_key("toc2") { state.add_warning(Warning::new(WarningKind::DeprecatedToc2Attribute, None)); } - let result = match grammar::document_parser::document(&owner.source, &mut state) { + let result = match grammar::parse_document(&owner.source, &mut state) { Ok(Ok(mut doc)) => { grammar::reference_text::finish_document(&mut state, &mut doc)?; if let Some(session) = session diff --git a/acdc-parser/src/proptests/invariants.rs b/acdc-parser/src/proptests/invariants.rs index 62b5bb941..b6323c798 100644 --- a/acdc-parser/src/proptests/invariants.rs +++ b/acdc-parser/src/proptests/invariants.rs @@ -85,7 +85,7 @@ proptest! { let arena = bumpalo::Bump::new(); let mut state = crate::grammar::ParserState::new(&result.text, &arena, Rc::new(options.clone())); state.leveloffset_ranges = result.leveloffset_ranges; - if let Ok(Ok(doc)) = crate::grammar::document_parser::document(&result.text, &mut state) { + if let Ok(Ok(doc)) = crate::grammar::parse_document(&result.text, &mut state) { let text = &result.text; walk_document_locations(&doc, &mut |loc, ctx| { assert!( From f631b89fdad9b86bb730f2417fe3b523fe18c62c Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 12 Nov 2026 16:53:46 +0100 Subject: [PATCH 05/55] refactor(parser): construct committed containers outside PEG Build section children, compound bodies, list attachments, quote bodies, and AsciiDoc table cells after their recognizers return. Reuse the native recognizers, metadata handling, and builders while retaining the ordinary recursive parsing path. Keep handler failures fatal through content recovery and preserve caption, footnote, attribute-scope, and diagnostic ordering. The accepted-block execution boundary remains internal. Public registry callbacks retain their existing post-document timing pending A2. SC-535 remains In Progress: cooperative source integration and performance acceptance follow in separate changes. Validated checkpoint: 12,562 workspace tests, 118 doctests, strict workspace Clippy, 1,221 feature-off tests, formatting, and diff checks. No existing fixture expectations were changed. Refs: SC-535 --- acdc-parser/CHANGELOG.md | 5 +- acdc-parser/src/extensions/mod.rs | 1 + acdc-parser/src/extensions/tests/mod.rs | 47 +- acdc-parser/src/extensions/traversal.rs | 50 +- acdc-parser/src/grammar/document.rs | 4 + .../src/grammar/document/construction.rs | 135 ++ .../grammar/document/construction/tests.rs | 901 ++++++++++ .../src/grammar/document/coordinator.rs | 384 ++++- acdc-parser/src/grammar/document/delimited.rs | 212 ++- acdc-parser/src/grammar/document/lists.rs | 382 ++++- .../src/grammar/document/lists/callout.rs | 118 ++ .../grammar/document/lists/construction.rs | 217 +++ .../src/grammar/document/lists/description.rs | 177 ++ acdc-parser/src/grammar/document/peg.rs | 1480 +++++++---------- acdc-parser/src/grammar/document/quotes.rs | 130 ++ acdc-parser/src/grammar/document/table.rs | 103 +- .../grammar/document/table/construction.rs | 156 ++ acdc-parser/src/grammar/document/tests.rs | 173 +- 18 files changed, 3682 insertions(+), 993 deletions(-) create mode 100644 acdc-parser/src/grammar/document/construction.rs create mode 100644 acdc-parser/src/grammar/document/construction/tests.rs create mode 100644 acdc-parser/src/grammar/document/lists/callout.rs create mode 100644 acdc-parser/src/grammar/document/lists/construction.rs create mode 100644 acdc-parser/src/grammar/document/lists/description.rs create mode 100644 acdc-parser/src/grammar/document/quotes.rs create mode 100644 acdc-parser/src/grammar/document/table/construction.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 35945eb81..a0d156539 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -189,7 +189,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `extensions::Registry`. Each document has fresh processor state. Typed queries cover nested containers and discrete headings. Stable target handles support ID assignment, literal paragraphs and lists, placeholder replacement and - section removal. Edits repair references, TOC and scoped footnotes while + section removal. Macros in nested sections retain source-position attribute + snapshots and original invocation locations in both compatibility modes. + Empty registries and unused registrations preserve ordinary diagnostic order. + Edits repair references, TOC and scoped footnotes while preserving surviving section and caption numbers. Call `ExtensionParseResult::finish()` before conversion or checked ASG export; unresolved requests return a located error. Callbacks run after parsing and diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index fcdefa975..2e1571c76 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -101,6 +101,7 @@ mod registry; mod session; mod target; mod traversal; +pub(crate) use traversal::{TablePart, compound_body_mut, ordinary_list_items_mut, table_cell_mut}; mod tree_processor; pub use block_macro::{ diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index a23d8d809..551fe4525 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -233,16 +233,49 @@ impl BlockMacroProcessor for Never { #[test] fn extensions_empty_or_unused_registry_preserves_document_and_warnings() -> TestResult { - let input = include_str!("../../../fixtures/tests/xref_nested_sections.adoc"); let options = Options::default(); - let ordinary = acdc_parser::parse(input, &options)?; - for registry in [Registry::default(), support::registry()] { - let parsed = registry.parse(input, &options)?; + for input in [ + include_str!("../../../fixtures/tests/xref_nested_sections.adoc"), + "= Document\n\n== Parent\n\n==== Skipped\n\n[subs=unknown]\nText", + ] { + let ordinary = acdc_parser::parse(input, &options)?; + for registry in [Registry::default(), support::registry()] { + let parsed = registry.parse(input, &options)?; + assert_eq!( + parsed.parsed.document_storage(), + ordinary.document_storage() + ); + assert_eq!(parsed.parsed.warnings(), ordinary.warnings()); + } + } + Ok(()) +} + +#[test] +fn extensions_nested_sections_preserve_source_position_attribute_snapshots() -> TestResult { + let input = "== Parent\n\n:mode: outer\n\ndefer::parent[]\n\n=== Child\n\n:mode: inner\n\ndefer::child[]\n\n== Sibling\n\ndefer::sibling[]\n\n:mode: later"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let parsed = support::registry().parse(input, &options)?; + let invocations: Vec<_> = parsed + .deferred_blocks() + .iter() + .map(|request| { + ( + request.invocation.target.as_ref(), + request.invocation.document_attributes.text("mode"), + request.invocation.location.location.start.line, + ) + }) + .collect(); assert_eq!( - parsed.parsed.document_storage(), - ordinary.document_storage() + invocations, + [ + ("parent", Some("outer"), 5), + ("child", Some("inner"), 11), + ("sibling", Some("inner"), 15), + ] ); - assert_eq!(parsed.parsed.warnings(), ordinary.warnings()); } Ok(()) } diff --git a/acdc-parser/src/extensions/traversal.rs b/acdc-parser/src/extensions/traversal.rs index 71f996053..a33ab7324 100644 --- a/acdc-parser/src/extensions/traversal.rs +++ b/acdc-parser/src/extensions/traversal.rs @@ -1,4 +1,4 @@ -use crate::{Block, ColumnStyle, DelimitedBlockType, Table}; +use crate::{Block, ColumnStyle, DelimitedBlockType, ListItem, Table, TableCell}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Children { @@ -12,7 +12,7 @@ pub(super) enum Children { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum TablePart { +pub(crate) enum TablePart { Head, Body, Foot, @@ -147,11 +147,8 @@ impl Children { | DelimitedBlockType::DelimitedVerse(_) | DelimitedBlockType::DelimitedStem(_) => None, }, - (Self::Item(index), Block::UnorderedList(block)) => { - Some(&mut block.items.get_mut(index)?.blocks) - } - (Self::Item(index), Block::OrderedList(block)) => { - Some(&mut block.items.get_mut(index)?.blocks) + (Self::Item(index), block @ (Block::UnorderedList(_) | Block::OrderedList(_))) => { + Some(&mut ordinary_list_items_mut(block)?.get_mut(index)?.blocks) } (Self::Item(index), Block::CalloutList(block)) => { Some(&mut block.items.get_mut(index)?.blocks) @@ -163,18 +160,45 @@ impl Children { let DelimitedBlockType::DelimitedTable(table) = &mut block.inner else { return None; }; - let rows = match part { - TablePart::Head => table.header.as_mut_slice(), - TablePart::Body => &mut table.rows, - TablePart::Foot => table.footer.as_mut_slice(), - }; - Some(&mut rows.get_mut(row)?.columns.get_mut(column)?.content) + Some(&mut table_cell_mut(table, part, row, column)?.content) } _ => None, } } } +pub(crate) fn table_cell_mut<'doc, 'a>( + table: &'doc mut Table<'a>, + part: TablePart, + row: usize, + column: usize, +) -> Option<&'doc mut TableCell<'a>> { + let rows = match part { + TablePart::Head => table.header.as_mut_slice(), + TablePart::Body => &mut table.rows, + TablePart::Foot => table.footer.as_mut_slice(), + }; + rows.get_mut(row)?.columns.get_mut(column) +} + +pub(crate) fn compound_body_mut<'doc, 'a>( + block: &'doc mut Block<'a>, +) -> Option<&'doc mut Vec>> { + Children::Body.get_mut(block) +} + +pub(crate) fn ordinary_list_items_mut<'doc, 'a>( + block: &'doc mut Block<'a>, +) -> Option<&'doc mut Vec>> { + if let Block::UnorderedList(block) = block { + Some(&mut block.items) + } else if let Block::OrderedList(block) = block { + Some(&mut block.items) + } else { + None + } +} + fn compound<'doc, 'a>(inner: &'doc DelimitedBlockType<'a>) -> Option<&'doc [Block<'a>]> { match inner { DelimitedBlockType::DelimitedExample(blocks) diff --git a/acdc-parser/src/grammar/document.rs b/acdc-parser/src/grammar/document.rs index e93742e5f..54e449a2e 100644 --- a/acdc-parser/src/grammar/document.rs +++ b/acdc-parser/src/grammar/document.rs @@ -2,6 +2,7 @@ mod author; mod callouts; +mod construction; mod coordinator; mod delimited; mod doctype; @@ -12,6 +13,7 @@ mod manpage; mod metadata; mod paragraph; mod peg; +mod quotes; mod references; mod revision; mod sections; @@ -21,6 +23,8 @@ mod verbatim; pub(crate) use coordinator::document; pub(crate) use peg::document_parser; +type RecognitionError = ::peg::error::ParseError<::peg::str::LineCol>; + #[cfg(test)] #[allow( clippy::indexing_slicing, diff --git a/acdc-parser/src/grammar/document/construction.rs b/acdc-parser/src/grammar/document/construction.rs new file mode 100644 index 000000000..903835d9d --- /dev/null +++ b/acdc-parser/src/grammar/document/construction.rs @@ -0,0 +1,135 @@ +//! Requests retained after a block recognizer has returned. + +use std::ops::ControlFlow; + +use crate::{ + Block, Error, + grammar::{ParserState, helpers::BlockParsingMetadata}, +}; + +use super::{ + coordinator::BlockStepKind, + delimited::{ + ContentParser, ContentRequest, DelimitedParams, build_delimited_block_with_parser, + }, + lists::{ListEntry, ListKind}, + metadata::assign_block_caption, + quotes::{QuoteParams, build_quote_with_parser}, + table::{TableParseParams, construction::TableConstruction}, +}; + +/// Shared block dispatch retains the metadata until its content form commits. +pub(super) type RecognizedContent<'a> = ControlFlow, Block<'a>>; + +pub(super) enum DeferredContent<'a> { + Delimited(DelimitedParams<'a>), + Table(TableParseParams<'a>), + Quote(QuoteParams<'a>), + List { + start: usize, + body_offset: usize, + kind: ListKind<'a>, + }, +} + +pub(super) fn commit_content<'a>( + state: &mut ParserState<'a>, + metadata: BlockParsingMetadata<'a>, + content: RecognizedContent<'a>, +) -> BlockStepKind<'a> { + match content { + ControlFlow::Continue(mut block) => { + assign_block_caption(state, &mut block); + BlockStepKind::Block(block) + } + ControlFlow::Break(DeferredContent::Delimited(params)) => { + BlockStepKind::Delimited(DelimitedConstruction { metadata, params }) + } + ControlFlow::Break(DeferredContent::Table(params)) => { + BlockStepKind::Table(TableConstruction { metadata, params }) + } + ControlFlow::Break(DeferredContent::Quote(params)) => { + BlockStepKind::Quote(QuoteConstruction { metadata, params }) + } + ControlFlow::Break(DeferredContent::List { + start, + body_offset, + kind, + }) => BlockStepKind::List(ListEntry { + start, + body_offset, + metadata: Some(metadata), + kind, + }), + } +} + +/// Ordinary parsing retains complete PEG construction. The ordered mode +/// returns accepted parents before constructing their child blocks. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum ConstructionMode { + Recursive, + Ordered, +} + +pub(super) struct DelimitedConstruction<'a> { + pub(super) metadata: BlockParsingMetadata<'a>, + pub(super) params: DelimitedParams<'a>, +} + +pub(super) struct QuoteConstruction<'a> { + metadata: BlockParsingMetadata<'a>, + params: QuoteParams<'a>, +} + +impl<'a> QuoteConstruction<'a> { + pub(super) fn start( + self, + state: &mut ParserState<'a>, + ) -> Result<(Block<'a>, Option>), Error> { + let mut content = CaptureContent::default(); + let block = build_quote_with_parser(state, &self.metadata, &self.params, &mut content)?; + Ok((block, content.request)) + } +} + +#[derive(Default)] +struct CaptureContent<'a> { + request: Option>, +} + +impl<'a> ContentParser<'a> for CaptureContent<'a> { + fn parse( + &mut self, + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + ) -> Result>, Error> { + if self.request.is_some() { + return Err(Error::Parse( + Box::new(state.create_error_source_location( + state.create_location(request.offset, request.offset), + )), + "compound builder requested more than one child body".into(), + )); + } + self.request = Some(request); + Ok(Vec::new()) + } +} + +#[cfg(test)] +mod tests; + +impl<'a> DelimitedConstruction<'a> { + /// Build the parent with its existing builder, retaining the child request + /// until the accepted parent handler releases its borrow. + pub(super) fn start( + self, + state: &mut ParserState<'a>, + ) -> Result<(Block<'a>, Option>), Error> { + let mut content = CaptureContent::default(); + let block = + build_delimited_block_with_parser(state, &self.metadata, &self.params, &mut content)?; + Ok((block, content.request)) + } +} diff --git a/acdc-parser/src/grammar/document/construction/tests.rs b/acdc-parser/src/grammar/document/construction/tests.rs new file mode 100644 index 000000000..801459aa9 --- /dev/null +++ b/acdc-parser/src/grammar/document/construction/tests.rs @@ -0,0 +1,901 @@ +use std::{path::PathBuf, rc::Rc}; + +use crate::{ + Block, CompatibilityMode, DelimitedBlockType, Error, InlineNode, Options, WarningKind, + grammar::{ParserState, state::BlockContext}, + model::SourceRange, +}; + +use super::super::{construction::ConstructionMode, coordinator::document_with}; + +type TestResult = Result<(), Box>; + +#[rstest::rstest] +#[case::open(include_str!("../../../../fixtures/tests/open_block_with_paragraphs.adoc"))] +#[case::styled_open(include_str!("../../../../fixtures/tests/styled_open_blocks.adoc"))] +#[case::open_context(include_str!("../../../../fixtures/tests/styled_open_contexts.adoc"))] +#[case::quote(include_str!("../../../../fixtures/tests/compatibility_quote_content.adoc"))] +#[case::quote_snapshots(include_str!("../../../../fixtures/tests/compatibility_quote_snapshots.adoc"))] +#[case::quote_locations(include_str!("../../../../fixtures/tests/compatibility_quote_locations.adoc"))] +#[case::admonition(include_str!("../../../../fixtures/tests/admonition_block.adoc"))] +#[case::admonition_forms(include_str!("../../../../fixtures/tests/admonition_source_forms.adoc"))] +#[case::delimited_header(include_str!("../../../../fixtures/tests/delimited_block_with_header.adoc"))] +#[case::delimited_section(include_str!("../../../../fixtures/tests/delimited_block_within_section.adoc"))] +#[case::listing(include_str!("../../../../fixtures/tests/source_block_with_delimiter_in_content.adoc"))] +#[case::literal(include_str!("../../../../fixtures/tests/literal_block_with_comments.adoc"))] +#[case::passthrough(include_str!("../../../../fixtures/tests/passthrough_block_with_comments.adoc"))] +#[case::comment(include_str!("../../../../fixtures/tests/comment_block_style.adoc"))] +#[case::stem(include_str!("../../../../fixtures/tests/stem_blocks.adoc"))] +#[case::caption_after_body( + "= Captions\n:example-caption: Old\n\n.Before body\n====\n:example-caption: New\n\nText.\n====\n\n.After body\n====\nText.\n====" +)] +#[case::unicode("Préface 世界.\n\n== Hèading\n\n====\nÉxample 世界.\n\n****\n嵌套.\n****\n====")] +fn compound_driver_preserves_existing_construction(#[case] input: &str) -> TestResult { + assert_equivalent(input) +} + +fn assert_equivalent(input: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let reference_arena = bumpalo::Bump::new(); + let ordered_arena = bumpalo::Bump::new(); + let options = Rc::new(Options::builder().with_compatibility_mode(mode).build()?); + let mut reference_state = ParserState::new(input, &reference_arena, Rc::clone(&options)); + let mut ordered_state = ParserState::new(input, &ordered_arena, options); + let reference = document_with( + input, + &mut reference_state, + ConstructionMode::Recursive, + &mut |_, _| Ok(()), + )??; + let ordered = document_with( + input, + &mut ordered_state, + ConstructionMode::Ordered, + &mut |_, _| Ok(()), + )??; + assert_eq!(ordered, reference, "{mode:?}"); + let reference_warnings = + std::mem::take(&mut *reference_state.warnings.borrow_mut()).into_vec(); + let ordered_warnings = std::mem::take(&mut *ordered_state.warnings.borrow_mut()).into_vec(); + assert_eq!(ordered_warnings, reference_warnings, "{mode:?}"); + } + Ok(()) +} + +#[test] +fn compound_driver_commits_parents_before_constructing_children() -> TestResult { + let input = "== Parent\n\n====\n{value}\n\n****\n{value}\n****\n====\n\n{value}"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let arena = bumpalo::Bump::new(); + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut state = ParserState::new(input, &arena, Rc::new(options)); + let mut locations = Vec::new(); + let mut paragraphs = Vec::new(); + document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + locations.push(block.location().absolute_start); + if let Block::DelimitedBlock(block) = block + && let DelimitedBlockType::DelimitedExample(body) + | DelimitedBlockType::DelimitedSidebar(body) = &block.inner + { + assert_eq!(body, &Vec::>::new()); + let value = if matches!(block.inner, DelimitedBlockType::DelimitedExample(_)) { + "example" + } else { + "sidebar" + }; + Rc::make_mut(&mut state.document_attributes) + .set_text("value".into(), value.into()); + } + if let Block::Paragraph(paragraph) = block + && let [InlineNode::PlainText(plain)] = paragraph.content.as_slice() + { + paragraphs.push(plain.content); + } + Ok(()) + }, + )??; + assert_eq!(locations.len(), 6); + assert!( + locations + .iter() + .zip(locations.iter().skip(1)) + .all(|(a, b)| a < b) + ); + assert_eq!(paragraphs, ["example", "sidebar", "sidebar"]); + assert_eq!(state.block_context, BlockContext::Document); + } + Ok(()) +} + +#[rstest::rstest] +#[case::primary(None, 3)] +#[case::included(Some(PathBuf::from("/virtual/part.adoc")), 41)] +fn compound_driver_restores_context_when_a_child_handler_fails( + #[case] file: Option, + #[case] line: u32, +) -> TestResult { + let input = "====\n\nfirst\n\n:later: value\n\nlast\n===="; + let mut state = ParserState::new_for_test(input); + if let Some(file) = &file { + state.source_ranges.push(SourceRange { + start_offset: "====\n\n".len(), + end_offset: input.len(), + file: Some(file.clone()), + file_chain: vec!["part.adoc".into()], + start_line: 41, + source_start_offset: 100, + column_shift: 0, + }); + } + let mut calls = 0; + let result = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + calls += 1; + if matches!(block, Block::Paragraph(_)) { + return Err(Error::Extension( + Box::new(state.create_error_source_location(block.location().clone())), + "deliberate compound child failure".into(), + )); + } + Ok(()) + }, + )?; + let Err(Error::Extension(location, _)) = result else { + return Err("expected a located child-handler failure".into()); + }; + assert_eq!(location.location.start.line, line); + assert_eq!(location.file, file); + assert_eq!(calls, 2); + assert_eq!(state.document_attributes.text("later"), None); + assert_eq!(state.block_context, BlockContext::Document); + Ok(()) +} + +#[test] +fn compound_driver_keeps_recovery_bounded_without_replaying_child_handlers() -> TestResult { + let input = "= Document\n\n== Parent\n\n[quote]\n____\n=== Child\n\nText.\n\n== Ancestor\n____"; + let mut state = ParserState::new_for_test(input); + let mut sections = Vec::new(); + let document = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, _| { + if let Block::Section(section) = block { + sections.push(section.level); + } + Ok(()) + }, + )??; + assert_eq!(sections, [1, 2]); + let [Block::Section(parent)] = document.blocks.as_slice() else { + return Err("expected the surviving parent section".into()); + }; + let [Block::DelimitedBlock(quote)] = parent.content.as_slice() else { + return Err("expected the recovered quote".into()); + }; + let DelimitedBlockType::DelimitedQuote(body) = "e.inner else { + return Err("expected quote content".into()); + }; + assert_eq!(body, &Vec::>::new()); + assert_eq!(document.toc_entries.len(), 1); + let warnings = std::mem::take(&mut *state.warnings.borrow_mut()).into_vec(); + assert_eq!(warnings.len(), 1); + let warning = warnings.first().ok_or("expected a recovery warning")?; + assert!(matches!(warning.kind, WarningKind::ContentRecovery { .. })); + assert_eq!( + warning + .location + .as_ref() + .map(|location| location.location.start.line), + Some(11) + ); + assert_eq!(state.block_context, BlockContext::Document); + Ok(()) +} + +#[rstest::rstest] +#[case::nested_basic(include_str!("../../../../fixtures/tests/table_nested_basic.adoc"))] +#[case::nested_multiple(include_str!("../../../../fixtures/tests/table_nested_multiple.adoc"))] +#[case::nested_content(include_str!("../../../../fixtures/tests/table_nested_with_content.adoc"))] +#[case::header_footer(include_str!("../../../../fixtures/tests/table_with_header_and_footer.adoc"))] +#[case::rowspan(include_str!("../../../../fixtures/tests/table_rowspan_with_cols.adoc"))] +#[case::combined_spans(include_str!("../../../../fixtures/tests/table_cell_span_combined.adoc"))] +#[case::colspan(include_str!("../../../../fixtures/tests/table_cell_colspan.adoc"))] +#[case::footnotes(include_str!("../../../../fixtures/tests/table_cell_footnotes.adoc"))] +#[case::footnote_scope(include_str!("../../../../fixtures/tests/table_cell_footnote_scope.adoc"))] +#[case::incomplete(include_str!("../../../../fixtures/tests/table_incomplete_row.adoc"))] +#[case::incomplete_single_line(include_str!("../../../../fixtures/tests/table_incomplete_row_single_line.adoc"))] +#[case::csv(include_str!("../../../../fixtures/tests/table_csv_no_header.adoc"))] +#[case::duplicated_styles("[cols=\"alh\",options=noheader]\n|===\n3*|Text footnote:[note].\n|===")] +#[case::dropped_ascii_doc( + "[cols=\"1a\",options=noheader]\n|===\n2+a|Text footnote:[discarded].\n\n== Dropped\n\n{missing}\n|Kept footnote:[kept].\n|===" +)] +#[case::unterminated("[cols=\"a\",options=noheader]\n|===\n|Text footnote:[note].")] +fn table_driver_preserves_existing_construction(#[case] input: &str) -> TestResult { + assert_equivalent(input) +} + +struct UnusedProcessor; + +impl crate::extensions::BlockMacroProcessor for UnusedProcessor { + fn process( + &mut self, + _: &crate::extensions::MacroInvocation<'_>, + ) -> Result { + Err("internal boundary tests do not execute public processors".into()) + } +} + +fn probe_options(mode: CompatibilityMode) -> Result, Box> { + let mut registry = crate::extensions::Registry::builder(); + registry.register(crate::extensions::BlockMacro::new("probe", || { + UnusedProcessor + }))?; + let mut options = Options::builder().with_compatibility_mode(mode).build()?; + options.extensions = Some(registry.build()); + Ok(options) +} + +#[test] +fn table_driver_commits_each_duplicate_with_isolated_attributes() -> TestResult { + let input = "[cols=\"3*a\",options=noheader]\n|===\n3*a|probe::copy[]\n\n{value}\n|===\n\nprobe::outside[]\n\n{value}"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new(input, &arena, Rc::new(probe_options(mode)?)); + let mut calls = Vec::new(); + let mut paragraphs = Vec::new(); + document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(( + extension.invocation.target.to_string(), + state.document_attributes.text("value").map(str::to_owned), + )); + let value = state.intern_str(&calls.len().to_string()); + Rc::make_mut(&mut state.document_attributes) + .set_text("value".into(), value.into()); + } + if let Block::Paragraph(paragraph) = block { + paragraphs.push( + paragraph + .content + .iter() + .filter_map(|node| { + if let InlineNode::PlainText(plain) = node { + Some(plain.content) + } else { + None + } + }) + .collect::(), + ); + } + Ok(()) + }, + )??; + assert_eq!( + calls, + [ + ("copy".into(), None), + ("copy".into(), None), + ("copy".into(), None), + ("outside".into(), None) + ] + ); + assert_eq!(paragraphs, ["1", "2", "3", "4"]); + assert_eq!(state.document_attributes.text("value"), Some("4")); + } + Ok(()) +} + +#[test] +fn table_driver_ignores_macros_in_plain_literal_header_and_rejected_cells() -> TestResult { + let input = "[cols=\"1a\",options=header]\n|===\n|probe::header[]\n\n2+a|probe::discarded[]\n|probe::accepted[]\n|===\n\n[cols=\"1l\",options=noheader]\n|===\n|probe::literal[]\n|===\n\n[cols=\"1\",options=noheader]\n|===\n|probe::plain[]\n|==="; + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new( + input, + &arena, + Rc::new(probe_options(CompatibilityMode::Asciidoctor)?), + ); + let mut calls = Vec::new(); + document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, _| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + } + Ok(()) + }, + )??; + assert_eq!(calls, ["accepted"]); + assert!( + state + .warnings + .borrow() + .iter() + .any(|warning| matches!(warning.kind, WarningKind::TableCellOverflow { .. })) + ); + Ok(()) +} + +#[test] +fn table_driver_restores_cell_scope_after_handler_failure() -> TestResult { + let input = "[cols=\"a\",options=noheader]\n|===\n|:cell-only: local\n\nprobe::fail[]\n\nprobe::later[]\n|===\n\nprobe::outside[]"; + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new( + input, + &arena, + Rc::new(probe_options(CompatibilityMode::Asciidoctor)?), + ); + let outer_tracker = Rc::clone(&state.footnote_tracker); + let mut calls = Vec::new(); + let result = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + assert_eq!(state.document_attributes.text("cell-only"), Some("local")); + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "stop".into(), + )); + } + Ok(()) + }, + )?; + assert!(result.is_err()); + assert_eq!(calls, ["fail"]); + assert_eq!(state.document_attributes.text("cell-only"), None); + assert!(Rc::ptr_eq(&state.footnote_tracker, &outer_tracker)); + assert_eq!(state.block_context, BlockContext::Document); + assert_eq!(state.toc_entries.len(), 0); + Ok(()) +} + +#[rstest::rstest] +#[case::checklist_contexts(include_str!("../../../../fixtures/tests/checklist_contexts.adoc"))] +#[case::compatibility_list_attachments(include_str!("../../../../fixtures/tests/compatibility_list_attachments.adoc"))] +#[case::compatibility_list_principal(include_str!("../../../../fixtures/tests/compatibility_list_principal.adoc"))] +#[case::compatibility_list_contexts(include_str!("../../../../fixtures/tests/compatibility_list_contexts.adoc"))] +#[case::list_dangling_continuation(include_str!("../../../../fixtures/tests/list_dangling_continuation.adoc"))] +#[case::list_continuation_comments(include_str!("../../../../fixtures/tests/list_continuation_comments.adoc"))] +#[case::list_continuation_list_boundaries(include_str!("../../../../fixtures/tests/list_continuation_list_boundaries.adoc"))] +#[case::list_continuation_dropped_metadata(include_str!("../../../../fixtures/tests/list_continuation_dropped_metadata.adoc"))] +#[case::list_nesting_after_attached_blocks(include_str!("../../../../fixtures/tests/list_nesting_after_attached_blocks.adoc"))] +#[case::list_marker_matching(include_str!("../../../../fixtures/tests/list_marker_matching.adoc"))] +#[case::ordered_list_numbered_siblings(include_str!("../../../../fixtures/tests/ordered_list_numbered_siblings.adoc"))] +#[case::list_continuation_comment_contexts(include_str!("../../../../fixtures/tests/list_continuation_comment_contexts.adoc"))] +#[case::list_anchor_ownership(include_str!("../../../../fixtures/tests/list_anchor_ownership.adoc"))] +#[case::list_ancestor_continuation(include_str!("../../../../fixtures/tests/list_ancestor_continuation.adoc"))] +#[case::list_to_section_transition(include_str!("../../../../fixtures/tests/list_to_section_transition.adoc"))] +#[case::list_separator_comment(include_str!("../../../../fixtures/tests/list_separator_comment.adoc"))] +#[case::list_multiline(include_str!("../../../../fixtures/tests/list_multiline.adoc"))] +#[case::list_followed_by_paragraph(include_str!("../../../../fixtures/tests/list_followed_by_paragraph.adoc"))] +#[case::ordered_list_with_explicit_continuation(include_str!("../../../../fixtures/tests/ordered_list_with_explicit_continuation.adoc"))] +#[case::ordered_list_with_checkmarks(include_str!("../../../../fixtures/tests/ordered_list_with_checkmarks.adoc"))] +#[case::ordered_list(include_str!("../../../../fixtures/tests/ordered_list.adoc"))] +#[case::nested_ordered_list_with_checkmarks(include_str!("../../../../fixtures/tests/nested_ordered_list_with_checkmarks.adoc"))] +#[case::nested_list_with_parent_continuation(include_str!("../../../../fixtures/tests/nested_list_with_parent_continuation.adoc"))] +#[case::nested_list_block_attributes(include_str!("../../../../fixtures/tests/nested_list_block_attributes.adoc"))] +#[case::nested_list_block_attribute_boundaries(include_str!("../../../../fixtures/tests/nested_list_block_attribute_boundaries.adoc"))] +#[case::unordered_list_with_explicit_continuation(include_str!("../../../../fixtures/tests/unordered_list_with_explicit_continuation.adoc"))] +#[case::unordered_list_continuation_comment_midchain(include_str!("../../../../fixtures/tests/unordered_list_continuation_comment_midchain.adoc"))] +#[case::unordered_list(include_str!("../../../../fixtures/tests/unordered_list.adoc"))] +#[case::unindented_cross_type_list_nesting(include_str!("../../../../fixtures/tests/unindented_cross_type_list_nesting.adoc"))] +#[case::titled_list_with_nested(include_str!("../../../../fixtures/tests/titled_list_with_nested.adoc"))] +#[case::rejected_callout_style("* Parent\n[listing]\n<1> Text")] +fn ordinary_list_driver_preserves_existing_construction(#[case] input: &str) -> TestResult { + assert_equivalent(input) +} + +#[test] +fn ordinary_list_driver_runs_attached_macros_before_later_principals() -> TestResult { + let input = "* First.\n+\nprobe::one[]\n* {value}\n** Nested.\n+\nprobe::two[]\n** {value}\n* {value}\n\n// Separate lists.\n\n. Ordered.\n+\nprobe::three[]\n. {value}"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new(input, &arena, Rc::new(probe_options(mode)?)); + let mut calls = Vec::new(); + let document = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + Rc::make_mut(&mut state.document_attributes) + .set_text("value".into(), extension.invocation.target.clone()); + } + Ok(()) + }, + )??; + assert_eq!(calls, ["one", "two", "three"]); + let Some(Block::UnorderedList(list)) = document.blocks.first() else { + return Err("missing list".into()); + }; + let Some(second) = list.items.get(1) else { + return Err("missing second item".into()); + }; + let Some(InlineNode::PlainText(text)) = second.principal.first() else { + return Err("missing principal".into()); + }; + assert_eq!(text.content, "one"); + let Some(Block::UnorderedList(nested)) = second.blocks.first() else { + return Err("missing nested list".into()); + }; + let Some(item) = nested.items.get(1) else { + return Err("missing nested second item".into()); + }; + let Some(InlineNode::PlainText(text)) = item.principal.first() else { + return Err("missing nested principal".into()); + }; + assert_eq!(text.content, "two"); + let Some(item) = list.items.last() else { + return Err("missing last item".into()); + }; + let Some(InlineNode::PlainText(text)) = item.principal.first() else { + return Err("missing last principal".into()); + }; + assert_eq!(text.content, "two"); + let Some(Block::OrderedList(list)) = document.blocks.last() else { + return Err("missing ordered list".into()); + }; + let Some(item) = list.items.last() else { + return Err("missing ordered second item".into()); + }; + let Some(InlineNode::PlainText(text)) = item.principal.first() else { + return Err("missing ordered principal".into()); + }; + assert_eq!(text.content, "three"); + } + Ok(()) +} + +#[test] +fn ordinary_list_driver_restores_scopes_when_an_attached_handler_fails() -> TestResult { + let input = "* Parent\n** Nested\n+\n====\nprobe::fail[]\n====\n** Later\n\nprobe::outside[]"; + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new( + input, + &arena, + Rc::new(probe_options(CompatibilityMode::Asciidoctor)?), + ); + let mut calls = Vec::new(); + let result = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "stop".into(), + )); + } + Ok(()) + }, + )?; + assert!(result.is_err()); + assert_eq!(calls, ["fail"]); + assert!(state.ordinary_list_scope.is_none()); + assert!(state.description_list_scope.is_none()); + assert!(state.callout_list_offset.is_none()); + assert_eq!(state.block_context, BlockContext::Document); + Ok(()) +} + +#[rstest::rstest] +#[case::callout_list_basic(include_str!("../../../../fixtures/tests/callout_list_basic.adoc"))] +#[case::callout_list_auto_numbering(include_str!("../../../../fixtures/tests/callout_list_auto_numbering.adoc"))] +#[case::callout_nested_lists(include_str!("../../../../fixtures/tests/callout_nested_lists.adoc"))] +#[case::callout_list_with_language(include_str!("../../../../fixtures/tests/callout_list_with_language.adoc"))] +#[case::callout_list_not_after_verbatim(include_str!("../../../../fixtures/tests/callout_list_not_after_verbatim.adoc"))] +#[case::callout_list_non_sequential(include_str!("../../../../fixtures/tests/callout_list_non_sequential.adoc"))] +#[case::callout_list_multiple_callouts_same_line(include_str!("../../../../fixtures/tests/callout_list_multiple_callouts_same_line.adoc"))] +#[case::callout_list_mixed_auto_explicit(include_str!("../../../../fixtures/tests/callout_list_mixed_auto_explicit.adoc"))] +#[case::callout_list_literal_block(include_str!("../../../../fixtures/tests/callout_list_literal_block.adoc"))] +#[case::callout_list_continuation(include_str!("../../../../fixtures/tests/callout_list_continuation.adoc"))] +#[case::footnote_order( + "----\ncode <1> <2>\n----\n<1> footnote:[first]\n+\nA footnote:[child].\n<2> footnote:[second]" +)] +fn callout_list_driver_preserves_existing_construction(#[case] input: &str) -> TestResult { + assert_equivalent(input) +} + +#[test] +fn callout_list_driver_commits_attached_macros_before_later_items() -> TestResult { + let input = + "----\ncode <1> <2>\n----\n<1> First.\n+\nprobe::one[]\n<2> {value}\n+\nprobe::two[]"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new(input, &arena, Rc::new(probe_options(mode)?)); + let mut calls = Vec::new(); + let document = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + Rc::make_mut(&mut state.document_attributes) + .set_text("value".into(), extension.invocation.target.clone()); + } + Ok(()) + }, + )??; + assert_eq!(calls, ["one", "two"]); + let Some(Block::CalloutList(list)) = document.blocks.last() else { + return Err("missing callout list".into()); + }; + let Some(item) = list.items.last() else { + return Err("missing callout item".into()); + }; + let Some(InlineNode::PlainText(text)) = item.principal.first() else { + return Err("missing callout principal".into()); + }; + assert_eq!(text.content, "one"); + assert_eq!(item.callout.number, 2); + assert_eq!(state.warnings.borrow().len(), 0); + assert!(state.callout_list_offset.is_none()); + } + Ok(()) +} + +#[test] +fn callout_list_driver_restores_scope_after_handler_failure() -> TestResult { + let input = + "----\ncode <1> <2>\n----\n<1> First.\n+\nprobe::fail[]\n<2> Later.\n+\nprobe::later[]"; + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new( + input, + &arena, + Rc::new(probe_options(CompatibilityMode::Asciidoctor)?), + ); + let mut calls = Vec::new(); + let result = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + assert!(state.callout_list_offset.is_some()); + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "stop".into(), + )); + } + Ok(()) + }, + )?; + assert!(result.is_err()); + assert_eq!(calls, ["fail"]); + assert!(state.callout_list_offset.is_none()); + assert_eq!(state.pending_callouts, Vec::::new()); + assert!(state.ordinary_list_scope.is_none()); + Ok(()) +} + +#[rstest::rstest] +#[case::description_list_anchor_boundary(include_str!("../../../../fixtures/tests/description_list_anchor_boundary.adoc"))] +#[case::description_list_basic(include_str!("../../../../fixtures/tests/description_list_basic.adoc"))] +#[case::description_list_block_attributes_boundary(include_str!("../../../../fixtures/tests/description_list_block_attributes_boundary.adoc"))] +#[case::description_list_boundaries(include_str!("../../../../fixtures/tests/description_list_boundaries.adoc"))] +#[case::description_list_complex_terms(include_str!("../../../../fixtures/tests/description_list_complex_terms.adoc"))] +#[case::description_list_continuations(include_str!("../../../../fixtures/tests/description_list_continuations.adoc"))] +#[case::description_list_delimiter_transitions(include_str!("../../../../fixtures/tests/description_list_delimiter_transitions.adoc"))] +#[case::description_list_different_delimiters(include_str!("../../../../fixtures/tests/description_list_different_delimiters.adoc"))] +#[case::description_list_effective_styles(include_str!("../../../../fixtures/tests/description_list_effective_styles.adoc"))] +#[case::description_list_empty_description(include_str!("../../../../fixtures/tests/description_list_empty_description.adoc"))] +#[case::description_list_explicit_continuation(include_str!("../../../../fixtures/tests/description_list_explicit_continuation.adoc"))] +#[case::description_list_followed_by_table_with_attributes(include_str!("../../../../fixtures/tests/description_list_followed_by_table_with_attributes.adoc"))] +#[case::description_list_hash_term_in_section(include_str!("../../../../fixtures/tests/description_list_hash_term_in_section.adoc"))] +#[case::description_list_implicit_continuation(include_str!("../../../../fixtures/tests/description_list_implicit_continuation.adoc"))] +#[case::description_list_in_sidebar_section(include_str!("../../../../fixtures/tests/description_list_in_sidebar_section.adoc"))] +#[case::description_list_mixed_content(include_str!("../../../../fixtures/tests/description_list_mixed_content.adoc"))] +#[case::description_list_multiline_formatting_locations(include_str!("../../../../fixtures/tests/description_list_multiline_formatting_locations.adoc"))] +#[case::description_list_multiple_blank_lines(include_str!("../../../../fixtures/tests/description_list_multiple_blank_lines.adoc"))] +#[case::description_list_nested_lists(include_str!("../../../../fixtures/tests/description_list_nested_lists.adoc"))] +#[case::description_list_no_blank_line(include_str!("../../../../fixtures/tests/description_list_no_blank_line.adoc"))] +#[case::description_list_no_inline_with_lists(include_str!("../../../../fixtures/tests/description_list_no_inline_with_lists.adoc"))] +#[case::description_list_principal_source_locations(include_str!("../../../../fixtures/tests/description_list_principal_source_locations.adoc"))] +#[case::description_list_separated_paragraphs(include_str!("../../../../fixtures/tests/description_list_separated_paragraphs.adoc"))] +#[case::description_list_term_inlines(include_str!("../../../../fixtures/tests/description_list_term_inlines.adoc"))] +#[case::description_list_with_admonition(include_str!("../../../../fixtures/tests/description_list_with_admonition.adoc"))] +#[case::description_list_with_auto_attached_list(include_str!("../../../../fixtures/tests/description_list_with_auto_attached_list.adoc"))] +#[case::description_list_with_continuation(include_str!("../../../../fixtures/tests/description_list_with_continuation.adoc"))] +#[case::description_list_with_ordered_list(include_str!("../../../../fixtures/tests/description_list_with_ordered_list.adoc"))] +#[case::description_list_with_surrounding_blocks(include_str!("../../../../fixtures/tests/description_list_with_surrounding_blocks.adoc"))] +#[case::nested_description_lists(include_str!("../../../../fixtures/tests/nested_description_lists.adoc"))] +#[case::dlist_continuation_trailing_comment(include_str!("../../../../fixtures/tests/dlist_continuation_trailing_comment.adoc"))] +#[case::dlist_continuation_trailing_block_comment(include_str!("../../../../fixtures/tests/dlist_continuation_trailing_block_comment.adoc"))] +#[case::dlist_continuation_comment_at_eof(include_str!("../../../../fixtures/tests/dlist_continuation_comment_at_eof.adoc"))] +fn description_list_driver_preserves_existing_construction(#[case] input: &str) -> TestResult { + assert_equivalent(input) +} + +#[test] +fn description_list_driver_runs_attachments_before_later_principals() -> TestResult { + let input = "Term:: First.\n+\nprobe::one[]\nNext:: {value}\n+\nprobe::two[]"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new(input, &arena, Rc::new(probe_options(mode)?)); + let mut calls = Vec::new(); + let document = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + Rc::make_mut(&mut state.document_attributes) + .set_text("value".into(), extension.invocation.target.clone()); + } + Ok(()) + }, + )??; + assert_eq!(calls, ["one", "two"]); + let Some(Block::DescriptionList(list)) = document.blocks.last() else { + return Err("missing description list".into()); + }; + let Some(definition) = list.items.last().and_then(|item| item.definition.as_ref()) else { + return Err("missing definition".into()); + }; + let Some(InlineNode::PlainText(text)) = definition + .principal + .as_ref() + .and_then(|principal| principal.first()) + else { + return Err("missing principal".into()); + }; + assert_eq!(text.content, "one"); + assert!(state.description_list_scope.is_none()); + } + Ok(()) +} + +#[rstest::rstest] +#[case::explicit("Term:: First.\n+\nprobe::fail[]\nNext:: Later.\n+\nprobe::later[]")] +#[case::ordinary_child( + "Term:: First.\n* Child.\n+\nprobe::fail[]\nNext:: Later.\n+\nprobe::later[]" +)] +#[case::table_cell( + "Term:: First.\n+\n[cols=\"a\",options=noheader]\n|===\n|probe::fail[]\n|===\nNext:: Later.\n+\nprobe::later[]" +)] +fn description_list_driver_does_not_recover_handler_failure(#[case] input: &str) -> TestResult { + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new( + input, + &arena, + Rc::new(probe_options(CompatibilityMode::Asciidoctor)?), + ); + let mut calls = Vec::new(); + let result = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "stop".into(), + )); + } + Ok(()) + }, + )?; + assert!(result.is_err()); + assert_eq!(calls, ["fail"]); + assert!(state.description_list_scope.is_none()); + assert!(state.ordinary_list_scope.is_none()); + assert!(state.warnings.borrow().is_empty()); + Ok(()) +} + +#[rstest::rstest] +#[case::explicit("Term:: First.\n+\nprobe::[]\n+\nprobe::kept[]\nNext:: Last.")] +#[case::ordinary_child("Term:: First.\n* Child.\n+\nprobe::[]\n+\nprobe::kept[]\nNext:: Last.")] +fn description_list_driver_preserves_native_macro_recovery(#[case] input: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let mut registry = crate::extensions::Registry::builder(); + registry.register( + crate::extensions::BlockMacro::new("probe", || UnusedProcessor) + .with_target(crate::extensions::MacroTarget::Required), + )?; + let mut options = Options::builder().with_compatibility_mode(mode).build()?; + options.extensions = Some(registry.build()); + let options = Rc::new(options); + let expected_arena = bumpalo::Bump::new(); + let ordered_arena = bumpalo::Bump::new(); + let mut expected_state = ParserState::new(input, &expected_arena, Rc::clone(&options)); + let mut ordered_state = ParserState::new(input, &ordered_arena, options); + let expected = document_with( + input, + &mut expected_state, + ConstructionMode::Recursive, + &mut |_, _| Ok(()), + )??; + let mut calls = Vec::new(); + let ordered = document_with( + input, + &mut ordered_state, + ConstructionMode::Ordered, + &mut |block, _| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + } + Ok(()) + }, + )??; + assert_eq!(calls, ["kept"]); + assert_eq!(ordered, expected); + assert_eq!( + &**ordered_state.warnings.borrow(), + &**expected_state.warnings.borrow() + ); + } + Ok(()) +} + +#[rstest::rstest] +#[case::quoted_paragraph(include_str!("../../../../fixtures/tests/quoted_paragraph.adoc"))] +#[case::markdown_blockquote(include_str!("../../../../fixtures/tests/markdown_blockquote.adoc"))] +#[case::quote_with_url_attribution(include_str!("../../../../fixtures/tests/quote_with_url_attribution.adoc"))] +#[case::quote_with_attribution(include_str!("../../../../fixtures/tests/quote_with_attribution.adoc"))] +#[case::quote_block_with_url_citation(include_str!("../../../../fixtures/tests/quote_block_with_url_citation.adoc"))] +#[case::quote_block_with_paragraphs(include_str!("../../../../fixtures/tests/quote_block_with_paragraphs.adoc"))] +#[case::compatibility_quote_locations(include_str!("../../../../fixtures/tests/compatibility_quote_locations.adoc"))] +#[case::compatibility_quote_content(include_str!("../../../../fixtures/tests/compatibility_quote_content.adoc"))] +#[case::compatibility_quote_snapshots(include_str!("../../../../fixtures/tests/compatibility_quote_snapshots.adoc"))] +#[case::unsupported_counters( + "\"Body {counter:sequence}.\"\n-- Author {counter:sequence}, Citation {counter:sequence}" +)] +#[case::empty_markdown(">\n>\n> -- Author")] +fn abbreviated_quote_driver_preserves_existing_construction(#[case] input: &str) -> TestResult { + assert_equivalent(input) +} + +#[rstest::rstest] +#[case::shorthand("\"probe::inside[]\n\n{value}\"\n-- Author\n\nprobe::outside[]")] +#[case::markdown("> probe::inside[]\n>\n> {value}\n\nprobe::outside[]")] +fn abbreviated_quote_driver_commits_children_in_source_order(#[case] input: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new(input, &arena, Rc::new(probe_options(mode)?)); + let mut calls = Vec::new(); + let mut paragraphs = Vec::new(); + document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + Rc::make_mut(&mut state.document_attributes) + .set_text("value".into(), extension.invocation.target.clone()); + } + if let Block::Paragraph(paragraph) = block { + paragraphs.push( + paragraph + .content + .iter() + .filter_map(|node| { + if let InlineNode::PlainText(text) = node { + Some(text.content) + } else { + None + } + }) + .collect::(), + ); + } + Ok(()) + }, + )??; + assert_eq!(calls, ["inside", "outside"]); + assert_eq!(paragraphs, ["inside"]); + assert_eq!(state.block_context, BlockContext::Document); + } + Ok(()) +} + +#[rstest::rstest] +#[case::shorthand("\"probe::fail[]\n\nprobe::later[]\"\n-- Author\n\nprobe::outside[]")] +#[case::markdown("> probe::fail[]\n>\n> probe::later[]\n\nprobe::outside[]")] +fn abbreviated_quote_driver_stops_after_handler_failure(#[case] input: &str) -> TestResult { + let arena = bumpalo::Bump::new(); + let mut state = ParserState::new( + input, + &arena, + Rc::new(probe_options(CompatibilityMode::Asciidoctor)?), + ); + let mut calls = Vec::new(); + let result = document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + if let Block::Extension(extension) = block { + calls.push(extension.invocation.target.to_string()); + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "stop".into(), + )); + } + Ok(()) + }, + )?; + assert!(result.is_err()); + assert_eq!(calls, ["fail"]); + assert_eq!(state.block_context, BlockContext::Document); + Ok(()) +} + +#[rstest::rstest] +fn abbreviated_quote_driver_preserves_attribution_footnote_order( + #[values(CompatibilityMode::Asciidoctor, CompatibilityMode::Draft)] mode: CompatibilityMode, +) -> TestResult { + let input = + "\"Body footnote:[body].\"\n-- Author footnote:[author], Citation footnote:[citation]"; + let arena = bumpalo::Bump::new(); + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut state = ParserState::new(input, &arena, Rc::new(options)); + let document = document_with(input, &mut state, ConstructionMode::Ordered, &mut |_, _| { + Ok(()) + })??; + let Some(Block::DelimitedBlock(block)) = document.blocks.first() else { + return Err("missing quote".into()); + }; + let numbers = |nodes: &[InlineNode<'_>]| { + nodes + .iter() + .filter_map(|node| { + if let InlineNode::Macro(crate::InlineMacro::Footnote(note)) = node { + Some(note.number) + } else { + None + } + }) + .collect::>() + }; + assert_eq!( + block + .metadata + .attribution + .as_ref() + .map(|content| numbers(content.as_inlines())), + Some(vec![1]) + ); + assert_eq!( + block + .metadata + .citetitle + .as_ref() + .map(|content| numbers(content.as_inlines())), + Some(vec![2]) + ); + let DelimitedBlockType::DelimitedQuote(children) = &block.inner else { + return Err("missing quote children".into()); + }; + let Some(Block::Paragraph(paragraph)) = children.first() else { + return Err("missing quote paragraph".into()); + }; + assert_eq!(numbers(¶graph.content), [3]); + Ok(()) +} diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index c7ed5d67d..2929ac0cc 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -3,11 +3,47 @@ use crate::{ Block, Document, DocumentAttributes, Error, grammar::{ParserState, helpers::PositionWithOffset}, + model::{SectionKind, SectionLevel}, }; -use super::{document_parser, finish, header::ParsedHeader, metadata::order_block_prefix_events}; +use super::{ + RecognitionError, + construction::{ConstructionMode, DelimitedConstruction, QuoteConstruction}, + delimited::{ContentParser, ContentRequest, parse_content}, + doctype::is_book_doctype, + document_parser, finish, + header::ParsedHeader, + lists::ListEntry, + metadata::{assign_block_caption, order_block_prefix_events}, + sections::expected_child_level, + table::{InitialAttributes, construction::TableConstruction}, +}; + +/// A handler failure always escapes native content recovery. Effects that +/// completed before failure are never retried or rolled back. +pub(super) struct Execution<'handler, F> { + callback: &'handler mut F, + failed: bool, +} + +impl Execution<'_, F> { + pub(super) fn run<'a>( + &mut self, + block: &Block<'a>, + state: &mut ParserState<'a>, + ) -> Result<(), Error> + where + F: FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + { + let result = (self.callback)(block, state); + self.failed |= result.is_err(); + result + } -type RecognitionError = peg::error::ParseError; + pub(super) fn failed(&self) -> bool { + self.failed + } +} pub(super) struct DocumentPrefix<'a> { pub(super) start: PositionWithOffset, @@ -17,40 +53,68 @@ pub(super) struct DocumentPrefix<'a> { pub(super) body_offset: usize, } +pub(super) struct NestedPrefix<'a> { + pub(super) blocks: Vec>, + pub(super) body_offset: usize, +} + pub(super) struct BlockStep<'a> { - pub(super) block: Option>, - pub(super) trailing: Vec>, + pub(super) kind: BlockStepKind<'a>, pub(super) end: usize, - pub(super) complete: bool, +} + +pub(super) enum BlockStepKind<'a> { + Block(Block<'a>), + Delimited(DelimitedConstruction<'a>), + Table(TableConstruction<'a>), + Quote(QuoteConstruction<'a>), + List(ListEntry<'a>), + End(Vec>), } impl<'a> BlockStep<'a> { - pub(super) fn block(block: Block<'a>, end: usize) -> Self { + pub(super) fn end(trailing: Vec>, end: usize) -> Self { Self { - block: Some(block), - trailing: Vec::new(), + kind: BlockStepKind::End(trailing), end, - complete: false, } } +} - pub(super) fn end(trailing: Vec>, end: usize) -> Self { - Self { - block: None, - trailing, - end, - complete: true, +impl<'a> BlockStepKind<'a> { + pub(super) fn into_ready(self, state: &ParserState<'a>) -> Result, Error> { + if let Self::Block(block) = self { + Ok(block) + } else { + Err(Error::Parse( + Box::new(state.create_error_source_location(state.create_location(0, 0))), + "recursive block dispatch returned unfinished content".into(), + )) } } } +#[derive(Clone, Copy, Default)] +pub(super) struct BlockParent { + pub(super) level: Option, + pub(super) kind: Option, +} + pub(super) struct BlockCursor { - offset: usize, + pub(super) offset: usize, + pub(super) base_offset: usize, + parent: BlockParent, + mode: ConstructionMode, } impl BlockCursor { - pub(super) fn new(offset: usize) -> Self { - Self { offset } + pub(super) fn new(offset: usize, mode: ConstructionMode) -> Self { + Self { + offset, + base_offset: 0, + parent: BlockParent::default(), + mode, + } } pub(super) fn advance<'a>( @@ -58,36 +122,290 @@ impl BlockCursor { input: &'a str, state: &mut ParserState<'a>, ) -> Result, Error>, RecognitionError> { - let step = document_parser::next_block(input, state, self.offset)?; + let step = document_parser::next_block( + input, + state, + self.offset, + self.base_offset, + self.parent, + self.mode, + )?; if let Ok(step) = &step { self.offset = step.end; } Ok(step) } + + pub(super) fn section(&self, section: &crate::Section<'_>, state: &ParserState<'_>) -> Self { + Self { + offset: self.offset, + base_offset: self.base_offset, + parent: BlockParent { + level: Some(expected_child_level( + section.level, + section.kind, + is_book_doctype(&state.document_attributes), + )), + kind: Some(section.kind), + }, + mode: self.mode, + } + } + + /// Ordered construction enters each section after its heading recognition + /// has returned. The recursive mode retains the ordinary parsing fast path. + fn collect<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + blocks: &mut Vec>, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result, RecognitionError> { + loop { + let step = match self.advance(input, state)? { + Ok(step) => step, + Err(error) => return Ok(Err(error)), + }; + let kind = match step.kind { + BlockStepKind::End(trailing) => { + blocks.extend(trailing); + *blocks = order_block_prefix_events(std::mem::take(blocks)); + return Ok(Ok(step.end)); + } + kind @ (BlockStepKind::Block(_) + | BlockStepKind::Delimited(_) + | BlockStepKind::Table(_) + | BlockStepKind::List(_) + | BlockStepKind::Quote(_)) => kind, + }; + match self.construct(input, state, kind, accepted)? { + Ok(block) => blocks.push(block), + Err(error) => return Ok(Err(error)), + } + } + } + + pub(super) fn construct<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + kind: BlockStepKind<'a>, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result, Error>, RecognitionError> { + let needs_caption = matches!( + &kind, + BlockStepKind::Delimited(_) | BlockStepKind::Table(_) | BlockStepKind::Quote(_) + ); + let mut table_content = None; + let (mut block, request) = match kind { + BlockStepKind::List(entry) => { + return self.construct_list( + input, + state, + &entry, + &crate::grammar::helpers::BlockParsingMetadata::new( + state.options.compatibility_mode, + ), + accepted, + ); + } + BlockStepKind::Block(block) => (block, None), + BlockStepKind::Delimited(construction) => match construction.start(state) { + Ok(started) => started, + Err(error) => return Ok(Err(error)), + }, + BlockStepKind::Quote(construction) => match construction.start(state) { + Ok(started) => started, + Err(error) => return Ok(Err(error)), + }, + BlockStepKind::Table(construction) => match construction.start(state) { + Ok((block, content)) => { + table_content = Some(content); + (block, None) + } + Err(error) => return Ok(Err(error)), + }, + BlockStepKind::End(_) => { + return Ok(Err(Error::Parse( + Box::new(state.create_error_source_location(state.create_location( + self.base_offset + self.offset, + self.base_offset + self.offset, + ))), + "block construction received an end boundary".into(), + ))); + } + }; + let child = if let Block::Section(section) = &block + && self.mode == ConstructionMode::Ordered + { + Some(self.section(section, state)) + } else { + None + }; + if let Err(error) = accepted.run(&block, state) { + return Ok(Err(error)); + } + if let (Block::Section(section), Some(mut child)) = (&mut block, child) { + let end = match child.collect(input, state, &mut section.content, accepted)? { + Ok(end) => end, + Err(error) => return Ok(Err(error)), + }; + self.offset = end; + section.location = state.create_block_location( + section.location.absolute_start, + self.base_offset + end, + 0, + ); + } + if let Some(request) = request { + let mut parser = CursorContent { accepted }; + let content = match parse_content(state, request, &mut parser) { + Ok(content) => content, + Err(error) => return Ok(Err(error)), + }; + let Some(body) = crate::extensions::compound_body_mut(&mut block) else { + return Ok(Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "compound builder returned no child content slot".into(), + ))); + }; + *body = content; + } + if needs_caption { + if let Some(content) = table_content + && let Err(error) = + content.finish(&mut block, state, &mut CursorContent { accepted }) + { + return Ok(Err(error)); + } + assign_block_caption(state, &mut block); + } + Ok(Ok(block)) + } +} + +struct CursorContent<'h, 'callback, F> { + accepted: &'h mut Execution<'callback, F>, +} + +impl<'a, F> ContentParser<'a> for CursorContent<'_, '_, F> +where + F: FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, +{ + fn parse( + &mut self, + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + ) -> Result>, Error> { + let mut cursor = BlockCursor { + offset: 0, + base_offset: request.offset, + parent: BlockParent { + level: request.parent_section_level, + kind: None, + }, + mode: ConstructionMode::Ordered, + }; + let mut blocks = Vec::new(); + let toc_start = state.toc_entries.len(); + let result = cursor + .collect(request.source, state, &mut blocks, self.accepted) + .and_then(|result| match result { + Ok(end) => document_parser::block_sequence_end(request.source, state, end) + .map(|()| Ok(blocks)), + Err(error) => Ok(Err(error)), + }); + match result { + Ok(result) => result, + Err(error) => { + // Recovery discards this child tree. Retain no provisional TOC + // entries for headings that cannot survive in the document. + state.toc_entries.truncate(toc_start); + crate::grammar::inline_processing::adjust_and_log_parse_error( + &error, + request.source, + request.offset, + state, + request.error_context, + ); + Ok(Vec::new()) + } + } + } + + fn nested_document( + &mut self, + state: &mut ParserState<'a>, + source: &'a str, + offset: usize, + initial_attributes: &mut InitialAttributes<'a>, + ) -> Result>, Error>, RecognitionError> { + let prefix = match document_parser::nested_document_prefix( + source, + state, + offset, + initial_attributes, + )? { + Ok(prefix) => prefix, + Err(error) => return Ok(Err(error)), + }; + let mut cursor = BlockCursor { + offset: prefix.body_offset, + base_offset: offset, + parent: BlockParent::default(), + mode: ConstructionMode::Ordered, + }; + let mut blocks = prefix.blocks; + let end = match cursor.collect(source, state, &mut blocks, self.accepted)? { + Ok(end) => end, + Err(error) => return Ok(Err(error)), + }; + document_parser::block_sequence_end(source, state, end)?; + Ok(Ok(blocks)) + } } pub(crate) fn document<'a>( input: &'a str, state: &mut ParserState<'a>, +) -> Result, Error>, RecognitionError> { + // Registry callbacks still run after parsing. A registry alone must not + // change construction or diagnostic order before source handlers are wired. + document_with( + input, + state, + ConstructionMode::Recursive, + &mut |_, _| Ok(()), + ) +} + +/// Internal accepted-block execution boundary for documents and containers. +/// Source reading still advances independently of these commits. +pub(super) fn document_with<'a>( + input: &'a str, + state: &mut ParserState<'a>, + mode: ConstructionMode, + accepted: &mut impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, ) -> Result, Error>, RecognitionError> { let prefix = match document_parser::document_prefix(input, state)? { Ok(prefix) => prefix, Err(error) => return Ok(Err(error)), }; - let mut cursor = BlockCursor::new(prefix.body_offset); + let mut cursor = BlockCursor::new(prefix.body_offset, mode); let mut blocks = prefix.comments; - let end = loop { - let step = match cursor.advance(input, state)? { - Ok(step) => step, - Err(error) => return Ok(Err(error)), - }; - if let Some(block) = step.block { - blocks.push(block); - } - if step.complete { - blocks.extend(step.trailing); - break step.end; - } + let mut execution = Execution { + callback: accepted, + failed: false, + }; + let end = match cursor.collect(input, state, &mut blocks, &mut execution)? { + Ok(end) => end, + Err(error) => return Ok(Err(error)), }; Ok(finish::finish( state, @@ -95,6 +413,6 @@ pub(crate) fn document<'a>( end, prefix.header, prefix.attributes, - order_block_prefix_events(blocks), + blocks, )) } diff --git a/acdc-parser/src/grammar/document/delimited.rs b/acdc-parser/src/grammar/document/delimited.rs index cf5e66a6d..ae8b781e9 100644 --- a/acdc-parser/src/grammar/document/delimited.rs +++ b/acdc-parser/src/grammar/document/delimited.rs @@ -12,8 +12,93 @@ use crate::{ inline_processing::{adjust_and_log_parse_error, process_inlines}, state::BlockContext, }, + model::SectionLevel, }; +use super::{RecognitionError, table::InitialAttributes}; + +#[derive(Clone, Copy)] +pub(super) enum ContentKind { + Compound, + Blocks, +} + +/// A child parse requested by a committed block's existing builder. +#[derive(Clone, Copy)] +pub(super) struct ContentRequest<'a> { + pub(super) source: &'a str, + pub(super) offset: usize, + pub(super) parent_section_level: Option, + pub(super) context: BlockContext, + pub(super) kind: ContentKind, + pub(super) error_context: &'static str, +} + +pub(super) trait ContentParser<'a> { + fn parse( + &mut self, + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + ) -> Result>, Error>; + + fn nested_document( + &mut self, + state: &mut ParserState<'a>, + source: &'a str, + offset: usize, + initial_attributes: &mut InitialAttributes<'a>, + ) -> Result>, Error>, RecognitionError> { + document_parser::nested_document_blocks(source, state, offset, initial_attributes) + } +} + +pub(super) struct GrammarContent; + +impl<'a> ContentParser<'a> for GrammarContent { + fn parse( + &mut self, + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + ) -> Result>, Error> { + let result = match request.kind { + ContentKind::Compound => document_parser::compound_blocks( + request.source, + state, + request.offset, + request.parent_section_level, + ), + ContentKind::Blocks => document_parser::blocks( + request.source, + state, + request.offset, + request.parent_section_level, + None, + ), + }; + result.unwrap_or_else(|error| { + adjust_and_log_parse_error( + &error, + request.source, + request.offset, + state, + request.error_context, + ); + Ok(Vec::new()) + }) + } +} + +pub(super) fn parse_content<'a>( + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + parser: &mut impl ContentParser<'a>, +) -> Result>, Error> { + let outer_context = std::mem::replace(&mut state.block_context, request.context); + let result = parser.parse(state, request); + state.block_context = outer_context; + result +} + /// Return an error if the closing delimiter does not match the opening delimiter. pub(super) fn check_delimiters( open: &str, @@ -120,23 +205,24 @@ fn parse_block_content<'input>( content: &'input str, content_start: usize, offset: usize, - error_context: &str, + error_context: &'static str, + parser: &mut impl ContentParser<'input>, ) -> Result>, Error> { if content.trim().is_empty() { Ok(Vec::new()) } else { - let outer_context = std::mem::replace(&mut state.block_context, BlockContext::Compound); - let result = document_parser::compound_blocks( - content, + parse_content( state, - content_start + offset, - block_metadata.parent_section_level, - ); - state.block_context = outer_context; - result.unwrap_or_else(|e| { - adjust_and_log_parse_error(&e, content, content_start + offset, state, error_context); - Ok(Vec::new()) - }) + ContentRequest { + source: content, + offset: content_start + offset, + parent_section_level: block_metadata.parent_section_level, + context: BlockContext::Compound, + kind: ContentKind::Compound, + error_context, + }, + parser, + ) } } @@ -159,12 +245,27 @@ pub(super) struct DelimitedParams<'input> { pub(super) close: Option<(usize, &'input str)>, } +struct DelimitedLocations { + block: Location, + open: Location, + close: Option, +} + /// Build a block from its matched delimiters and content. /// If the closing delimiter is missing, keep the block and warn, as in asciidoctor. pub(super) fn build_delimited_block<'input>( state: &mut ParserState<'input>, block_metadata: &BlockParsingMetadata<'input>, p: &DelimitedParams<'input>, +) -> Result, Error> { + build_delimited_block_with_parser(state, block_metadata, p, &mut GrammarContent) +} + +pub(super) fn build_delimited_block_with_parser<'input>( + state: &mut ParserState<'input>, + block_metadata: &BlockParsingMetadata<'input>, + p: &DelimitedParams<'input>, + parser: &mut impl ContentParser<'input>, ) -> Result, Error> { let close_delimiter_location = resolve_delimited_close(state, p)?; let resolved = DelimitedParams { @@ -172,35 +273,30 @@ pub(super) fn build_delimited_block<'input>( ..*p }; let p = &resolved; - let location = state.create_block_location(p.start, p.end, p.offset); - let open_delimiter_location = state.create_location( - p.open_start + p.offset, - p.open_start + p.offset + p.open_delim.len().saturating_sub(1), - ); + let locations = DelimitedLocations { + block: state.create_block_location(p.start, p.end, p.offset), + open: state.create_location( + p.open_start + p.offset, + p.open_start + p.offset + p.open_delim.len().saturating_sub(1), + ), + close: close_delimiter_location, + }; let mut metadata = block_metadata.metadata.clone(); let inner = match p.kind { // An example block can become an admonition (a different `Block` variant), // so it constructs and returns the whole block itself. DelimitedKind::Example => { - return build_example_block( - state, - block_metadata, - metadata, - p, - location, - open_delimiter_location, - close_delimiter_location, - ); + return build_example_block(state, block_metadata, metadata, p, locations, parser); } DelimitedKind::Comment => comment_inner(state, &mut metadata, p), DelimitedKind::Listing | DelimitedKind::Literal => { verbatim_inner(state, block_metadata, &mut metadata, p)? } - DelimitedKind::Open => open_inner(state, block_metadata, &mut metadata, p)?, - DelimitedKind::Sidebar => sidebar_inner(state, block_metadata, &mut metadata, p)?, + DelimitedKind::Open => open_inner(state, block_metadata, &mut metadata, p, parser)?, + DelimitedKind::Sidebar => sidebar_inner(state, block_metadata, &mut metadata, p, parser)?, DelimitedKind::Passthrough => pass_inner(state, &mut metadata, p), - DelimitedKind::Quote => quote_inner(state, block_metadata, &mut metadata, p)?, + DelimitedKind::Quote => quote_inner(state, block_metadata, &mut metadata, p, parser)?, }; Ok(assemble_delimited( @@ -208,9 +304,7 @@ pub(super) fn build_delimited_block<'input>( p, inner, block_metadata.title.clone(), - location, - open_delimiter_location, - close_delimiter_location, + locations, )) } @@ -220,18 +314,16 @@ fn assemble_delimited<'input>( p: &DelimitedParams<'input>, inner: DelimitedBlockType<'input>, title: Title<'input>, - location: Location, - open_delimiter_location: Location, - close_delimiter_location: Option, + locations: DelimitedLocations, ) -> Block<'input> { Block::DelimitedBlock(DelimitedBlock { metadata, delimiter: p.open_delim, inner, title, - location, - open_delimiter_location: Some(open_delimiter_location), - close_delimiter_location, + location: locations.block, + open_delimiter_location: Some(locations.open), + close_delimiter_location: locations.close, source_text: Some(p.source_text), }) } @@ -242,9 +334,8 @@ fn build_example_block<'input>( block_metadata: &BlockParsingMetadata<'input>, mut metadata: BlockMetadata<'input>, p: &DelimitedParams<'input>, - location: Location, - open_delimiter_location: Location, - close_delimiter_location: Option, + locations: DelimitedLocations, + parser: &mut impl ContentParser<'input>, ) -> Result, Error> { metadata.move_positional_attributes_to_attributes(); let blocks = parse_block_content( @@ -254,13 +345,14 @@ fn build_example_block<'input>( p.content_start, p.offset, "Error parsing example content as blocks in example block", + parser, )?; // An admonition style (NOTE/TIP/…) turns the example block into an admonition. if let Some(style) = block_metadata.metadata.style && let Ok(variant) = style.parse::() { metadata.style = None; - let mut admonition = Admonition::new(variant, blocks, location) + let mut admonition = Admonition::new(variant, blocks, locations.block) .with_form(AdmonitionForm::Delimited(p.open_delim)) .with_title(block_metadata.title.clone()); admonition.metadata = metadata; @@ -271,9 +363,7 @@ fn build_example_block<'input>( p, DelimitedBlockType::DelimitedExample(blocks), block_metadata.title.clone(), - location, - open_delimiter_location, - close_delimiter_location, + locations, )) } @@ -298,6 +388,7 @@ fn open_inner<'input>( block_metadata: &BlockParsingMetadata<'input>, metadata: &mut BlockMetadata<'input>, p: &DelimitedParams<'input>, + parser: &mut impl ContentParser<'input>, ) -> Result, Error> { metadata.move_positional_attributes_to_attributes(); if block_metadata.metadata.style == Some("comment") { @@ -319,6 +410,7 @@ fn open_inner<'input>( p.content_start, p.offset, "Error parsing content as blocks in open block", + parser, )?; Ok(DelimitedBlockType::DelimitedOpen(blocks)) } @@ -329,6 +421,7 @@ fn sidebar_inner<'input>( block_metadata: &BlockParsingMetadata<'input>, metadata: &mut BlockMetadata<'input>, p: &DelimitedParams<'input>, + parser: &mut impl ContentParser<'input>, ) -> Result, Error> { metadata.move_positional_attributes_to_attributes(); let blocks = parse_block_content( @@ -338,6 +431,7 @@ fn sidebar_inner<'input>( p.content_start, p.offset, "Error parsing sidebar content as blocks", + parser, )?; Ok(DelimitedBlockType::DelimitedSidebar(blocks)) } @@ -413,6 +507,7 @@ fn quote_inner<'input>( block_metadata: &BlockParsingMetadata<'input>, metadata: &mut BlockMetadata<'input>, p: &DelimitedParams<'input>, + parser: &mut impl ContentParser<'input>, ) -> Result, Error> { metadata.move_positional_attributes_to_attributes(); @@ -428,23 +523,15 @@ fn quote_inner<'input>( Ok(DelimitedBlockType::DelimitedVerse(inlines)) } else if metadata.style.is_some() { // A styled (non-verse) quote always parses its body, even when empty. - let blocks = document_parser::blocks( - p.content, - state, - p.content_start + p.offset, - block_metadata.parent_section_level, - None, - ) - .unwrap_or_else(|e| { - adjust_and_log_parse_error( - &e, - p.content, - p.content_start + p.offset, - state, - "Error parsing example content as blocks in quote block", - ); - Ok(Vec::new()) - })?; + let request = ContentRequest { + source: p.content, + offset: p.content_start + p.offset, + parent_section_level: block_metadata.parent_section_level, + context: state.block_context, + kind: ContentKind::Blocks, + error_context: "Error parsing example content as blocks in quote block", + }; + let blocks = parse_content(state, request, parser)?; Ok(DelimitedBlockType::DelimitedQuote(blocks)) } else { let blocks = parse_block_content( @@ -454,6 +541,7 @@ fn quote_inner<'input>( p.content_start, p.offset, "Error parsing content as blocks in quote block", + parser, )?; Ok(DelimitedBlockType::DelimitedQuote(blocks)) } diff --git a/acdc-parser/src/grammar/document/lists.rs b/acdc-parser/src/grammar/document/lists.rs index fd378a885..a75bfe252 100644 --- a/acdc-parser/src/grammar/document/lists.rs +++ b/acdc-parser/src/grammar/document/lists.rs @@ -1,11 +1,387 @@ //! List item locations and description-list nesting. +mod callout; +mod construction; +mod description; + use crate::{ - Block, BlockMetadata, DescriptionList, DescriptionListDefinition, DescriptionListItem, - Location, Title, grammar::ParserState, + Block, BlockMetadata, CalloutList, CalloutListItem, CalloutMarker, DescriptionList, + DescriptionListDefinition, DescriptionListItem, DescriptionListTerm, Error, InlineNode, + ListItem, ListItemCheckedStatus, Location, OrderedList, Title, UnorderedList, Warning, + WarningKind, + grammar::{ParserState, helpers::BlockParsingMetadata}, + model::ListLevel, }; use bumpalo::collections::String as BumpString; -use std::collections::VecDeque; +use std::{collections::VecDeque, ops::ControlFlow}; + +use super::metadata::order_block_prefix_events; + +#[derive(Clone, Copy)] +pub(super) enum ListKind<'a> { + Unordered(OrdinaryListKind<'a>), + Ordered(OrdinaryListKind<'a>), + Callout, + Description, +} + +#[derive(Clone, Copy)] +pub(super) struct OrdinaryListKind<'a> { + pub(super) parent_other: Option<&'a str>, + pub(super) parent_same: Option<&'a str>, + pub(super) allow_continuation: bool, + pub(super) has_own_metadata: bool, +} + +pub(super) struct ListEntry<'a> { + pub(super) start: usize, + pub(super) body_offset: usize, + pub(super) metadata: Option>, + pub(super) kind: ListKind<'a>, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum ListPhase { + AfterPrincipal, + Attachments, + Sibling, +} + +pub(super) type ListStepKind<'a> = + ControlFlow, Error>, Option>>; + +pub(super) struct ListStep<'a> { + pub(super) kind: ListStepKind<'a>, + pub(super) end: usize, +} + +pub(super) struct DescriptionStep<'a> { + pub(super) child: Option, Error>>, + pub(super) end: usize, + pub(super) continuing: bool, + pub(super) warn_on_error: bool, +} + +#[derive(Clone, Copy)] +pub(super) struct OrdinaryListLayout { + pub(super) start: usize, + pub(super) end: usize, + pub(super) offset: usize, + pub(super) ordered: bool, + pub(super) has_own_metadata: bool, +} + +pub(super) fn build_ordinary_list<'a>( + state: &ParserState<'a>, + metadata: &BlockParsingMetadata<'a>, + layout: OrdinaryListLayout, + items: Vec>, +) -> Block<'a> { + let marker = items.first().map_or("", |item| item.marker); + let title = if layout.has_own_metadata { + metadata.title.clone() + } else { + Title::default() + }; + let metadata = if layout.has_own_metadata { + metadata.metadata.clone() + } else { + BlockMetadata::default() + }; + let location = state.create_location(layout.start + layout.offset, layout.end + layout.offset); + if layout.ordered { + Block::OrderedList(OrderedList { + title, + metadata, + items, + marker, + location, + }) + } else { + Block::UnorderedList(UnorderedList { + title, + metadata, + items, + marker, + location, + }) + } +} + +pub(super) type CalloutScope = (Option, Vec); +pub(super) type CalloutItem<'a> = (CalloutListItem<'a>, String, usize); + +pub(super) fn build_callout_list<'a>( + state: &ParserState<'a>, + block_metadata: &BlockParsingMetadata<'a>, + location: Location, + content: Vec>, + callouts: &[CalloutMarker], +) -> Block<'a> { + let mut auto_number = 0; + let mut items: Vec = Vec::with_capacity(content.len()); + + for (expected_number, (mut item, marker, _end)) in (1..).zip(content) { + let actual_number = if marker == "<.>" { + auto_number += 1; + auto_number.to_string() + } else { + marker + .trim_start_matches('<') + .trim_end_matches('>') + .to_string() + }; + if actual_number != expected_number.to_string() { + state.add_generic_warning_at( + format!("callout list item index: expected {expected_number}, got {actual_number}"), + item.location.clone(), + ); + } + // List labels use their ordinal even when the source marker is + // invalid or mixes explicit and automatic numbering. + item.callout.number = expected_number; + + // Check if the EXPECTED callout exists in the verbatim block + // (This warns when sequence is broken and the expected number is missing) + let callout_exists = callouts.iter().any(|c| c.number == expected_number); + if !callout_exists { + state.add_generic_warning_at( + format!("no callout found for <{expected_number}>"), + item.location.clone(), + ); + } + items.push(item); + } + + Block::CalloutList(CalloutList { + title: block_metadata.title.clone(), + metadata: block_metadata.metadata.clone(), + items, + location, + }) +} + +pub(super) struct CalloutItemHead<'a> { + pub(super) principal: Result>, Error>, + pub(super) marker: &'a str, + pub(super) start: usize, + pub(super) end: usize, +} + +impl<'a> CalloutItemHead<'a> { + pub(super) fn finish( + self, + state: &ParserState<'a>, + blocks: Result>, Error>, + parsed_end: usize, + offset: usize, + ) -> Result, Error> { + let principal = self.principal?; + let blocks = blocks?; + let marker_start = self.start + offset; + let location = state.create_location(marker_start, marker_start + self.marker.len() - 1); + let callout = if self.marker == "<.>" { + CalloutMarker::auto(0, location) + } else { + CalloutMarker::explicit(0, location) + }; + let end = if blocks.is_empty() { + self.end + } else { + parsed_end.saturating_sub(1) + }; + Ok(( + CalloutListItem { + callout, + principal, + blocks: super::metadata::order_block_prefix_events(blocks), + location: state.create_location(self.start + offset, end + offset), + }, + self.marker.to_string(), + end, + )) + } +} + +pub(super) type DescriptionPrincipal<'a> = (Vec>, Vec>); + +pub(super) struct DescriptionTermSource<'a> { + pub(super) raw: &'a str, + pub(super) start: usize, + pub(super) end: usize, + pub(super) delimiter_start: usize, + pub(super) delimiter_end: usize, + pub(super) delimiter: &'a str, +} + +pub(super) struct DescriptionItemSource<'a> { + pub(super) term: DescriptionTermSource<'a>, + pub(super) principal_content: &'a str, + pub(super) principal_start: usize, +} + +pub(super) struct DescriptionItemHead<'a> { + pub(super) source: DescriptionItemSource<'a>, + pub(super) principal: Result, Error>, +} + +pub(super) fn warn_discarded_attachment(state: &ParserState<'_>, error: &Error) { + state.add_warning(Warning::new( + WarningKind::ContentRecovery { + message: format!("discarded attached content: {error}").into(), + }, + error.source_location().cloned(), + )); +} + +impl<'a> DescriptionItemHead<'a> { + pub(super) fn finish( + self, + state: &ParserState<'a>, + attached: Vec>, Error>>, + offset: usize, + ) -> Result, Error> { + let principal = self.principal?; + let mut blocks = Vec::with_capacity(attached.len()); + for content in attached { + match content { + Ok(content) => blocks.extend(content), + Err(error) => warn_discarded_attachment(state, &error), + } + } + Ok(self.source.build(state, principal, blocks, offset)) + } +} + +impl<'a> DescriptionItemSource<'a> { + pub(super) fn build( + self, + state: &ParserState<'a>, + principal: DescriptionPrincipal<'a>, + description: Vec>, + offset: usize, + ) -> DescriptionListItem<'a> { + let Self { + term: + DescriptionTermSource { + start: term_start, + delimiter_start: delim_start, + delimiter_end: delim_end, + delimiter, + .. + }, + principal_content, + principal_start, + } = self; + let (term, principal_text) = principal; + let principal_end = principal_start + principal_content.trim_end().len(); + let actual_end = description.last().map_or_else( + || { + state + .create_block_location(term_start, principal_end.max(delim_end), offset) + .absolute_end + - offset + }, + |block| block.location().absolute_end - offset, + ); + + let delimiter_location = state.create_block_location(delim_start, delim_end, offset); + let term = DescriptionListTerm { + anchors: Vec::new(), + content: term, + delimiter, + delimiter_location: Some(delimiter_location), + location: state.create_block_location(term_start, delim_end, offset), + }; + let principal = (!principal_content.trim().is_empty()).then_some(principal_text); + let blocks = order_block_prefix_events(description); + let definition = if principal.is_some() || !blocks.is_empty() { + let location = if principal.is_some() { + let start = principal_start + principal_content.len() + - principal_content.trim_start().len(); + state.create_location(start + offset, actual_end + offset) + } else { + let mut location = blocks + .first() + .map_or_else(Location::default, |block| block.location().clone()); + if let Some(last) = blocks.last() { + location.absolute_end = last.location().absolute_end; + location.end = last.location().end.clone(); + } + location + }; + Some(DescriptionListDefinition { + principal, + blocks, + location, + }) + } else { + None + }; + let mut location = state.create_location(term_start + offset, actual_end + offset); + if definition.is_none() { + location.absolute_end = term.location.absolute_end; + location.end = term.location.end.clone(); + } + DescriptionListItem { + terms: vec![term], + definition, + location, + } + } +} + +pub(super) fn build_description_list<'a>( + metadata: &BlockParsingMetadata<'a>, + location: Location, + items: Vec>, +) -> Block<'a> { + Block::DescriptionList(DescriptionList { + title: metadata.title.clone(), + metadata: metadata.metadata.clone(), + items: build_description_list_topology(items), + location, + }) +} + +/// An accepted principal, before its nested and attached blocks are built. +pub(super) struct ListItemHead<'a> { + pub(super) principal: Result>, Error>, + pub(super) marker: &'a str, + pub(super) checked: Option, + pub(super) start: usize, + pub(super) end: usize, +} + +impl<'a> ListItemHead<'a> { + pub(super) fn finish( + self, + state: &ParserState<'a>, + blocks: Vec>, + parsed_end: usize, + offset: usize, + ) -> Result<(ListItem<'a>, usize), Error> { + let level = + ListLevel::try_from(ListItem::parse_depth_from_marker(self.marker).unwrap_or(1))?; + let principal = self.principal?; + let end = if blocks.is_empty() { + self.end + } else { + parsed_end.saturating_sub(1) + }; + Ok(( + ListItem { + principal, + blocks: super::metadata::order_block_prefix_events(blocks), + level, + marker: self.marker, + checked: self.checked, + location: state.create_location(self.start + offset, end + offset), + }, + end, + )) + } +} #[derive(Clone, Copy, Debug, Default)] pub(in crate::grammar) struct OrdinaryListScope<'a> { diff --git a/acdc-parser/src/grammar/document/lists/callout.rs b/acdc-parser/src/grammar/document/lists/callout.rs new file mode 100644 index 000000000..b58fb76f9 --- /dev/null +++ b/acdc-parser/src/grammar/document/lists/callout.rs @@ -0,0 +1,118 @@ +//! Committed callout-list construction with shared numbering and validation. + +use crate::{ + Block, Error, + grammar::{ParserState, helpers::BlockParsingMetadata}, +}; + +use super::super::{ + RecognitionError, + coordinator::{BlockCursor, Execution}, + document_parser, + metadata::order_block_prefix_events, +}; +use super::{CalloutItem, CalloutItemHead, ListEntry, ListKind, build_callout_list}; + +impl BlockCursor { + pub(super) fn construct_callout_list<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + entry: &ListEntry<'a>, + metadata: &BlockParsingMetadata<'a>, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result, Error>, RecognitionError> { + let (head, (parent_scope, callouts), end) = document_parser::first_callout_list_item( + input, + state, + self.offset, + self.base_offset, + metadata, + )?; + self.offset = end; + let result = self.collect_callout_items(input, state, entry, metadata, head, accepted); + state.callout_list_offset = parent_scope; + state.pending_callouts.clear(); + result.map(|result| { + result.map(|items| { + let end = items.last().map_or(self.offset, |(_, _, end)| *end); + build_callout_list( + state, + metadata, + state.create_location(entry.start + self.base_offset, end + self.base_offset), + items, + &callouts, + ) + }) + }) + } + + fn collect_callout_items<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + entry: &ListEntry<'a>, + metadata: &BlockParsingMetadata<'a>, + head: CalloutItemHead<'a>, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result>, Error>, RecognitionError> { + let mut item = match head.finish(state, Ok(Vec::new()), self.offset, self.base_offset) { + Ok(item) => item, + Err(error) => return Ok(Err(error)), + }; + let shell = build_callout_list( + state, + metadata, + state.create_location(entry.start + self.base_offset, item.2 + self.base_offset), + Vec::new(), + &[], + ); + if let Err(error) = accepted.run(&shell, state) { + return Ok(Err(error)); + } + let mut items = Vec::new(); + loop { + item.0.blocks = match self.collect_list_children( + input, + state, + metadata, + (ListKind::Callout, "", ""), + accepted, + )? { + Ok(blocks) => blocks, + Err(error) => return Ok(Err(error)), + }; + self.offset = + document_parser::list_item_end(input, state, self.offset, self.base_offset, true)?; + if !item.0.blocks.is_empty() { + item.2 = self.offset.saturating_sub(1); + item.0.location = state + .create_location(item.0.location.absolute_start, item.2 + self.base_offset); + item.0.blocks = order_block_prefix_events(item.0.blocks); + } + items.push(item); + let (next, end) = document_parser::next_callout_list_item( + input, + state, + self.offset, + self.base_offset, + metadata, + )?; + self.offset = end; + if let Some(head) = next { + item = match head.finish(state, Ok(Vec::new()), self.offset, self.base_offset) { + Ok(item) => item, + Err(error) => return Ok(Err(error)), + }; + } else { + return Ok(Ok(items)); + } + } + } +} diff --git a/acdc-parser/src/grammar/document/lists/construction.rs b/acdc-parser/src/grammar/document/lists/construction.rs new file mode 100644 index 000000000..75c11469f --- /dev/null +++ b/acdc-parser/src/grammar/document/lists/construction.rs @@ -0,0 +1,217 @@ +//! Advance ordinary list principals and attachments at committed boundaries. + +use crate::{ + Block, Error, + grammar::{ParserState, helpers::BlockParsingMetadata}, +}; + +use super::super::{ + RecognitionError, + coordinator::{BlockCursor, Execution}, + document_parser, + metadata::order_block_prefix_events, +}; +use super::{ + ListEntry, ListItemHead, ListKind, ListPhase, ListStepKind, OrdinaryListLayout, + build_ordinary_list, +}; + +impl BlockCursor { + pub(in crate::grammar::document) fn construct_list<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + entry: &ListEntry<'a>, + parent_metadata: &BlockParsingMetadata<'a>, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result, Error>, RecognitionError> { + let metadata = entry.metadata.as_ref().unwrap_or(parent_metadata); + self.offset = entry.body_offset; + if matches!(entry.kind, ListKind::Callout) { + return self.construct_callout_list(input, state, entry, metadata, accepted); + } + if matches!(entry.kind, ListKind::Description) { + return self.construct_description_list(input, state, entry, metadata, accepted); + } + let (head, parent_scope, end) = document_parser::first_ordinary_list_item( + input, + state, + self.offset, + self.base_offset, + entry.kind, + metadata, + )?; + self.offset = end; + let result = self.construct_ordinary_list(input, state, entry, metadata, head, accepted); + state.ordinary_list_scope = parent_scope; + result + } + + fn construct_ordinary_list<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + entry: &ListEntry<'a>, + metadata: &BlockParsingMetadata<'a>, + head: ListItemHead<'a>, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result, Error>, RecognitionError> { + let (ordered, kind) = match entry.kind { + ListKind::Unordered(kind) => (false, kind), + ListKind::Ordered(kind) => (true, kind), + ListKind::Callout | ListKind::Description => { + return Ok(Err(list_error( + state, + entry.start + self.base_offset, + "ordinary list construction received a different list kind", + ))); + } + }; + let base_marker = head.marker; + let (mut item, end) = match head.finish(state, Vec::new(), self.offset, self.base_offset) { + Ok(item) => item, + Err(error) => return Ok(Err(error)), + }; + let mut block = build_ordinary_list( + state, + metadata, + OrdinaryListLayout { + start: entry.start, + end, + offset: self.base_offset, + ordered, + has_own_metadata: kind.has_own_metadata, + }, + vec![item], + ); + if let Err(error) = accepted.run(&block, state) { + return Ok(Err(error)); + } + let Some(first) = crate::extensions::ordinary_list_items_mut(&mut block).and_then(Vec::pop) + else { + return Ok(Err(list_error( + state, + entry.start + self.base_offset, + "ordinary list builder returned no first item", + ))); + }; + item = first; + let mut items = Vec::new(); + loop { + item.blocks = match self.collect_list_children( + input, + state, + metadata, + (entry.kind, base_marker, item.marker), + accepted, + )? { + Ok(blocks) => blocks, + Err(error) => return Ok(Err(error)), + }; + self.offset = document_parser::list_item_end( + input, + state, + self.offset, + self.base_offset, + kind.allow_continuation, + )?; + if !item.blocks.is_empty() { + item.location = state.create_location( + item.location.absolute_start, + self.base_offset + self.offset.saturating_sub(1), + ); + item.blocks = order_block_prefix_events(item.blocks); + } + let last_end = item.location.absolute_end; + items.push(item); + let step = document_parser::list_next( + input, + state, + self.offset, + self.base_offset, + entry.kind, + base_marker, + base_marker, + metadata, + ListPhase::Sibling, + )?; + self.offset = step.end; + if let ListStepKind::Continue(Some(head)) = step.kind { + item = match head.finish(state, Vec::new(), self.offset, self.base_offset) { + Ok((item, _)) => item, + Err(error) => return Ok(Err(error)), + }; + } else { + *block.location_mut() = + state.create_location(entry.start + self.base_offset, last_end); + if let Some(slot) = crate::extensions::ordinary_list_items_mut(&mut block) { + *slot = items; + } + return Ok(Ok(block)); + } + } + } + pub(super) fn collect_list_children<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + metadata: &BlockParsingMetadata<'a>, + context: (ListKind<'a>, &'a str, &'a str), + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result>, Error>, RecognitionError> { + let (kind, base_marker, marker) = context; + let mut blocks = Vec::new(); + let mut phase = ListPhase::AfterPrincipal; + loop { + let step = document_parser::list_next( + input, + state, + self.offset, + self.base_offset, + kind, + base_marker, + marker, + metadata, + phase, + )?; + self.offset = step.end; + let child = match step.kind { + ListStepKind::Break(Ok(super::super::coordinator::BlockStepKind::List(entry))) => { + self.construct_list(input, state, &entry, metadata, accepted)? + } + ListStepKind::Break(Ok(kind)) => self.construct(input, state, kind, accepted)?, + ListStepKind::Break(Err(error)) => Err(error), + ListStepKind::Continue(None) if phase == ListPhase::AfterPrincipal => { + phase = ListPhase::Attachments; + continue; + } + ListStepKind::Continue(None | Some(_)) => break, + }; + match child { + Ok(block) => blocks.push(block), + Err(_) + if !accepted.failed() + && matches!(kind, ListKind::Unordered(_) | ListKind::Ordered(_)) => {} + Err(error) => return Ok(Err(error)), + } + phase = ListPhase::Attachments; + } + Ok(Ok(blocks)) + } +} + +fn list_error(state: &ParserState<'_>, offset: usize, message: &str) -> Error { + Error::Parse( + Box::new(state.create_error_source_location(state.create_location(offset, offset))), + message.into(), + ) +} diff --git a/acdc-parser/src/grammar/document/lists/description.rs b/acdc-parser/src/grammar/document/lists/description.rs new file mode 100644 index 000000000..edefe1f80 --- /dev/null +++ b/acdc-parser/src/grammar/document/lists/description.rs @@ -0,0 +1,177 @@ +//! Committed description-list items and native attachment recovery. + +use crate::{ + Block, Error, + grammar::{ParserState, helpers::BlockParsingMetadata}, +}; + +use super::super::{ + RecognitionError, + coordinator::{BlockCursor, BlockStepKind, Execution}, + document_parser, +}; +use super::{ + DescriptionItemHead, DescriptionListScope, ListEntry, build_description_list, + warn_discarded_attachment, +}; + +#[derive(Default)] +struct DescriptionChildren<'a> { + blocks: Vec>, + errors: Vec, +} + +impl BlockCursor { + pub(super) fn construct_description_list<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + entry: &ListEntry<'a>, + metadata: &BlockParsingMetadata<'a>, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result, Error>, RecognitionError> { + let (head, parent_scope, end) = document_parser::first_description_list_item( + input, + state, + self.offset, + self.base_offset, + metadata, + )?; + self.offset = end; + let result = self.collect_description_items( + input, + state, + entry, + metadata, + (head, parent_scope), + accepted, + ); + state.description_list_scope = parent_scope; + result.map(|result| { + result.map(|items| { + let end = items.last().map_or(self.offset + self.base_offset, |item| { + item.location.absolute_end + }); + build_description_list( + metadata, + state.create_location(entry.start + self.base_offset, end), + items, + ) + }) + }) + } + + fn collect_description_items<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + entry: &ListEntry<'a>, + metadata: &BlockParsingMetadata<'a>, + initial: (DescriptionItemHead<'a>, Option>), + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result>, Error>, RecognitionError> { + let (mut head, parent_scope) = initial; + let mut items = Vec::new(); + let mut first = true; + loop { + let DescriptionItemHead { source, principal } = head; + let principal = match principal { + Ok(principal) => principal, + Err(error) => return Ok(Err(error)), + }; + if first { + let end = source.principal_start + source.principal_content.trim_end().len(); + let location = state.create_block_location( + entry.start, + end.max(source.term.delimiter_end), + self.base_offset, + ); + let shell = build_description_list(metadata, location, Vec::new()); + if let Err(error) = accepted.run(&shell, state) { + return Ok(Err(error)); + } + first = false; + } + let children = match self.collect_description_children( + input, + state, + metadata, + source.term.delimiter, + accepted, + )? { + Ok(children) => children, + Err(error) => return Ok(Err(error)), + }; + // Native attachment diagnostics follow all child parsing in this + // item. Preserve that order while keeping handler failures fatal. + for error in children.errors { + warn_discarded_attachment(state, &error); + } + items.push(source.build(state, principal, children.blocks, self.base_offset)); + let (next, end) = document_parser::next_description_list_item( + input, + state, + self.offset, + self.base_offset, + metadata, + parent_scope, + )?; + self.offset = end; + if let Some(next) = next { + head = next; + } else { + return Ok(Ok(items)); + } + } + } + + fn collect_description_children<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + metadata: &BlockParsingMetadata<'a>, + delimiter: &'a str, + accepted: &mut Execution< + '_, + impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + >, + ) -> Result, Error>, RecognitionError> { + let mut children = DescriptionChildren::default(); + let mut continuing = false; + loop { + let step = document_parser::description_list_next( + input, + state, + self.offset, + self.base_offset, + metadata, + delimiter, + continuing, + )?; + self.offset = step.end; + continuing = step.continuing; + let Some(child) = step.child else { + return Ok(Ok(children)); + }; + let child = match child { + Ok(BlockStepKind::List(entry)) => { + self.construct_list(input, state, &entry, metadata, accepted)? + } + Ok(kind) => self.construct(input, state, kind, accepted)?, + Err(error) => Err(error), + }; + match child { + Ok(block) => children.blocks.push(block), + Err(error) if accepted.failed() => return Ok(Err(error)), + Err(error) if step.warn_on_error => children.errors.push(error), + Err(_) => {} + } + } + } +} diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index ee4c030d8..57b94902a 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -3,13 +3,11 @@ #![allow(clippy::too_many_arguments)] use crate::{ - Anchor, Attribution, Audio, Author, Block, BlockMetadata, CalloutList, CalloutListItem, - CalloutMarker, CiteTitle, Comment, CommentKind, CompatibilityMode, DelimitedBlock, - DelimitedBlockType, DescriptionList, DescriptionListDefinition, DescriptionListItem, - DescriptionListTerm, DiscreteHeading, DocumentAttribute, DocumentAttributes, Error, Header, - Image, InlineNode, ListItem, ListItemCheckedStatus, Location, OrderedList, PageBreak, - Paragraph, Plain, Section, Source, Subtitle, TableOfContents, ThematicBreak, Title, - UnorderedList, Video, Warning, WarningKind, + Anchor, Audio, Author, Block, BlockMetadata, CalloutListItem, Comment, CommentKind, + CompatibilityMode, DescriptionListItem, DiscreteHeading, DocumentAttribute, DocumentAttributes, + Error, Header, Image, InlineNode, ListItem, ListItemCheckedStatus, Location, PageBreak, + Paragraph, Plain, Section, Source, Subtitle, TableOfContents, ThematicBreak, Title, Video, + Warning, WarningKind, document_attribute::{ AttributeDeclaration, RawAttributeValue, join_wrapped_value, starts_like_entry_name, }, @@ -21,13 +19,18 @@ use crate::{ }, document::{ author::{derive_author_attrs, register_author_attrs}, - coordinator::{BlockStep, DocumentPrefix}, + construction::{ConstructionMode, DeferredContent, RecognizedContent, commit_content}, + coordinator::{BlockParent, BlockStep, BlockStepKind, DocumentPrefix, NestedPrefix}, delimited::{DelimitedKind, DelimitedParams, build_delimited_block}, doctype::{is_book_doctype, is_manpage_doctype}, header::{ParsedHeader, header_span, merge_header_metadata}, lists::{ - DescriptionListScope, ListMarker, OrdinaryListScope, assemble_principal_text, - build_description_list_topology, calculate_item_end, find_dlist_marker, + CalloutItem, CalloutItemHead, CalloutScope, DescriptionItemHead, + DescriptionItemSource, DescriptionListScope, DescriptionStep, + DescriptionTermSource, ListEntry, ListItemHead, ListKind, ListMarker, ListPhase, + ListStep, ListStepKind, OrdinaryListKind, OrdinaryListLayout, OrdinaryListScope, + assemble_principal_text, build_callout_list, build_description_list, + build_ordinary_list, calculate_item_end, find_dlist_marker, }, manpage::{ ManpageNameSection, derive_manpage_header_attrs, derive_name_section_attrs, @@ -35,19 +38,21 @@ use crate::{ }, metadata::{ AttributeBlockForm, AttributeOrAnchorLine, BlockMetadataLine, MetadataComment, - ParsedAttributeList, RawAttributeList, TitleSource, assign_block_caption, - finish_block_parsing_metadata, media_attributes_ahead, merge_macro_metadata, - metadata_comment, metadata_marks_discrete_heading, order_block_prefix_events, + ParsedAttributeList, RawAttributeList, TitleSource, finish_block_parsing_metadata, + media_attributes_ahead, merge_macro_metadata, metadata_comment, + metadata_marks_discrete_heading, order_block_prefix_events, parse_block_attribute_list, push_metadata_anchor, resolve_block_content_attributes, resolve_title, route_block_positions, route_media_attributes, select_heading_style, thematic_break_anchors, }, paragraph::{ParagraphParams, build_paragraph, paragraph_text_end}, + quotes::{QuoteAttribution, QuoteParams, QuoteSource, build_quote}, references::{ParsedSectionHeader, register_section_header}, revision::{IgnoredRevisionFields, RevisionInfo, process_revision_info}, sections::{apply_leveloffset, expected_child_level}, table::{ - PreparedTableCellParagraph, TableClosing, TableParseParams, parse_table_block_impl, + InitialAttributes, PreparedTableCellParagraph, TableClosing, TableParseParams, + parse_table_block_impl, }, }, helpers::{ @@ -56,7 +61,7 @@ use crate::{ }, inline_preprocessing, inline_preprocessor::InlinePreprocessorParserState, - inline_processing::{adjust_and_log_parse_error, process_inlines}, + inline_processing::process_inlines, setext, state::{BlockContext, UntitledHeaderEntries}, }, @@ -100,17 +105,28 @@ peg::parser! { }} #[no_eof] - pub(in crate::grammar::document) rule next_block(offset: usize) -> Result, Error> + pub(in crate::grammar::document) rule next_block(offset: usize, base_offset: usize, parent: BlockParent, mode: ConstructionMode) -> Result, Error> = resume_at(offset) step:( - !trailing_block_metadata_match() block:block(0, None, None) end:position!() - { block.map(|block| BlockStep::block(block, end)) } - / trailing:trailing_block_metadata(0)? end:position!() eol()* ![_] + !trailing_block_metadata_match() + block:recognized_block(base_offset, parent.level, parent.kind, mode) + end:position!() + { block.map(|kind| BlockStep { kind, end }) } + / eol()* &same_or_higher_level_section(base_offset, parent.level) + { Ok(BlockStep::end(Vec::new(), offset)) } + / trailing:trailing_block_metadata(base_offset)? end:position!() eol()* ![_] { trailing.transpose().map(|blocks| BlockStep::end(blocks.unwrap_or_default(), end)) } ) { step } + rule ordered_construction(mode: ConstructionMode) + = {? matches!(mode, ConstructionMode::Ordered).then_some(()).ok_or("recursive construction") } + + pub(in crate::grammar::document) rule block_sequence_end(offset: usize) + = resume_at(offset) eol()* + // Header entries among the first block's metadata are applied by the body. // Defer the snapshot until those entries have been processed. rule header_attribute_snapshot() -> Option> + = { if state.untitled_header_entries.is_some() { None @@ -673,7 +689,7 @@ peg::parser! { } pub(in crate::grammar::document) rule blocks(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result>, Error> - = blocks:(!trailing_block_metadata_match() block:block(offset, parent_section_level, direct_parent_section_kind) { block })* + = blocks:(!trailing_block_metadata_match() block:block(offset, parent_section_level, direct_parent_section_kind, ConstructionMode::Recursive) { block })* trailing:trailing_block_metadata(offset)? { let mut blocks = blocks.into_iter().collect::, Error>>()?; @@ -701,18 +717,26 @@ peg::parser! { events.into_iter().flatten().collect() } - pub(in crate::grammar::document) rule nested_document_blocks(offset: usize, initial_attributes: &mut Vec<(crate::AttributeName<'input>, crate::DocumentAttributeAssignment<'input>)>) -> Result>, Error> + pub(in crate::grammar::document) rule nested_document_blocks(offset: usize, initial_attributes: &mut InitialAttributes<'input>) -> Result>, Error> + = prefix:nested_document_prefix(offset, initial_attributes) + body:blocks(offset, None, None) + { + let mut blocks = prefix?.blocks; + blocks.extend(body?); + Ok(order_block_prefix_events(blocks)) + } + + #[no_eof] + pub(in crate::grammar::document) rule nested_document_prefix(offset: usize, initial_attributes: &mut InitialAttributes<'input>) -> Result, Error> = eol()* header:( comment:comment_line_block(offset) eol()* { comment } / attribute:document_attribute_block(offset) (eol() / ![_]) { attribute } )* header:normalize_nested_header(header, initial_attributes) - body:blocks(offset, None, None) + body_offset:position!() { - let mut blocks = header?; - blocks.extend(body?); - Ok(order_block_prefix_events(blocks)) + header.map(|blocks| NestedPrefix { blocks, body_offset }) } rule normalize_nested_header(header: Vec, Error>>, initial_attributes: &mut Vec<(crate::AttributeName<'input>, crate::DocumentAttributeAssignment<'input>)>) -> Result>, Error> @@ -757,30 +781,34 @@ peg::parser! { blocks.into_iter().collect() } - rule block(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result, Error> + rule block(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option, mode: ConstructionMode) -> Result, Error> + = value:recognized_block(offset, parent_section_level, direct_parent_section_kind, mode) + { value.and_then(|value| value.into_ready(state)) } + + rule recognized_block(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option, mode: ConstructionMode) -> Result, Error> = eol()* // First check: if we're at a same-or-higher-level section, fail the entire block // This prevents section content from consuming sibling/parent sections as paragraphs !same_or_higher_level_section(offset, parent_section_level) block:( - comment_line_block(offset) / - document_attribute_block(offset) / + value:comment_line_block(offset) { value.map(BlockStepKind::Block) } / + value:document_attribute_block(offset) { value.map(BlockStepKind::Block) } / // A discrete heading is introduced by an attribute line (`[discrete]`, // `[#id,discrete]`, `[float]`, …) or an anchor preceding one, so only // attempt it when the block starts with `[`. The rule itself backtracks // to `section`/`block_generic` when the metadata isn't a discrete marker. - &"[" dh:discrete_header(offset) { dh } / - section:section(offset, parent_section_level, direct_parent_section_kind) { section } / + &"[" dh:discrete_header(offset) { dh.map(BlockStepKind::Block) } / + section:section(offset, parent_section_level, direct_parent_section_kind, mode) { section.map(BlockStepKind::Block) } / // Legacy underlined sections are recognized in Asciidoctor mode. - section_setext:section_setext(offset, parent_section_level, direct_parent_section_kind) { section_setext } / - block_generic(offset, parent_section_level) + section_setext:section_setext(offset, parent_section_level, direct_parent_section_kind, mode) { section_setext.map(BlockStepKind::Block) } / + block_generic(offset, parent_section_level, mode) ) { block } /// Single-line comment that becomes a block in the AST. /// Line comments begin with `//` (but not `///` or `////` which are block comment delimiters). rule comment_line_block(offset: usize) -> Result, Error> - = "//" !("/") content:$([^'\n']*) end:position!() (eol() / ![_]) + = comment_line_prefix() content:$([^'\n']*) end:position!() (eol() / ![_]) { // `end` is captured before consuming the trailing newline so the // comment's location doesn't include it. @@ -792,6 +820,9 @@ peg::parser! { })) } + rule comment_line_prefix() + = "//" !"/" + rule leading_comment() -> Result, Error> = comment_line_block(0) / start:position!() block:comment_block(start, 0, &BlockParsingMetadata::new(state.options.compatibility_mode)) { block } @@ -809,7 +840,7 @@ peg::parser! { /// `+` continuation following the comment can still match, since /// continuation markers expect a leading newline before the `+`. rule comment_line_block_keep_eol(offset: usize) -> Result, Error> - = "//" !("/") content:$([^'\n']*) end:position!() &(eol() / ![_]) + = comment_line_prefix() content:$([^'\n']*) end:position!() &(eol() / ![_]) { Ok(Block::Comment(Comment { kind: CommentKind::Line, @@ -958,7 +989,7 @@ peg::parser! { Ok(Block::DocumentAttribute(event)) } - rule section(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result, Error> + rule section(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option, mode: ConstructionMode) -> Result, Error> = check_section_blocks() &atx_heading_match() block_metadata:(bm:heading_metadata(offset, parent_section_level) {? bm.map_err(|_| { @@ -984,7 +1015,7 @@ peg::parser! { direct_parent_section_kind, )) }) - content:section_content(offset, Some(expected_child_level( + content:section_content(mode, offset, Some(expected_child_level( section_level.1, SectionKind::from_style(block_metadata.metadata.style), is_book_doctype(&state.document_attributes), @@ -1095,7 +1126,7 @@ peg::parser! { /// Parse a setext-style section (title followed by underline). /// Excludes description list items (e.g., `term:: content`) which would otherwise /// match as setext titles. - rule section_setext(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result, Error> + rule section_setext(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option, mode: ConstructionMode) -> Result, Error> = check_section_blocks() !check_line_is_description_list(offset) &setext_section_match(parent_section_level) block_metadata:(bm:heading_metadata(offset, parent_section_level) {? @@ -1121,7 +1152,7 @@ peg::parser! { direct_parent_section_kind, )) }) - content:section_content(offset, Some(expected_child_level( + content:section_content(mode, offset, Some(expected_child_level( setext_level, SectionKind::from_style(block_metadata.metadata.style), is_book_doctype(&state.document_attributes), @@ -1364,10 +1395,14 @@ peg::parser! { Ok((Title::new(content), natural_title)) } - rule section_content(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result>, Error> - = blocks(offset, parent_section_level, direct_parent_section_kind) / { Ok(vec![]) } + rule section_content(mode: ConstructionMode, offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result>, Error> + = recursive_section_content(mode) blocks:blocks(offset, parent_section_level, direct_parent_section_kind) { blocks } + / { Ok(vec![]) } - rule block_generic(offset: usize, parent_section_level: Option) -> Result, Error> + rule recursive_section_content(mode: ConstructionMode) + = {? matches!(mode, ConstructionMode::Recursive).then_some(()).ok_or("section body belongs to the coordinator") } + + rule block_generic(offset: usize, parent_section_level: Option, mode: ConstructionMode) -> Result, Error> = start:position!() block_metadata:(bm:block_metadata(offset, parent_section_level) {? bm.map_err(|_| { @@ -1376,24 +1411,27 @@ peg::parser! { }) }) block:( - delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block } - / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim } - / extension:extension_macro(start, offset, &block_metadata) { extension } - / image:image(start, offset, &block_metadata) { image } - / audio:audio(start, offset, &block_metadata) { audio } - / video:video(start, offset, &block_metadata) { video } - / toc:toc(start, offset, &block_metadata) { toc } - / excessive_list_item(start, offset, &block_metadata) - / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break } - / page_break:page_break(start, offset, &block_metadata) { page_break } - / list:list(start, offset, &block_metadata) { list } - / quoted_paragraph:quoted_paragraph(start, offset, &block_metadata) { quoted_paragraph } - / markdown_blockquote:markdown_blockquote(start, offset, &block_metadata) { markdown_blockquote } - / paragraph:paragraph(start, offset, &block_metadata) { paragraph } + ordered_construction(mode) params:generic_delimited_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Delimited(params))) } + / ordered_construction(mode) params:table_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Table(params))) } + / delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block.map(RecognizedContent::Continue) } + / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim.map(RecognizedContent::Continue) } + / recovered:excessive_list_item(start, offset, &block_metadata) { recovered.map(RecognizedContent::Continue) } + / extension:extension_macro(start, offset, &block_metadata) { extension.map(RecognizedContent::Continue) } + / image:image(start, offset, &block_metadata) { image.map(RecognizedContent::Continue) } + / audio:audio(start, offset, &block_metadata) { audio.map(RecognizedContent::Continue) } + / video:video(start, offset, &block_metadata) { video.map(RecognizedContent::Continue) } + / toc:toc(start, offset, &block_metadata) { toc.map(RecognizedContent::Continue) } + / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break.map(RecognizedContent::Continue) } + / page_break:page_break(start, offset, &block_metadata) { page_break.map(RecognizedContent::Continue) } + / ordered_construction(mode) body_offset:position!() kind:committed_list_kind(offset, &block_metadata, true) { Ok(RecognizedContent::Break(DeferredContent::List { start, body_offset, kind })) } + / list:list(start, offset, &block_metadata) { list.map(RecognizedContent::Continue) } + / ordered_construction(mode) params:quoted_paragraph_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } + / quoted_paragraph:quoted_paragraph(start, offset, &block_metadata) { quoted_paragraph.map(RecognizedContent::Continue) } + / ordered_construction(mode) params:markdown_blockquote_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } + / markdown_blockquote:markdown_blockquote(start, offset, &block_metadata) { markdown_blockquote.map(RecognizedContent::Continue) } + / paragraph:paragraph(start, offset, &block_metadata) { paragraph.map(RecognizedContent::Continue) } ) { - let mut block = block?; - assign_block_caption(state, &mut block); - Ok(block) + block.map(|content| commit_content(state, block_metadata, content)) } // Block parsing for continuation context - lists inside continuations cannot consume @@ -1401,11 +1439,15 @@ peg::parser! { // Comments before attached content do not consume its continuation. // Keep comment-only and next-item cases on the existing path. rule block_in_continuation(offset: usize, parent_section_level: Option, parent_marker: Option>) -> Result, Error> + = value:recognized_block_in_continuation(offset, parent_section_level, parent_marker, ConstructionMode::Recursive) + { value.and_then(|value| value.into_ready(state)) } + + rule recognized_block_in_continuation(offset: usize, parent_section_level: Option, parent_marker: Option>, mode: ConstructionMode) -> Result, Error> = continuation_comments() !eol() !at_list_item_start() !at_callout_list_item() !check_line_is_description_list(offset) !("+" whitespace()* (eol() / ![_])) - block:continuation_block(offset, parent_section_level, parent_marker) { block } - / block:continuation_block(offset, parent_section_level, parent_marker) { block } + block:recognized_continuation_block(offset, parent_section_level, parent_marker, mode) { block } + / block:recognized_continuation_block(offset, parent_section_level, parent_marker, mode) { block } rule continuation_comments() = eol()* ( @@ -1414,7 +1456,7 @@ peg::parser! { until_block_close(delimiter) eol()? block_close_delim(delimiter) eol()? ) - rule continuation_block(offset: usize, parent_section_level: Option, parent_marker: Option>) -> Result, Error> + rule recognized_continuation_block(offset: usize, parent_section_level: Option, parent_marker: Option>, mode: ConstructionMode) -> Result, Error> = !trailing_block_metadata_match() start:position!() block_metadata:(bm:block_metadata(offset, parent_section_level) {? bm.map_err(|_| { @@ -1433,27 +1475,30 @@ peg::parser! { comment:(eol()* comment_start:position!() c:( comment_line_block_keep_eol(offset) / comment_block(comment_start, offset, &block_metadata) - ) { c }) { comment } - / delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block } - / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim } - / extension:extension_macro(start, offset, &block_metadata) { extension } - / image:image(start, offset, &block_metadata) { image } - / audio:audio(start, offset, &block_metadata) { audio } - / video:video(start, offset, &block_metadata) { video } - / toc:toc(start, offset, &block_metadata) { toc } - / excessive_list_item(start, offset, &block_metadata) - / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break } - / page_break:page_break(start, offset, &block_metadata) { page_break } + ) { c }) { comment.map(RecognizedContent::Continue) } + / ordered_construction(mode) params:generic_delimited_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Delimited(params))) } + / ordered_construction(mode) params:table_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Table(params))) } + / delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block.map(RecognizedContent::Continue) } + / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim.map(RecognizedContent::Continue) } + / recovered:excessive_list_item(start, offset, &block_metadata) { recovered.map(RecognizedContent::Continue) } + / extension:extension_macro(start, offset, &block_metadata) { extension.map(RecognizedContent::Continue) } + / image:image(start, offset, &block_metadata) { image.map(RecognizedContent::Continue) } + / audio:audio(start, offset, &block_metadata) { audio.map(RecognizedContent::Continue) } + / video:video(start, offset, &block_metadata) { video.map(RecognizedContent::Continue) } + / toc:toc(start, offset, &block_metadata) { toc.map(RecognizedContent::Continue) } + / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break.map(RecognizedContent::Continue) } + / page_break:page_break(start, offset, &block_metadata) { page_break.map(RecognizedContent::Continue) } // Lists in continuation context cannot consume further continuations - / list:list_with_continuation(start, offset, &block_metadata, false) { list } - / quoted_paragraph:quoted_paragraph(start, offset, &block_metadata) { quoted_paragraph } - / markdown_blockquote:markdown_blockquote(start, offset, &block_metadata) { markdown_blockquote } + / ordered_construction(mode) body_offset:position!() kind:committed_list_kind(offset, &block_metadata, false) { Ok(RecognizedContent::Break(DeferredContent::List { start, body_offset, kind })) } + / list:list_with_continuation(start, offset, &block_metadata, false) { list.map(RecognizedContent::Continue) } + / ordered_construction(mode) params:quoted_paragraph_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } + / quoted_paragraph:quoted_paragraph(start, offset, &block_metadata) { quoted_paragraph.map(RecognizedContent::Continue) } + / ordered_construction(mode) params:markdown_blockquote_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } + / markdown_blockquote:markdown_blockquote(start, offset, &block_metadata) { markdown_blockquote.map(RecognizedContent::Continue) } / !(eol()+ attached_list_marker()) - paragraph:paragraph_with_list_boundary(start, offset, &block_metadata, parent_marker) { paragraph } + paragraph:paragraph_with_list_boundary(start, offset, &block_metadata, parent_marker) { paragraph.map(RecognizedContent::Continue) } ) { - let mut block = block?; - assign_block_caption(state, &mut block); - Ok(block) + block.map(|content| commit_content(state, block_metadata, content)) } rule delimited_block( @@ -1472,6 +1517,12 @@ peg::parser! { // to end of input still produce a block, closed at EOF (asciidoctor's // recovery; `build_delimited_block` emits the unterminated warning). rule generic_delimited_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = params:generic_delimited_params(start, offset) + { + build_delimited_block(state, block_metadata, ¶ms) + } + + rule generic_delimited_params(start: usize, offset: usize) -> DelimitedParams<'input> = open_start:position!() open:block_open() (eol() / ![_]) content_start:position!() source_text:$(until_block_close(open.1) (eol() &block_close_delim(open.1))?) body_end:position!() @@ -1483,10 +1534,10 @@ peg::parser! { source_text }; let content_end = body_end - (source_text.len() - content.len()); - build_delimited_block(state, block_metadata, &DelimitedParams { + DelimitedParams { kind: open.0, open_delim: open.1, content, source_text, open_start, start, content_start, content_end, end: span_end, offset, close, - }) + } } // Recognize a non-table delimited-block opening delimiter, returning its @@ -1585,77 +1636,64 @@ peg::parser! { // Terminated variants are tried first; unterminated fallbacks only match // when an opening delimiter runs to end-of-input without a close. rule table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> - = pipe_table_block(start, offset, block_metadata) - / excl_table_block(start, offset, block_metadata) - / comma_table_block(start, offset, block_metadata) - / colon_table_block(start, offset, block_metadata) - / unterminated_pipe_table_block(start, offset, block_metadata) - / unterminated_excl_table_block(start, offset, block_metadata) - / unterminated_comma_table_block(start, offset, block_metadata) - / unterminated_colon_table_block(start, offset, block_metadata) - - rule pipe_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = params:table_params(start, offset) { parse_table_block_impl(¶ms, state, block_metadata) } + + rule table_params(start: usize, offset: usize) -> TableParseParams<'input> + = pipe_table_params(start, offset) + / excl_table_params(start, offset) + / comma_table_params(start, offset) + / colon_table_params(start, offset) + / unterminated_pipe_table_params(start, offset) + / unterminated_excl_table_params(start, offset) + / unterminated_comma_table_params(start, offset) + / unterminated_colon_table_params(start, offset) + + rule pipe_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:pipe_table_delimiter() eol() content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: "|", closing: TableClosing::Terminated { close_delim, close_start }, - }, - state, - block_metadata, - ) + } } - rule excl_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule excl_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:excl_table_delimiter() eol() content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: "!", closing: TableClosing::Terminated { close_delim, close_start }, - }, - state, - block_metadata, - ) + } } - rule comma_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule comma_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:comma_table_delimiter() eol() content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: ",", closing: TableClosing::Terminated { close_delim, close_start }, - }, - state, - block_metadata, - ) + } } - rule colon_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule colon_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:colon_table_delimiter() eol() content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: ":", closing: TableClosing::Terminated { close_delim, close_start }, - }, - state, - block_metadata, - ) + } } // Unterminated table fallbacks: match an opening table delimiter @@ -1670,68 +1708,52 @@ peg::parser! { // `|===\n...` and `|===`: the preprocessor's `normalize` // strips a single trailing newline (mirroring `str::lines`), so a // file ending with just `|===\n` reaches the grammar as `|===`. - rule unterminated_pipe_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule unterminated_pipe_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:pipe_table_delimiter() (eol() / ![_]) content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() ![_] { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: "|", closing: TableClosing::Unterminated, - }, - state, - block_metadata, - ) + } } - rule unterminated_excl_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule unterminated_excl_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:excl_table_delimiter() (eol() / ![_]) content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() ![_] { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: "!", closing: TableClosing::Unterminated, - }, - state, - block_metadata, - ) + } } - rule unterminated_comma_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule unterminated_comma_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:comma_table_delimiter() (eol() / ![_]) content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() ![_] { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: ",", closing: TableClosing::Unterminated, - }, - state, - block_metadata, - ) + } } - rule unterminated_colon_table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule unterminated_colon_table_params(start: usize, offset: usize) -> TableParseParams<'input> = table_start:position!() open_delim:colon_table_delimiter() (eol() / ![_]) content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() ![_] { - parse_table_block_impl( - &TableParseParams { + TableParseParams { start, offset, table_start, content_start, content_end, end: span_end, open_delim, content, default_separator: ":", closing: TableClosing::Unterminated, - }, - state, - block_metadata, - ) + } } rule toc(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> @@ -1914,6 +1936,198 @@ peg::parser! { ) { list } / description_list(start, offset, block_metadata) + + rule unordered_kind(kind: ListKind<'input>) -> OrdinaryListKind<'input> + = {? if let ListKind::Unordered(kind) = kind { Ok(kind) } else { Err("not unordered") } } + + rule ordered_kind(kind: ListKind<'input>) -> OrdinaryListKind<'input> + = {? if let ListKind::Ordered(kind) = kind { Ok(kind) } else { Err("not ordered") } } + + rule callout_kind(kind: ListKind<'input>) + = {? matches!(kind, ListKind::Callout).then_some(()).ok_or("not callout") } + + rule description_kind(kind: ListKind<'input>) + = {? matches!(kind, ListKind::Description).then_some(()).ok_or("not description") } + + rule nested_same(kind: OrdinaryListKind<'input>) -> &'input str + = {? kind.parent_same.ok_or("no same-type parent") } + + rule native_list_entry(offset: usize, entry: &ListEntry<'input>, parent_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = kind:unordered_kind(entry.kind) parent:nested_same(kind) + list:unordered_list_nested(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), parent, kind.parent_other, kind.has_own_metadata) { list } + / kind:unordered_kind(entry.kind) parent_is_none(kind.parent_same) + list:unordered_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), kind.parent_other, kind.allow_continuation, !kind.has_own_metadata) { list } + / kind:ordered_kind(entry.kind) parent:nested_same(kind) + list:ordered_list_nested(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), parent, kind.parent_other, kind.has_own_metadata) { list } + / kind:ordered_kind(entry.kind) parent_is_none(kind.parent_same) + list:ordered_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), kind.parent_other, kind.allow_continuation, !kind.has_own_metadata) { list } + / callout_kind(entry.kind) list:callout_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata)) { list } + / description_kind(entry.kind) list:description_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata)) { list } + + rule description_list_ahead(offset: usize) + = !at_list_item_start() !at_callout_list_item() !at_description_parent_item(offset) + check_line_is_description_list(offset) + + rule nested_kind_allowed(kind: ListKind<'input>, metadata: &BlockParsingMetadata<'input>) + = callout_kind(kind) structural_block_boundaries(metadata) + / !callout_kind(kind) + + rule unordered_child_kind(offset: usize, current_marker: &'input str, parent_ordered_marker: Option<&'input str>, own: bool) -> ListKind<'input> + = !at_open_ordered_marker(offset) + &(whitespace()* ordered_list_marker() whitespace()) + { ListKind::Ordered(OrdinaryListKind { parent_other: Some(current_marker), parent_same: None, allow_continuation: false, has_own_metadata: own }) } + / &at_nested_unordered_marker(offset, current_marker) + { ListKind::Unordered(OrdinaryListKind { parent_other: parent_ordered_marker, parent_same: Some(current_marker), allow_continuation: false, has_own_metadata: own }) } + / !at_callout_parent_item(offset) &at_callout_list_item() { ListKind::Callout } + / &description_list_ahead(offset) { ListKind::Description } + + rule unordered_child_entry_with_metadata(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> ListEntry<'input> + = start:position!() own:parsed_nested_list_metadata(offset, metadata.parent_section_level) + nested_list_metadata_gap()* kind:unordered_child_kind(offset, current_marker, parent_ordered_marker, true) nested_kind_allowed(kind, &own) + { ListEntry { start, body_offset: span_end, metadata: Some(own), kind } } + + rule unordered_child_entry(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> ListEntry<'input> + = start:position!() kind:unordered_child_kind(offset, current_marker, parent_ordered_marker, false) + content_metadata:( + callout_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } + / description_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } + / { None } + ) + { ListEntry { start, body_offset: start, metadata: content_metadata, kind } } + + rule ordered_child_kind(offset: usize, current_marker: &'input str, parent_unordered_marker: Option<&'input str>, own: bool) -> ListKind<'input> + = !at_open_unordered_marker(offset) + &(whitespace()* unordered_list_marker() whitespace()) + { ListKind::Unordered(OrdinaryListKind { parent_other: Some(current_marker), parent_same: None, allow_continuation: false, has_own_metadata: own }) } + / &at_nested_ordered_marker(offset, current_marker) + { ListKind::Ordered(OrdinaryListKind { parent_other: parent_unordered_marker, parent_same: Some(current_marker), allow_continuation: false, has_own_metadata: own }) } + / !at_callout_parent_item(offset) &at_callout_list_item() { ListKind::Callout } + / &description_list_ahead(offset) { ListKind::Description } + + rule ordered_child_entry_with_metadata(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> ListEntry<'input> + = start:position!() own:parsed_nested_list_metadata(offset, metadata.parent_section_level) + nested_list_metadata_gap()* kind:ordered_child_kind(offset, current_marker, parent_unordered_marker, true) nested_kind_allowed(kind, &own) + { ListEntry { start, body_offset: span_end, metadata: Some(own), kind } } + + rule ordered_child_entry(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> ListEntry<'input> + = start:position!() kind:ordered_child_kind(offset, current_marker, parent_unordered_marker, false) + content_metadata:( + callout_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } + / description_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } + / { None } + ) + { ListEntry { start, body_offset: start, metadata: content_metadata, kind } } + + + rule committed_list_kind(offset: usize, metadata: &BlockParsingMetadata<'input>, allow: bool) -> ListKind<'input> + = at_callout_list_item() structural_block_boundaries(metadata) callout_list_marker() { ListKind::Callout } + / ordinary_list_kind(offset, allow) + / description_list_ahead(offset) description_list_term_source() { ListKind::Description } + + #[no_eof] + pub(in crate::grammar::document) rule first_callout_list_item(offset: usize, base: usize, metadata: &BlockParsingMetadata<'input>) -> (CalloutItemHead<'input>, CalloutScope, usize) + = resume_at(offset) at_callout_list_item() structural_block_boundaries(metadata) + scope:enter_callout_list(base) head:callout_list_head(base, metadata) end:position!() + { (head, scope, end) } + + #[no_eof] + pub(in crate::grammar::document) rule next_callout_list_item(offset: usize, base: usize, metadata: &BlockParsingMetadata<'input>) -> (Option>, usize) + = resume_at(offset) head:(eol()* head:callout_list_head(base, metadata) { head })? end:position!() + { (head, end) } + + #[no_eof] + pub(in crate::grammar::document) rule first_description_list_item(offset: usize, base: usize, metadata: &BlockParsingMetadata<'input>) -> (DescriptionItemHead<'input>, Option>, usize) + = resume_at(offset) description_list_ahead(base) parent:enter_description_list(base) + head:description_list_head(base, metadata) end:position!() { (head, parent, end) } + + #[no_eof] + pub(in crate::grammar::document) rule next_description_list_item(offset: usize, base: usize, metadata: &BlockParsingMetadata<'input>, parent: Option>) -> (Option>, usize) + = resume_at(offset) parent_item_continuation(base)? head:(description_list_additional_prefix(base, parent) head:description_list_head(base, metadata) { head })? end:position!() + { (head, end) } + + rule continuing_description(actual: bool) + = {? actual.then_some(()).ok_or("no active description continuation group") } + + #[no_eof] + pub(in crate::grammar::document) rule description_list_next(offset: usize, base: usize, metadata: &BlockParsingMetadata<'input>, delimiter: &'input str, continuing: bool) -> DescriptionStep<'input> + = resume_at(offset) value:( + continuing_description(continuing) description_continuation_prefix(base) + block:recognized_block_in_continuation(base, metadata.parent_section_level, Some(ListMarker::Description(delimiter)), ConstructionMode::Ordered) + end:position!() { DescriptionStep { child: Some(block), end, continuing: true, warn_on_error: false } } + / eol() description_continuation_prefix(base) + block:recognized_block_in_continuation(base, metadata.parent_section_level, Some(ListMarker::Description(delimiter)), ConstructionMode::Ordered) + end:position!() { DescriptionStep { child: Some(block), end, continuing: true, warn_on_error: false } } + / eol() entry:description_auto_entry(base, metadata) end:position!() + { DescriptionStep { child: Some(Ok(BlockStepKind::List(entry))), end, continuing: false, warn_on_error: true } } + / { DescriptionStep { child: None, end: offset, continuing: false, warn_on_error: false } } + ) { value } + + rule ordinary_list_kind(offset: usize, allow: bool) -> ListKind<'input> + = scope:ordinary_list_scope(offset) kind:( + whitespace()* unordered_list_marker() &whitespace() + { ListKind::Unordered(OrdinaryListKind { parent_other: scope.ordered, parent_same: None, allow_continuation: allow, has_own_metadata: true }) } + / whitespace()* ordered_list_marker() &whitespace() + { ListKind::Ordered(OrdinaryListKind { parent_other: scope.unordered, parent_same: None, allow_continuation: allow, has_own_metadata: true }) } + ) { kind } + + rule list_phase(actual: ListPhase, expected: ListPhase) + = {? (actual == expected).then_some(()).ok_or("different list phase") } + + #[no_eof] + pub(in crate::grammar::document) rule first_ordinary_list_item(offset: usize, base: usize, kind: ListKind<'input>, metadata: &BlockParsingMetadata<'input>) -> (ListItemHead<'input>, Option>, usize) + = resume_at(offset) result:( + kind:unordered_kind(kind) prefix:unordered_list_prefix(base) empty_start:position!() + head:unordered_list_head(base, metadata, prefix.0, prefix.1, empty_start, kind.parent_other) + end:position!() { (head, prefix.2, end) } + / kind:ordered_kind(kind) prefix:ordered_list_prefix(base) empty_start:position!() + head:ordered_list_head(base, metadata, prefix.0, prefix.1, empty_start, kind.parent_other) + end:position!() { (head, prefix.2, end) } + ) { result } + + #[no_eof] + pub(in crate::grammar::document) rule list_next(offset: usize, base: usize, kind: ListKind<'input>, base_marker: &'input str, marker: &'input str, metadata: &BlockParsingMetadata<'input>, phase: ListPhase) -> ListStep<'input> + = resume_at(offset) value:( + list_phase(phase, ListPhase::AfterPrincipal) + entry:( + kind:unordered_kind(kind) entry:unordered_child_after_principal(base, metadata, marker, kind.parent_other) { entry } + / kind:ordered_kind(kind) entry:ordered_child_after_principal(base, metadata, marker, kind.parent_other) { entry } + / callout_kind(kind) entry:callout_child_after_principal(base, metadata) { entry } + ) end:position!() { ListStep { kind: ListStepKind::Break(Ok(BlockStepKind::List(entry))), end } } + / list_phase(phase, ListPhase::Attachments) !at_list_separator() + value:( + parent:(kind:unordered_kind(kind) { (Some(ListMarker::Unordered(marker)), kind.allow_continuation) } + / kind:ordered_kind(kind) { (Some(ListMarker::Ordered(marker)), kind.allow_continuation) } + / callout_kind(kind) { (None, true) }) + (list_continuation_immediate_prefix(base) + / list_continuation_allowed(parent.1) list_continuation_ancestor_prefix(base)) + block:recognized_block_in_continuation(base, metadata.parent_section_level, parent.0, ConstructionMode::Ordered) + end:position!() { ListStep { kind: ListStepKind::Break(block), end } } + / entry:( + kind:unordered_kind(kind) entry:unordered_child_after_attachment(base, metadata, marker, kind.parent_other) { entry } + / kind:ordered_kind(kind) entry:ordered_child_after_attachment(base, metadata, marker, kind.parent_other) { entry } + ) end:position!() { ListStep { kind: ListStepKind::Break(Ok(BlockStepKind::List(entry))), end } } + ) { value } + / list_phase(phase, ListPhase::Sibling) head:( + kind:unordered_kind(kind) + (parent:nested_same(kind) unordered_list_nested_rest_prefix(base, parent, base_marker) + / parent_is_none(kind.parent_same) unordered_list_rest_prefix(base, kind.parent_other, base_marker)) + item_start:position!() whitespace()* marker:unordered_list_marker() + head:unordered_list_head(base, metadata, marker, item_start, item_start, kind.parent_other) { head } + / kind:ordered_kind(kind) + (parent:nested_same(kind) ordered_list_nested_rest_prefix(base, parent, base_marker) + / parent_is_none(kind.parent_same) ordered_list_rest_prefix(base, kind.parent_other, base_marker)) + item_start:position!() whitespace()* marker:ordered_list_marker() + head:ordered_list_head(base, metadata, marker, item_start, item_start, kind.parent_other) { head } + ) end:position!() { ListStep { kind: ListStepKind::Continue(Some(head)), end } } + / { ListStep { kind: ListStepKind::Continue(None), end: offset } } + ) { value } + + #[no_eof] + pub(in crate::grammar::document) rule list_item_end(offset: usize, base: usize, allow: bool) -> usize + = resume_at(offset) + (list_continuation_allowed(allow) list_dangling_continuation())? + parent_item_continuation(base)? end:position!() { end } + rule raw_unordered_list_marker() -> &'input str = $("*"+ / "-") rule raw_ordered_list_marker() -> &'input str = $(digits()? "."+) @@ -2157,31 +2371,33 @@ peg::parser! { / ("." ![' ' | '\t' | '\n' | '\r' | '.'] [^'\n']* eol()) ) + rule unordered_list_prefix(offset: usize) -> (&'input str, usize, Option>) + = whitespace()* marker_start:position!() marker:$(unordered_list_marker()) &whitespace() + parent:enter_ordinary_list(offset, Some(marker), None) + { (marker, marker_start, parent) } + + rule ordered_list_prefix(offset: usize) -> (&'input str, usize, Option>) + = whitespace()* marker_start:position!() marker:$(ordered_list_marker()) &whitespace() + parent:enter_ordinary_list(offset, None, Some(marker)) + { (marker, marker_start, parent) } + rule unordered_list(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_ordered_marker: Option<&'input str>, allow_continuation: bool, is_nested: bool) -> Result, Error> - // Parse whitespace + marker first to capture base_marker for rest items + // Parse the marker and enter its scope before constructing principals. // marker_start captures position before marker for correct first item location - = whitespace()* marker_start:position!() base_marker:$(unordered_list_marker()) &whitespace() - parent_scope:enter_ordinary_list(offset, Some(base_marker), None) - first:unordered_list_item_after_marker(offset, block_metadata, allow_continuation, base_marker, marker_start, parent_ordered_marker) - rest:(unordered_list_rest_item(offset, block_metadata, parent_ordered_marker, allow_continuation, base_marker))* + = prefix:unordered_list_prefix(offset) + first:unordered_list_item_after_marker(offset, block_metadata, allow_continuation, prefix.0, prefix.1, parent_ordered_marker) + rest:(unordered_list_rest_item(offset, block_metadata, parent_ordered_marker, allow_continuation, prefix.0))* { tracing::debug!("Found unordered list block"); - state.ordinary_list_scope = parent_scope; + state.ordinary_list_scope = prefix.2; let mut content = vec![first?]; for item in rest { content.push(item?); } let end = content.last().map_or(span_end, |(_, item_end)| *item_end); let items: Vec> = content.into_iter().map(|(item, _)| item).collect(); - let marker = items.first().map_or("", |item| item.marker); - Ok(Block::UnorderedList(UnorderedList { - title: if is_nested { Title::default() } else { block_metadata.title.clone() }, - metadata: if is_nested { BlockMetadata::default() } else { block_metadata.metadata.clone() }, - items, - marker, - location: state.create_location(start+offset, end+offset), - })) + Ok(build_ordinary_list(state, block_metadata, OrdinaryListLayout { start, end, offset, ordered: false, has_own_metadata: !is_nested }, items)) } // Parse first item content after marker has been consumed by unordered_list @@ -2200,51 +2416,35 @@ peg::parser! { rule parent_is_none(parent: Option<&'input str>) -> () = {? if parent.is_none() { Ok(()) } else { Err("parent_is_some") } } - rule unordered_list_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_ordered_marker: Option<&'input str>, allow_continuation: bool, base_marker: &str) -> Result<(ListItem<'input>, usize), Error> - // `parent_ordered_marker` is fixed for the whole `unordered_list` call, so - // rather than parse the (expensive) item first and reject via a trailing - // `{? }` action on three of four alternatives, guard each alternative at - // the front with a zero-cost check and only parse when the branch applies. - // The `!at_ordered_marker_ahead()` lookahead is kept only in the - // `parent_ordered_marker.is_some()` branch where it actually pays off. - // See fixtures: nested_unordered_in_ordered.adoc, nested_ordered_in_unordered.adoc - // - // Branch: parent is ordered - = parent_is_some(parent_ordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_unordered_marker(offset, base_marker) !at_ordered_marker_ahead() item:unordered_list_item(offset, block_metadata, allow_continuation, parent_ordered_marker) - { item } - / parent_is_some(parent_ordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_unordered_marker(offset, base_marker) !at_ordered_marker_ahead() item:unordered_list_item(offset, block_metadata, allow_continuation, parent_ordered_marker) - { item } + rule unordered_list_rest_prefix(offset: usize, parent_ordered_marker: Option<&'input str>, base_marker: &str) + = parent_is_some(parent_ordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_unordered_marker(offset, base_marker) !at_ordered_marker_ahead() + / parent_is_some(parent_ordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_unordered_marker(offset, base_marker) !at_ordered_marker_ahead() // Branch: no ordered parent - / parent_is_none(parent_ordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_unordered_marker(offset, base_marker) item:unordered_list_item(offset, block_metadata, allow_continuation, parent_ordered_marker) - { item } - / parent_is_none(parent_ordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_unordered_marker(offset, base_marker) item:unordered_list_item(offset, block_metadata, allow_continuation, parent_ordered_marker) - { item } + / parent_is_none(parent_ordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_unordered_marker(offset, base_marker) + / parent_is_none(parent_ordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_unordered_marker(offset, base_marker) + + rule unordered_list_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_ordered_marker: Option<&'input str>, allow_continuation: bool, base_marker: &str) -> Result<(ListItem<'input>, usize), Error> + = unordered_list_rest_prefix(offset, parent_ordered_marker, base_marker) + item:unordered_list_item(offset, block_metadata, allow_continuation, parent_ordered_marker) { item } + rule ordered_list(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_unordered_marker: Option<&'input str>, allow_continuation: bool, is_nested: bool) -> Result, Error> - // Parse whitespace + marker first to capture base_marker for rest items + // Parse the marker and enter its scope before constructing principals. // marker_start captures position before marker for correct first item location - = whitespace()* marker_start:position!() base_marker:$(ordered_list_marker()) &whitespace() - parent_scope:enter_ordinary_list(offset, None, Some(base_marker)) - first:ordered_list_item_after_marker(offset, block_metadata, allow_continuation, base_marker, marker_start, parent_unordered_marker) - rest:(ordered_list_rest_item(offset, block_metadata, parent_unordered_marker, allow_continuation, base_marker))* + = prefix:ordered_list_prefix(offset) + first:ordered_list_item_after_marker(offset, block_metadata, allow_continuation, prefix.0, prefix.1, parent_unordered_marker) + rest:(ordered_list_rest_item(offset, block_metadata, parent_unordered_marker, allow_continuation, prefix.0))* { tracing::debug!("Found ordered list block"); - state.ordinary_list_scope = parent_scope; + state.ordinary_list_scope = prefix.2; let mut content = vec![first?]; for item in rest { content.push(item?); } let end = content.last().map_or(span_end, |(_, item_end)| *item_end); let items: Vec> = content.into_iter().map(|(item, _)| item).collect(); - let marker = items.first().map_or("", |item| item.marker); - Ok(Block::OrderedList(OrderedList { - title: if is_nested { Title::default() } else { block_metadata.title.clone() }, - metadata: if is_nested { BlockMetadata::default() } else { block_metadata.metadata.clone() }, - items, - marker, - location: state.create_location(start+offset, end+offset), - })) + Ok(build_ordinary_list(state, block_metadata, OrdinaryListLayout { start, end, offset, ordered: true, has_own_metadata: !is_nested }, items)) } // Parse first item content after marker has been consumed by ordered_list @@ -2254,20 +2454,17 @@ peg::parser! { item:ordered_list_item_with_continuation_after_marker(offset, block_metadata, marker, marker_start, parent_unordered_marker) { item } / item:ordered_list_item_no_continuation_after_marker(offset, block_metadata, marker, marker_start, parent_unordered_marker) { item } - rule ordered_list_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_unordered_marker: Option<&'input str>, allow_continuation: bool, base_marker: &str) -> Result<(ListItem<'input>, usize), Error> - // Mirror of `unordered_list_rest_item`'s front-guard structure. See that - // rule's comment for the rationale. - // - // Branch: parent is unordered - = parent_is_some(parent_unordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_ordered_marker(offset, base_marker) !at_unordered_marker_ahead() item:ordered_list_item(offset, block_metadata, allow_continuation, parent_unordered_marker) - { item } - / parent_is_some(parent_unordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_ordered_marker(offset, base_marker) !at_unordered_marker_ahead() item:ordered_list_item(offset, block_metadata, allow_continuation, parent_unordered_marker) - { item } + rule ordered_list_rest_prefix(offset: usize, parent_unordered_marker: Option<&'input str>, base_marker: &str) + = parent_is_some(parent_unordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_ordered_marker(offset, base_marker) !at_unordered_marker_ahead() + / parent_is_some(parent_unordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_ordered_marker(offset, base_marker) !at_unordered_marker_ahead() // Branch: no unordered parent - / parent_is_none(parent_unordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_ordered_marker(offset, base_marker) item:ordered_list_item(offset, block_metadata, allow_continuation, parent_unordered_marker) - { item } - / parent_is_none(parent_unordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_ordered_marker(offset, base_marker) item:ordered_list_item(offset, block_metadata, allow_continuation, parent_unordered_marker) - { item } + / parent_is_none(parent_unordered_marker) !at_list_separator() !eol() comment_line()* !at_enclosing_ordered_marker(offset, base_marker) + / parent_is_none(parent_unordered_marker) !at_list_separator() eol()+ comment_line()* !at_enclosing_ordered_marker(offset, base_marker) + + rule ordered_list_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_unordered_marker: Option<&'input str>, allow_continuation: bool, base_marker: &str) -> Result<(ListItem<'input>, usize), Error> + = ordered_list_rest_prefix(offset, parent_unordered_marker, base_marker) + item:ordered_list_item(offset, block_metadata, allow_continuation, parent_unordered_marker) { item } + // Note: The `*_with_continuation` and `*_no_continuation` variants exist because // PEG parsers are greedy - nested items must NOT consume explicit continuations @@ -2280,18 +2477,8 @@ peg::parser! { / item:unordered_list_item_no_continuation(offset, block_metadata, parent_ordered_marker) { item } rule unordered_list_item_with_continuation(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_ordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace()* - marker:unordered_list_marker() - whitespace() - checked:checklist_item()? - first_line_start:position!() - // Parse first line (principal text) - first_line:$((!(eol()) [_])*) - // Parse continuation lines that are part of the same paragraph - // Stop at: blank line, list item start, explicit continuation marker, or list separator - continuation_lines:unordered_list_principal_continuation(offset, marker, parent_ordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = item_start:position!() whitespace()* marker:unordered_list_marker() + head:unordered_list_head(offset, block_metadata, marker, item_start, item_start, parent_ordered_marker) // Try to parse nested list (ordered, or unordered with deeper markers) // Don't consume newlines if we're at a list separator (comment or []) // Nested items cannot consume parent-level continuations (allow_continuation: false) @@ -2312,10 +2499,6 @@ peg::parser! { list_dangling_continuation()? parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found unordered list item"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2323,31 +2506,15 @@ peg::parser! { } blocks.extend(explicit_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked, - location: state.create_location(span_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } // Version with immediate continuations only (for nested items) // Nested items consume continuations with 0 empty lines (immediate attachment). // Continuations with 1+ empty lines bubble up to ancestor items. rule unordered_list_item_no_continuation(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_ordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace()* - marker:unordered_list_marker() - whitespace() - checked:checklist_item()? - first_line_start:position!() - first_line:$((!(eol()) [_])*) - continuation_lines:unordered_list_principal_continuation(offset, marker, parent_ordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = item_start:position!() whitespace()* marker:unordered_list_marker() + head:unordered_list_head(offset, block_metadata, marker, item_start, item_start, parent_ordered_marker) // Nested items can still have nested lists, but those also cannot consume parent continuations // NOTE: nested_content is NOT optional here - if no nested content matches, the entire // alternative fails and backtracks, leaving eol() unconsumed for immediate_continuation @@ -2357,10 +2524,6 @@ peg::parser! { immediate_continuations:(!at_list_separator() cont:(list_explicit_continuation_immediate(offset, block_metadata, Some(ListMarker::Unordered(marker))) / unordered_list_nested_after_attachment(offset, block_metadata, marker, parent_ordered_marker)) { cont })* parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found unordered list item (immediate continuation only)"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2368,29 +2531,15 @@ peg::parser! { } blocks.extend(immediate_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked, - location: state.create_location(span_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } // After-marker variants: used when marker has already been consumed by parent rule // These are identical to the regular variants except they take marker as a parameter // instead of parsing it, and start after the marker position rule unordered_list_item_with_continuation_after_marker(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, marker_start: usize, parent_ordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace() - checked:checklist_item()? - first_line_start:position!() - first_line:$((!(eol()) [_])*) - continuation_lines:unordered_list_principal_continuation(offset, marker, parent_ordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = empty_start:position!() + head:unordered_list_head(offset, block_metadata, marker, marker_start, empty_start, parent_ordered_marker) nested:(!at_list_separator() nested_content:unordered_list_item_nested_after_principal(offset, block_metadata, marker, parent_ordered_marker) { nested_content })? explicit_continuations:(!at_list_separator() cont:( list_explicit_continuation_immediate(offset, block_metadata, Some(ListMarker::Unordered(marker))) @@ -2400,10 +2549,6 @@ peg::parser! { list_dangling_continuation()? parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found unordered list item (after marker)"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2411,34 +2556,16 @@ peg::parser! { } blocks.extend(explicit_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked, - location: state.create_location(marker_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } rule unordered_list_item_no_continuation_after_marker(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, marker_start: usize, parent_ordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace() - checked:checklist_item()? - first_line_start:position!() - first_line:$((!(eol()) [_])*) - continuation_lines:unordered_list_principal_continuation(offset, marker, parent_ordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = empty_start:position!() + head:unordered_list_head(offset, block_metadata, marker, marker_start, empty_start, parent_ordered_marker) nested:(!at_list_separator() nested_content:unordered_list_item_nested_after_principal(offset, block_metadata, marker, parent_ordered_marker) { nested_content })? immediate_continuations:(!at_list_separator() cont:(list_explicit_continuation_immediate(offset, block_metadata, Some(ListMarker::Unordered(marker))) / unordered_list_nested_after_attachment(offset, block_metadata, marker, parent_ordered_marker)) { cont })* parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found unordered list item (after marker, immediate only)"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2446,16 +2573,7 @@ peg::parser! { } blocks.extend(immediate_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked, - location: state.create_location(marker_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } /// Parse nested content within an unordered list item (e.g., nested ordered or unordered list) @@ -2464,57 +2582,27 @@ peg::parser! { /// parent_ordered_marker: the marker of an ancestor ordered list (if any), to prevent /// consuming sibling ordered markers that belong to a parent ordered list context rule unordered_list_item_nested_after_principal(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> Option, Error>> + = entry:unordered_child_after_principal(offset, block_metadata, current_marker, parent_ordered_marker) + list:native_list_entry(offset, &entry, block_metadata) { Some(list) } + + rule unordered_child_after_principal(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> ListEntry<'input> = eol() comment_line()* nested:( - unordered_list_item_nested_content_with_metadata(offset, block_metadata, current_marker, parent_ordered_marker) - / unordered_list_item_nested_content(offset, block_metadata, current_marker, parent_ordered_marker) + unordered_child_entry_with_metadata(offset, block_metadata, current_marker, parent_ordered_marker) + / unordered_child_entry(offset, block_metadata, current_marker, parent_ordered_marker) ) { nested } - / eol()+ !at_callout_list_item() nested:unordered_list_item_nested_content(offset, block_metadata, current_marker, parent_ordered_marker) { nested } + / eol()+ !at_callout_list_item() nested:unordered_child_entry(offset, block_metadata, current_marker, parent_ordered_marker) { nested } // A list after an item's attached blocks nests in the item, as it does // directly after the principal text. rule unordered_list_nested_after_attachment(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, parent_ordered_marker: Option<&'input str>) -> Result, Error> + = entry:unordered_child_after_attachment(offset, block_metadata, marker, parent_ordered_marker) + list:native_list_entry(offset, &entry, block_metadata) { list } + + rule unordered_child_after_attachment(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, parent_ordered_marker: Option<&'input str>) -> ListEntry<'input> = eol() &nested_unordered_child_after_metadata(offset, marker, parent_ordered_marker) - nested:unordered_list_item_nested_content_with_metadata(offset, block_metadata, marker, parent_ordered_marker) {? - nested.ok_or("no nested list after attached content") - } - / nested:unordered_list_item_nested_after_principal(offset, block_metadata, marker, parent_ordered_marker) {? - nested.ok_or("no nested list after attached content") - } + entry:unordered_child_entry_with_metadata(offset, block_metadata, marker, parent_ordered_marker) { entry } + / entry:unordered_child_after_principal(offset, block_metadata, marker, parent_ordered_marker) { entry } - rule unordered_list_item_nested_content_with_metadata(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> Option, Error>> - = nested_start:position!() - metadata:parsed_nested_list_metadata(offset, block_metadata.parent_section_level) - nested_list_metadata_gap()* - list:( - !at_open_ordered_marker(offset) - list:ordered_list(nested_start, offset, &metadata, Some(current_marker), false, false) { list } - / &at_nested_unordered_marker(offset, current_marker) - list:unordered_list_nested(nested_start, offset, &metadata, current_marker, parent_ordered_marker, true) { list } - / !at_callout_parent_item(offset) - list:callout_list(nested_start, offset, &metadata) { list } - / list:description_list(nested_start, offset, &metadata) { list } - ) - { - Some(list) - } - - rule unordered_list_item_nested_content(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> Option, Error>> - // !at_open_ordered_marker() prevents sibling ordered markers from a parent - // ordered list context from being consumed by this nested unordered item. - = !at_open_ordered_marker(offset) nested_start:position!() list:ordered_list(nested_start, offset, block_metadata, Some(current_marker), false, true) { - Some(list) - } - // Nested unordered list with deeper markers (e.g., ** inside *) - // Uses unordered_list_nested which only parses items deeper than current_marker - / &at_nested_unordered_marker(offset, current_marker) - nested_start:position!() - list:unordered_list_nested(nested_start, offset, block_metadata, current_marker, parent_ordered_marker, false) - { - Some(list) - } - / list:nested_callout_list(offset, block_metadata) { Some(list) } - / start:position!() metadata:nested_list_content_metadata(block_metadata) - list:description_list(start, offset, &metadata) { Some(list) } /// Parse a nested unordered list where all items have markers deeper than parent_marker. /// This is used to parse same-type nesting (e.g., ** inside *) as hierarchical content @@ -2523,49 +2611,40 @@ peg::parser! { rule unordered_list_nested(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: &str, parent_ordered_marker: Option<&'input str>, has_own_metadata: bool) -> Result, Error> // Parse first item - must have a deeper marker than parent_marker = &at_nested_unordered_marker(offset, parent_marker) - whitespace()* marker_start:position!() base_marker:$(unordered_list_marker()) &whitespace() - parent_scope:enter_ordinary_list(offset, Some(base_marker), None) - first:unordered_list_item_after_marker(offset, block_metadata, false, base_marker, marker_start, parent_ordered_marker) - // Parse rest items - only those at same level as base_marker (not deeper, not shallower than parent) - rest:(unordered_list_nested_rest_item(offset, block_metadata, parent_marker, base_marker, parent_ordered_marker))* + prefix:unordered_list_prefix(offset) + first:unordered_list_item_after_marker(offset, block_metadata, false, prefix.0, prefix.1, parent_ordered_marker) + // Parse rest items - only those at same level as prefix.0 (not deeper, not shallower than parent) + rest:(unordered_list_nested_rest_item(offset, block_metadata, parent_marker, prefix.0, parent_ordered_marker))* { tracing::debug!("Found nested unordered list block"); - state.ordinary_list_scope = parent_scope; + state.ordinary_list_scope = prefix.2; let mut content = vec![first?]; for item in rest { content.push(item?); } let end = content.last().map_or(span_end, |(_, item_end)| *item_end); let items: Vec> = content.into_iter().map(|(item, _)| item).collect(); - let marker = items.first().map_or("", |item| item.marker); - Ok(Block::UnorderedList(UnorderedList { - title: if has_own_metadata { block_metadata.title.clone() } else { Title::default() }, - metadata: if has_own_metadata { block_metadata.metadata.clone() } else { BlockMetadata::default() }, - items, - marker, - location: state.create_location(start+offset, end+offset), - })) + Ok(build_ordinary_list(state, block_metadata, OrdinaryListLayout { start, end, offset, ordered: false, has_own_metadata }, items)) } /// Parse rest items in a nested unordered list. - /// Items must be deeper than parent_marker and at same-or-deeper level as base_marker. - /// Stops when we encounter a marker at or shallower than parent_marker. - rule unordered_list_nested_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: &str, base_marker: &str, parent_ordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - // Case 1: No blank lines - accept same-level or deeper items + /// Matching an enclosing list marker ends this list. + rule unordered_list_nested_rest_prefix(offset: usize, parent_marker: &str, base_marker: &str) = !at_list_separator() !eol() comment_line()* - // Must not be at shallower-or-equal to parent (that would end the nested list) + // An item of an enclosing list ends this list. !at_enclosing_unordered_marker(offset, base_marker) - item:unordered_list_item(offset, block_metadata, false, parent_ordered_marker) - { item } // Case 2: Blank lines present - only accept same-level items (deeper would be its own nesting) / !at_list_separator() eol()+ comment_line()* - // Must not be at shallower-or-equal to parent + // An item of an enclosing list ends this list. !at_enclosing_unordered_marker(offset, base_marker) - // Must not be deeper than base (that would be nested inside this item) + // After blank lines, an unopened marker starts a separate list. !at_nested_unordered_marker(offset, base_marker) - item:unordered_list_item(offset, block_metadata, false, parent_ordered_marker) - { item } + + rule unordered_list_nested_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: &str, base_marker: &str, parent_ordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> + = unordered_list_nested_rest_prefix(offset, parent_marker, base_marker) + item:unordered_list_item(offset, block_metadata, false, parent_ordered_marker) { item } + // See comment on unordered_list_item for why *_with/without_continuation variants exist. @@ -2575,17 +2654,8 @@ peg::parser! { / item:ordered_list_item_no_continuation(offset, block_metadata, parent_unordered_marker) { item } rule ordered_list_item_with_continuation(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_unordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace()* - marker:ordered_list_marker() - whitespace() - first_line_start:position!() - // Parse first line (principal text) - first_line:$((!(eol()) [_])*) - // Parse continuation lines that are part of the same paragraph - // Stop at: blank line, list item start, explicit continuation marker, or list separator - continuation_lines:ordered_list_principal_continuation(offset, marker, parent_unordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = item_start:position!() whitespace()* marker:ordered_list_marker() + head:ordered_list_head(offset, block_metadata, marker, item_start, item_start, parent_unordered_marker) // Try to parse nested list (unordered, or ordered with deeper markers) // Don't consume newlines if we're at a list separator (comment or []) // Nested items cannot consume parent-level continuations (allow_continuation: false) @@ -2606,10 +2676,6 @@ peg::parser! { list_dangling_continuation()? parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found ordered list item"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2617,30 +2683,15 @@ peg::parser! { } blocks.extend(explicit_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked: None, - location: state.create_location(span_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } // Version with immediate continuations only (for nested items) // Nested items consume continuations with 0 empty lines (immediate attachment). // Continuations with 1+ empty lines bubble up to ancestor items. rule ordered_list_item_no_continuation(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_unordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace()* - marker:ordered_list_marker() - whitespace() - first_line_start:position!() - first_line:$((!(eol()) [_])*) - continuation_lines:ordered_list_principal_continuation(offset, marker, parent_unordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = item_start:position!() whitespace()* marker:ordered_list_marker() + head:ordered_list_head(offset, block_metadata, marker, item_start, item_start, parent_unordered_marker) // Nested items can still have nested lists, but those also cannot consume parent continuations // NOTE: nested_content is NOT optional here - if no nested content matches, the entire // alternative fails and backtracks, leaving eol() unconsumed for immediate_continuation @@ -2650,10 +2701,6 @@ peg::parser! { immediate_continuations:(!at_list_separator() cont:(list_explicit_continuation_immediate(offset, block_metadata, Some(ListMarker::Ordered(marker))) / ordered_list_nested_after_attachment(offset, block_metadata, marker, parent_unordered_marker)) { cont })* parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found ordered list item (immediate continuation only)"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2661,26 +2708,13 @@ peg::parser! { } blocks.extend(immediate_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked: None, - location: state.create_location(span_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } // After-marker variants for ordered lists: used when marker has already been consumed by parent rule rule ordered_list_item_with_continuation_after_marker(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, marker_start: usize, parent_unordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace() - first_line_start:position!() - first_line:$((!(eol()) [_])*) - continuation_lines:ordered_list_principal_continuation(offset, marker, parent_unordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = empty_start:position!() + head:ordered_list_head(offset, block_metadata, marker, marker_start, empty_start, parent_unordered_marker) nested:(!at_list_separator() nested_content:ordered_list_item_nested_after_principal(offset, block_metadata, marker, parent_unordered_marker) { nested_content })? explicit_continuations:(!at_list_separator() cont:( list_explicit_continuation_immediate(offset, block_metadata, Some(ListMarker::Ordered(marker))) @@ -2690,10 +2724,6 @@ peg::parser! { list_dangling_continuation()? parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found ordered list item (after marker)"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2701,33 +2731,16 @@ peg::parser! { } blocks.extend(explicit_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked: None, - location: state.create_location(marker_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } rule ordered_list_item_no_continuation_after_marker(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, marker_start: usize, parent_unordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - = whitespace() - first_line_start:position!() - first_line:$((!(eol()) [_])*) - continuation_lines:ordered_list_principal_continuation(offset, marker, parent_unordered_marker)* - first_line_end:position!() - principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) + = empty_start:position!() + head:ordered_list_head(offset, block_metadata, marker, marker_start, empty_start, parent_unordered_marker) nested:(!at_list_separator() nested_content:ordered_list_item_nested_after_principal(offset, block_metadata, marker, parent_unordered_marker) { nested_content })? immediate_continuations:(!at_list_separator() cont:(list_explicit_continuation_immediate(offset, block_metadata, Some(ListMarker::Ordered(marker))) / ordered_list_nested_after_attachment(offset, block_metadata, marker, parent_unordered_marker)) { cont })* parent_item_continuation(offset)? { - tracing::debug!(first_line_len = first_line.len(), continuation_count = continuation_lines.len(), "found ordered list item (after marker, immediate only)"); - let level = ListLevel::try_from(ListItem::parse_depth_from_marker(marker).unwrap_or(1))?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - let principal = principal?; let mut blocks = Vec::new(); if let Some(Some(Ok(nested_list))) = nested { @@ -2735,16 +2748,7 @@ peg::parser! { } blocks.extend(immediate_continuations.into_iter().flatten()); - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; - - Ok((ListItem { - principal, - blocks: order_block_prefix_events(blocks), - level, - marker, - checked: None, - location: state.create_location(marker_start+offset, actual_end+offset), - }, actual_end)) + head.finish(state, blocks, span_end, offset) } /// Parse nested content within an ordered list item (e.g., nested unordered or ordered list) @@ -2753,57 +2757,27 @@ peg::parser! { /// parent_unordered_marker: the marker of an ancestor unordered list (if any), to prevent /// consuming sibling unordered markers that belong to a parent unordered list context rule ordered_list_item_nested_after_principal(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> Option, Error>> + = entry:ordered_child_after_principal(offset, block_metadata, current_marker, parent_unordered_marker) + list:native_list_entry(offset, &entry, block_metadata) { Some(list) } + + rule ordered_child_after_principal(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> ListEntry<'input> = eol() comment_line()* nested:( - ordered_list_item_nested_content_with_metadata(offset, block_metadata, current_marker, parent_unordered_marker) - / ordered_list_item_nested_content(offset, block_metadata, current_marker, parent_unordered_marker) + ordered_child_entry_with_metadata(offset, block_metadata, current_marker, parent_unordered_marker) + / ordered_child_entry(offset, block_metadata, current_marker, parent_unordered_marker) ) { nested } - / eol()+ !at_callout_list_item() nested:ordered_list_item_nested_content(offset, block_metadata, current_marker, parent_unordered_marker) { nested } + / eol()+ !at_callout_list_item() nested:ordered_child_entry(offset, block_metadata, current_marker, parent_unordered_marker) { nested } // A list after an item's attached blocks nests in the item, as it does // directly after the principal text. rule ordered_list_nested_after_attachment(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, parent_unordered_marker: Option<&'input str>) -> Result, Error> - = eol() &nested_ordered_child_after_metadata(offset, marker, parent_unordered_marker) - nested:ordered_list_item_nested_content_with_metadata(offset, block_metadata, marker, parent_unordered_marker) {? - nested.ok_or("no nested list after attached content") - } - / nested:ordered_list_item_nested_after_principal(offset, block_metadata, marker, parent_unordered_marker) {? - nested.ok_or("no nested list after attached content") - } + = entry:ordered_child_after_attachment(offset, block_metadata, marker, parent_unordered_marker) + list:native_list_entry(offset, &entry, block_metadata) { list } - rule ordered_list_item_nested_content_with_metadata(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> Option, Error>> - = nested_start:position!() - metadata:parsed_nested_list_metadata(offset, block_metadata.parent_section_level) - nested_list_metadata_gap()* - list:( - !at_open_unordered_marker(offset) - list:unordered_list(nested_start, offset, &metadata, Some(current_marker), false, false) { list } - / &at_nested_ordered_marker(offset, current_marker) - list:ordered_list_nested(nested_start, offset, &metadata, current_marker, parent_unordered_marker, true) { list } - / !at_callout_parent_item(offset) - list:callout_list(nested_start, offset, &metadata) { list } - / list:description_list(nested_start, offset, &metadata) { list } - ) - { - Some(list) - } + rule ordered_child_after_attachment(offset: usize, block_metadata: &BlockParsingMetadata<'input>, marker: &'input str, parent_unordered_marker: Option<&'input str>) -> ListEntry<'input> + = eol() &nested_ordered_child_after_metadata(offset, marker, parent_unordered_marker) + entry:ordered_child_entry_with_metadata(offset, block_metadata, marker, parent_unordered_marker) { entry } + / entry:ordered_child_after_principal(offset, block_metadata, marker, parent_unordered_marker) { entry } - rule ordered_list_item_nested_content(offset: usize, block_metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> Option, Error>> - // !at_open_unordered_marker() prevents sibling unordered markers from a parent - // unordered list context from being consumed by this nested ordered item. - = !at_open_unordered_marker(offset) nested_start:position!() list:unordered_list(nested_start, offset, block_metadata, Some(current_marker), false, true) { - Some(list) - } - // Nested ordered list with deeper markers (e.g., .. inside .) - // Uses ordered_list_nested which only parses items deeper than current_marker - / &at_nested_ordered_marker(offset, current_marker) - nested_start:position!() - list:ordered_list_nested(nested_start, offset, block_metadata, current_marker, parent_unordered_marker, false) - { - Some(list) - } - / list:nested_callout_list(offset, block_metadata) { Some(list) } - / start:position!() metadata:nested_list_content_metadata(block_metadata) - list:description_list(start, offset, &metadata) { Some(list) } /// Parse a nested ordered list where all items have markers deeper than parent_marker. /// This is used to parse same-type nesting (e.g., .. inside .) as hierarchical content @@ -2812,49 +2786,40 @@ peg::parser! { rule ordered_list_nested(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: &str, parent_unordered_marker: Option<&'input str>, has_own_metadata: bool) -> Result, Error> // Parse first item - must have a deeper marker than parent_marker = &at_nested_ordered_marker(offset, parent_marker) - whitespace()* marker_start:position!() base_marker:$(ordered_list_marker()) &whitespace() - parent_scope:enter_ordinary_list(offset, None, Some(base_marker)) - first:ordered_list_item_after_marker(offset, block_metadata, false, base_marker, marker_start, parent_unordered_marker) - // Parse rest items - only those at same level as base_marker (not deeper, not shallower than parent) - rest:(ordered_list_nested_rest_item(offset, block_metadata, parent_marker, base_marker, parent_unordered_marker))* + prefix:ordered_list_prefix(offset) + first:ordered_list_item_after_marker(offset, block_metadata, false, prefix.0, prefix.1, parent_unordered_marker) + // Parse rest items - only those at same level as prefix.0 (not deeper, not shallower than parent) + rest:(ordered_list_nested_rest_item(offset, block_metadata, parent_marker, prefix.0, parent_unordered_marker))* { tracing::debug!("Found nested ordered list block"); - state.ordinary_list_scope = parent_scope; + state.ordinary_list_scope = prefix.2; let mut content = vec![first?]; for item in rest { content.push(item?); } let end = content.last().map_or(span_end, |(_, item_end)| *item_end); let items: Vec> = content.into_iter().map(|(item, _)| item).collect(); - let marker = items.first().map_or("", |item| item.marker); - Ok(Block::OrderedList(OrderedList { - title: if has_own_metadata { block_metadata.title.clone() } else { Title::default() }, - metadata: if has_own_metadata { block_metadata.metadata.clone() } else { BlockMetadata::default() }, - items, - marker, - location: state.create_location(start+offset, end+offset), - })) + Ok(build_ordinary_list(state, block_metadata, OrdinaryListLayout { start, end, offset, ordered: true, has_own_metadata }, items)) } /// Parse rest items in a nested ordered list. - /// Items must be deeper than parent_marker and at same-or-deeper level as base_marker. - /// Stops when we encounter a marker at or shallower than parent_marker. - rule ordered_list_nested_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: &str, base_marker: &str, parent_unordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> - // Case 1: No blank lines - accept same-level or deeper items + /// Matching an enclosing list marker ends this list. + rule ordered_list_nested_rest_prefix(offset: usize, parent_marker: &str, base_marker: &str) = !at_list_separator() !eol() comment_line()* - // Must not be at shallower-or-equal to parent (that would end the nested list) + // An item of an enclosing list ends this list. !at_enclosing_ordered_marker(offset, base_marker) - item:ordered_list_item(offset, block_metadata, false, parent_unordered_marker) - { item } // Case 2: Blank lines present - only accept same-level items (deeper would be its own nesting) / !at_list_separator() eol()+ comment_line()* - // Must not be at shallower-or-equal to parent + // An item of an enclosing list ends this list. !at_enclosing_ordered_marker(offset, base_marker) - // Must not be deeper than base (that would be nested inside this item) + // After blank lines, an unopened marker starts a separate list. !at_nested_ordered_marker(offset, base_marker) - item:ordered_list_item(offset, block_metadata, false, parent_unordered_marker) - { item } + + rule ordered_list_nested_rest_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: &str, base_marker: &str, parent_unordered_marker: Option<&'input str>) -> Result<(ListItem<'input>, usize), Error> + = ordered_list_nested_rest_prefix(offset, parent_marker, base_marker) + item:ordered_list_item(offset, block_metadata, false, parent_unordered_marker) { item } + // Only a column-one marker with nonempty text starts a callout item. @@ -2873,7 +2838,7 @@ peg::parser! { // Save the enclosing scope for callout_list to restore after parsing its // items. Keep pending verbatim references local for validation, // since child listings add their own references to the shared catalog. - rule enter_callout_list(offset: usize) -> (Option, Vec) + rule enter_callout_list(offset: usize) -> CalloutScope = { let parent = state.callout_list_offset.replace(offset); (parent, std::mem::take(&mut state.pending_callouts)) @@ -2896,47 +2861,7 @@ peg::parser! { } let end = content.last().map_or(span_end, |(_, _, item_end)| *item_end); - let mut auto_number = 0; - let mut items: Vec = Vec::with_capacity(content.len()); - - for (expected_number, (mut item, marker, _end)) in (1..).zip(content) { - let actual_number = if marker == "<.>" { - auto_number += 1; - auto_number.to_string() - } else { - marker.trim_start_matches('<').trim_end_matches('>').to_string() - }; - if actual_number != expected_number.to_string() { - state.add_generic_warning_at( - format!( - "callout list item index: expected {expected_number}, got {actual_number}" - ), - item.location.clone(), - ); - } - // List labels use their ordinal even when the source marker is - // invalid or mixes explicit and automatic numbering. - item.callout.number = expected_number; - - // Check if the EXPECTED callout exists in the verbatim block - // (This warns when sequence is broken and the expected number is missing) - let callout_exists = callouts.iter() - .any(|c| c.number == expected_number); - if !callout_exists { - state.add_generic_warning_at( - format!("no callout found for <{expected_number}>"), - item.location.clone(), - ); - } - items.push(item); - } - - Ok(Block::CalloutList(CalloutList { - title: block_metadata.title.clone(), - metadata: block_metadata.metadata.clone(), - items, - location: state.create_location(start+offset, end+offset), - })) + Ok(build_callout_list(state, block_metadata, state.create_location(start+offset, end+offset), content, &callouts)) } // A dropped `+` before this item leaves no line break to consume. @@ -2966,16 +2891,29 @@ peg::parser! { // blocks. Metadata must be adjacent to the principal text; a blank line // before metadata starts a separate list. rule callout_list_nested(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = entry:callout_child_after_principal(offset, block_metadata) + list:native_list_entry(offset, &entry, block_metadata) { list } + + rule callout_child_after_principal(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> ListEntry<'input> = eol() child:( &((attribute_or_anchor_line_match() eol()*)+ callout_child_marker(offset)) start:position!() metadata:parsed_nested_list_metadata(offset, block_metadata.parent_section_level) - list:callout_child_list(start, offset, &metadata) { list } + kind:callout_child_kind(offset) body_offset:position!() + { ListEntry { start, body_offset, metadata: Some(metadata), kind } } / eol()* callout_child_marker(offset) start:position!() metadata:nested_list_content_metadata(block_metadata) - list:callout_child_list(start, offset, &metadata) { list } + kind:callout_child_kind(offset) body_offset:position!() + { ListEntry { start, body_offset, metadata: Some(metadata), kind } } ) { child } + rule callout_child_kind(offset: usize) -> ListKind<'input> + = &(whitespace()* unordered_list_marker() whitespace()) + { ListKind::Unordered(OrdinaryListKind { parent_other: None, parent_same: None, allow_continuation: false, has_own_metadata: true }) } + / &(whitespace()* ordered_list_marker() whitespace()) + { ListKind::Ordered(OrdinaryListKind { parent_other: None, parent_same: None, allow_continuation: false, has_own_metadata: true }) } + / &description_list_ahead(offset) { ListKind::Description } + // Inherit section context and text settings without copying the parent's // ID, title, or style onto a child that has no metadata of its own. rule nested_list_content_metadata(parent: &BlockParsingMetadata<'input>) -> BlockParsingMetadata<'input> @@ -2988,17 +2926,23 @@ peg::parser! { } } - // Disable child continuations so `+` blocks remain for the owning callout item. - rule callout_child_list(start: usize, offset: usize, metadata: &BlockParsingMetadata<'input>) -> Result, Error> - = unordered_list(start, offset, metadata, None, false, false) - / ordered_list(start, offset, metadata, None, false, false) - / description_list(start, offset, metadata) + rule callout_list_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = head:callout_list_head(offset, block_metadata) + nested:(!at_list_separator() child:callout_list_nested(offset, block_metadata) { child })? + explicit_continuations:(!at_list_separator() cont:( + list_explicit_continuation_immediate(offset, block_metadata, None) + / list_explicit_continuation_ancestor(offset, block_metadata, None) + ) { cont })* + list_dangling_continuation()? + parent_item_continuation(offset)? + { + let blocks = nested.into_iter().chain(explicit_continuations).collect(); + head.finish(state, blocks, span_end, offset) + } - rule callout_list_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result<(CalloutListItem<'input>, String, usize), Error> + rule callout_list_head(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> CalloutItemHead<'input> = at_callout_list_item() - marker_start:position!() marker:callout_list_marker() - marker_end:position!() whitespace() first_line_start:position!() // Parse first line (principal text) @@ -3015,41 +2959,40 @@ peg::parser! { )* first_line_end:position!() principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) - nested:(!at_list_separator() child:callout_list_nested(offset, block_metadata) { child })? - explicit_continuations:(!at_list_separator() cont:( - list_explicit_continuation_immediate(offset, block_metadata, None) - / list_explicit_continuation_ancestor(offset, block_metadata, None) - ) { cont })* - list_dangling_continuation()? - parent_item_continuation(offset)? { - let principal = principal?; - let item_end = calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end); - - let blocks = nested - .into_iter() - .chain(explicit_continuations) - .collect::, _>>()?; - - // The marker's location covers `` only; the principal has its own. - let location = state.create_location(marker_start+offset, marker_end.saturating_sub(1)+offset); - - // Create a placeholder callout - will be resolved in callout_list - // We pass the marker string to the parent rule for resolution - let callout = if marker == "<.>" { - CalloutMarker::auto(0, location) // Number will be resolved later - } else { - CalloutMarker::explicit(0, location) - }; + CalloutItemHead { + principal, marker, start: span_start, + end: calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), span_start, first_line_end), + } + } - let actual_end = if blocks.is_empty() { item_end } else { span_end.saturating_sub(1) }; + rule unordered_list_head(offset: usize, metadata: &BlockParsingMetadata<'input>, marker: &'input str, item_start: usize, empty_start: usize, parent_ordered_marker: Option<&'input str>) -> ListItemHead<'input> + = whitespace() + checked:checklist_item()? + first_line_start:position!() + first_line:$((!eol() [_])*) + continuation_lines:unordered_list_principal_continuation(offset, marker, parent_ordered_marker)* + first_line_end:position!() + principal:list_item_principal(offset, metadata, first_line_start, first_line_end, first_line, &continuation_lines) + { + ListItemHead { + principal, marker, checked, start: item_start, + end: calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), empty_start, first_line_end), + } + } - Ok((CalloutListItem { - callout, - principal, - blocks: order_block_prefix_events(blocks), - location: state.create_location(span_start+offset, actual_end+offset), - }, marker.to_string(), actual_end)) + rule ordered_list_head(offset: usize, metadata: &BlockParsingMetadata<'input>, marker: &'input str, item_start: usize, empty_start: usize, parent_unordered_marker: Option<&'input str>) -> ListItemHead<'input> + = whitespace() + first_line_start:position!() + first_line:$((!eol() [_])*) + continuation_lines:ordered_list_principal_continuation(offset, marker, parent_unordered_marker)* + first_line_end:position!() + principal:list_item_principal(offset, metadata, first_line_start, first_line_end, first_line, &continuation_lines) + { + ListItemHead { + principal, marker, checked: None, start: item_start, + end: calculate_item_end(first_line.is_empty() && continuation_lines.is_empty(), empty_start, first_line_end), + } } // Run before child parsing to register footnotes in source order; @@ -3124,19 +3067,14 @@ peg::parser! { loc_end - offset }); - Ok(Block::DescriptionList(DescriptionList { - title: block_metadata.title.clone(), - metadata: block_metadata.metadata.clone(), - items: build_description_list_topology(items), - location: state.create_location(start+offset, actual_end+offset), - })) + Ok(build_description_list(block_metadata, state.create_location(start+offset, actual_end+offset), items)) } // Parse additional description list items (after potential auto-attached content) // // !at_dlist_block_boundary() prevents continuing the list when a blank line is // followed by block attributes. This allows attributes to apply to a new list. - rule description_list_additional_items(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_scope: Option>) -> Result, Error> + rule description_list_additional_prefix(offset: usize, parent_scope: Option>) = !at_dlist_block_boundary() eol()* !at_description_scope_item(offset, parent_scope) @@ -3144,11 +3082,10 @@ peg::parser! { !at_callout_list_item() !at_list_item_start() check_line_is_description_list(offset) - item:description_list_item(offset, block_metadata) - { - tracing::debug!("Found additional description list item"); - item - } + + rule description_list_additional_items(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_scope: Option>) -> Result, Error> + = description_list_additional_prefix(offset, parent_scope) + item:description_list_item(offset, block_metadata) { item } // A missing principal can start after blank lines, with the same list boundaries. rule description_list_principal_line(offset: usize) @@ -3169,12 +3106,15 @@ peg::parser! { !markdown_code_delimiter() !attribute_or_anchor_line_match() - rule description_list_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule description_list_term_source() -> DescriptionTermSource<'input> = term_start:position!() - term:$((!(description_list_marker() (eol() / " " / ![_]) / eol()) [_])+) - term_end:position!() - delim_start:position!() delimiter:description_list_marker() delim_end:position!() - select_description_marker(delimiter) + term:$((!(description_list_marker() (eol() / " " / ![_]) / eol()) [_])+) + term_end:position!() + delim_start:position!() delimiter:description_list_marker() delim_end:position!() + { DescriptionTermSource { raw: term, start: term_start, end: term_end, delimiter_start: delim_start, delimiter_end: delim_end, delimiter } } + + rule description_list_head(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> DescriptionItemHead<'input> + = term:description_list_term_source() select_description_marker(term.delimiter) whitespace()* principal_start:position!() principal_content:$( @@ -3188,72 +3128,17 @@ peg::parser! { (!eol() [_])+ // continuation line content )* ) - principal:description_list_principal(offset, block_metadata, term, term_start, term_end, principal_content, principal_start) - // Now handle auto-attachment and explicit continuation - attached_content:description_list_attached_content(offset, block_metadata, delimiter)* - parent_item_continuation(offset)? + principal:description_list_principal(offset, block_metadata, term.raw, term.start, term.end, principal_content, principal_start) { - tracing::debug!("parsing description list item with auto-attachment"); - - let (term, principal_text) = principal?; - - // Collect all attached blocks (auto-attached and explicitly continued) - let mut description = Vec::with_capacity(attached_content.len()); - for content in attached_content { - match content { - Ok(blocks) => description.extend(blocks), - Err(e) => { - state.add_warning(Warning::new( - WarningKind::ContentRecovery { - message: format!("discarded attached content: {e}").into(), - }, - e.source_location().cloned(), - )); - tracing::error!("Error processing attached content"); - } - } - } - - let principal_end = principal_start + principal_content.trim_end().len(); - let actual_end = description.last().map_or_else( - || state.create_block_location(term_start, principal_end.max(delim_end), offset).absolute_end - offset, - |block| block.location().absolute_end - offset, - ); - - let delimiter_location = state.create_block_location(delim_start, delim_end, offset); - let term = DescriptionListTerm { - anchors: Vec::new(), - content: term, - delimiter, - delimiter_location: Some(delimiter_location), - location: state.create_block_location(term_start, delim_end, offset), - }; - let principal = (!principal_content.trim().is_empty()).then_some(principal_text); - let blocks = order_block_prefix_events(description); - let definition = if principal.is_some() || !blocks.is_empty() { - let location = if principal.is_some() { - let start = principal_start + principal_content.len() - principal_content.trim_start().len(); - state.create_location(start + offset, actual_end + offset) - } else { - let mut location = blocks.first().map_or_else(Location::default, |block| block.location().clone()); - if let Some(last) = blocks.last() { - location.absolute_end = last.location().absolute_end; - location.end = last.location().end.clone(); - } - location - }; - Some(DescriptionListDefinition { principal, blocks, location }) - } else { - None - }; - let mut location = state.create_location(span_start + offset, actual_end + offset); - if definition.is_none() { - location.absolute_end = term.location.absolute_end; - location.end = term.location.end.clone(); - } - Ok(DescriptionListItem { terms: vec![term], definition, location }) + DescriptionItemHead { source: DescriptionItemSource { term, principal_content, principal_start }, principal } } + rule description_list_item(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = head:description_list_head(offset, block_metadata) + attached:description_list_attached_content(offset, block_metadata, head.source.term.delimiter)* + parent_item_continuation(offset)? + { head.finish(state, attached, offset) } + // As with list_item_principal, process parent macros before attachments. rule description_list_principal(offset: usize, block_metadata: &BlockParsingMetadata<'input>, term: &'input str, term_start: usize, term_end: usize, principal_content: &'input str, principal_start: usize) -> Result<(Vec>, Vec>), Error> = { @@ -3303,34 +3188,39 @@ peg::parser! { } rule description_list_auto_attached_list(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result>, Error> - = eol()* list:description_list_auto_attached_list_with_metadata(offset, block_metadata) { list } - / eol()* !at_ordinary_parent_item(offset) - list_start:position!() - list:description_list_ordinary_child(list_start, offset, block_metadata, false) { Ok(vec![list?]) } - / list:nested_callout_list(offset, block_metadata) { Ok(vec![list?]) } - - // Preserve both ordinary ancestors while parsing a description's child list. - rule description_list_ordinary_child(start: usize, offset: usize, metadata: &BlockParsingMetadata<'input>, has_own_metadata: bool) -> Result, Error> - = scope:ordinary_list_scope(offset) list:( - parent_is_some(scope.unordered) - list:unordered_list_nested(start, offset, metadata, scope.unordered.unwrap_or_default(), scope.ordered, has_own_metadata) { list } - / parent_is_none(scope.unordered) - list:unordered_list(start, offset, metadata, scope.ordered, true, !has_own_metadata) { list } - / parent_is_some(scope.ordered) - list:ordered_list_nested(start, offset, metadata, scope.ordered.unwrap_or_default(), scope.unordered, has_own_metadata) { list } - / parent_is_none(scope.ordered) - list:ordered_list(start, offset, metadata, scope.unordered, true, !has_own_metadata) { list } - ) { list } - - // Metadata belongs to a nested list only when a child marker follows it. - rule description_list_auto_attached_list_with_metadata(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result>, Error> + = entry:description_auto_entry(offset, block_metadata) + list:native_list_entry(offset, &entry, block_metadata) { Ok(vec![list?]) } + + rule description_auto_entry(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> ListEntry<'input> + = eol()* entry:description_auto_entry_with_metadata(offset, block_metadata) { entry } + / eol()* !at_ordinary_parent_item(offset) start:position!() + kind:description_ordinary_child_kind(offset, false) body_offset:position!() + { ListEntry { start, body_offset, metadata: None, kind } } + / !at_callout_parent_item(offset) &at_callout_list_item() start:position!() + metadata:nested_list_content_metadata(block_metadata) + { ListEntry { start, body_offset: start, metadata: Some(metadata), kind: ListKind::Callout } } + + rule description_ordinary_child_kind(offset: usize, own: bool) -> ListKind<'input> + = scope:ordinary_list_scope(offset) kind:( + parent_is_some(scope.unordered) &at_nested_unordered_marker(offset, scope.unordered.unwrap_or_default()) + { ListKind::Unordered(OrdinaryListKind { parent_other: scope.ordered, parent_same: scope.unordered, allow_continuation: false, has_own_metadata: own }) } + / parent_is_none(scope.unordered) &(whitespace()* unordered_list_marker() whitespace()) + { ListKind::Unordered(OrdinaryListKind { parent_other: scope.ordered, parent_same: None, allow_continuation: true, has_own_metadata: own }) } + / parent_is_some(scope.ordered) &at_nested_ordered_marker(offset, scope.ordered.unwrap_or_default()) + { ListKind::Ordered(OrdinaryListKind { parent_other: scope.unordered, parent_same: scope.ordered, allow_continuation: false, has_own_metadata: own }) } + / parent_is_none(scope.ordered) &(whitespace()* ordered_list_marker() whitespace()) + { ListKind::Ordered(OrdinaryListKind { parent_other: scope.unordered, parent_same: None, allow_continuation: true, has_own_metadata: own }) } + ) { kind } + + rule description_auto_entry_with_metadata(offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> ListEntry<'input> = &((attribute_or_anchor_line_match() eol()*)+ !at_ordinary_parent_item(offset) (at_list_item_start() / !at_callout_parent_item(offset) at_callout_list_item())) - list_start:position!() - metadata:parsed_nested_list_metadata(offset, block_metadata.parent_section_level) - list:(callout_list(list_start, offset, &metadata) - / description_list_ordinary_child(list_start, offset, &metadata, true)) - { Ok(vec![list?]) } + start:position!() metadata:parsed_nested_list_metadata(offset, block_metadata.parent_section_level) + kind:( + &at_callout_list_item() structural_block_boundaries(&metadata) { ListKind::Callout } + / kind:description_ordinary_child_kind(offset, true) { kind } + ) body_offset:position!() + { ListEntry { start, body_offset, metadata: Some(metadata), kind } } // A blank line before `+` returns from a nested description to its ordinary parent. rule description_continuation_gap(offset: usize) @@ -3339,13 +3229,16 @@ peg::parser! { .then_some(()).ok_or("continuation belongs to ordinary parent") } + rule description_continuation_prefix(offset: usize) + = description_continuation_gap(offset) "+" eol() !at_open_list_item_after_metadata(offset) + // Parse one or more explicit continuations for description lists // Same pattern as list_explicit_continuation: + marker followed by a single block // Uses block_in_continuation to prevent lists inside continuations from consuming // further continuations that belong to the parent item rule description_list_explicit_continuation(offset: usize, block_metadata: &BlockParsingMetadata<'input>, delimiter: &'input str) -> Result>, Error> = continuations:( - description_continuation_gap(offset) "+" eol() !at_open_list_item_after_metadata(offset) + description_continuation_prefix(offset) block:block_in_continuation(offset, block_metadata.parent_section_level, Some(ListMarker::Description(delimiter))) { block } )+ @@ -3360,7 +3253,7 @@ peg::parser! { // further continuations that belong to the parent item. // Pattern: exactly one newline before + (content\n+\nblock) rule list_explicit_continuation_immediate(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: Option>) -> Result, Error> - = eol() !eol() "+" eol() !at_open_list_item_after_metadata(offset) + = list_continuation_immediate_prefix(offset) block:block_in_continuation(offset, block_metadata.parent_section_level, parent_marker) { tracing::debug!("List immediate continuation block (0 empty lines)"); @@ -3374,13 +3267,19 @@ peg::parser! { // further continuations that belong to the parent item. // Pattern: two or more newlines before + (content\n\n+\nblock) rule list_explicit_continuation_ancestor(offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: Option>) -> Result, Error> - = eol() eol()+ "+" eol() !at_open_list_item_after_metadata(offset) + = list_continuation_ancestor_prefix(offset) block:block_in_continuation(offset, block_metadata.parent_section_level, parent_marker) { tracing::debug!("List ancestor continuation block (1+ empty lines)"); block } + rule list_continuation_immediate_prefix(offset: usize) + = eol() !eol() "+" eol() !at_open_list_item_after_metadata(offset) + + rule list_continuation_ancestor_prefix(offset: usize) + = eol() eol()+ "+" eol() !at_open_list_item_after_metadata(offset) + // Asciidoctor drops a `+` that comes before an item of an open list, // together with any block metadata between them, and the list continues // with that item. Comments without metadata stay attached as comment nodes. @@ -3417,153 +3316,26 @@ peg::parser! { // -- Thomas Jefferson, Papers of Thomas Jefferson // ``` rule quoted_paragraph(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = params:quoted_paragraph_params(start, offset) { build_quote(state, block_metadata, ¶ms) } + + rule quoted_paragraph_params(start: usize, offset: usize) -> QuoteParams<'input> = content_start:position!() - "\"" quoted_content:$((!"\"" [_])+) "\"" - eol() + "\"" content:$((!"\"" [_])+) "\"" eol() "-- " attr_start:position!() attribution_line:$([^'\n']+) { - tracing::debug!("found quoted paragraph"); - - // Parse attribution line: "Author Name, Source Title" or just "Author Name" - // Intern the slices into the parser arena so downstream inline parsing - // can produce nodes with the `'input` lifetime. - let (attr_str, cite_str): (&'input str, Option<&'input str>) = match attribution_line.split_once(',') { - Some((attr, cite)) => (state.intern_str(attr.trim()), Some(state.intern_str(cite.trim()))), - None => (state.intern_str(attribution_line.trim()), None), - }; - - let attr_end_offset = attr_start + attr_str.len(); - let (attr_inlines, _) = process_inlines( - state, - block_metadata, - attr_start, - attr_end_offset, - offset, - attr_str, - )?; - - let cite_inlines = if let Some(cite) = cite_str { - let cite_offset_in_line = attribution_line.find(',').unwrap_or(0) + 1; - let cite_raw_start = attr_start + cite_offset_in_line + (attribution_line[cite_offset_in_line..].len() - attribution_line[cite_offset_in_line..].trim_start().len()); - let cite_pos = PositionWithOffset { - offset: cite_raw_start, - position: state.line_map.offset_to_position(cite_raw_start, state.input), - }; - let (cite_inlines, _) = process_inlines( - state, - block_metadata, - cite_pos.offset, - cite_raw_start + cite.len(), - offset, - cite, - )?; - Some(cite_inlines) - } else { - None - }; - - let blocks = document_parser::blocks(quoted_content, state, content_start + offset, block_metadata.parent_section_level, None).unwrap_or_else(|e| { - adjust_and_log_parse_error(&e, quoted_content, content_start + offset, state, "Error parsing content as blocks in quoted paragraph"); - Ok(Vec::new()) - })?; - - let mut metadata = block_metadata.metadata.clone(); - metadata.style = Some("quote"); - metadata.attribution = Some(Attribution::new(attr_inlines)); - if let Some(inlines) = cite_inlines { - metadata.citetitle = Some(CiteTitle::new(inlines)); + QuoteParams { + start, end: span_end, offset, + source: QuoteSource::Shorthand { content, content_start }, + attribution: Some(QuoteAttribution::from_line(attribution_line, attr_start)), } - - Ok(Block::DelimitedBlock(DelimitedBlock { - source_text: None, - metadata, - delimiter: "\"", - inner: DelimitedBlockType::DelimitedQuote(blocks), - title: block_metadata.title.clone(), - location: state.create_block_location(start, span_end, offset), - open_delimiter_location: None, - close_delimiter_location: None, - })) } - /// Parse a markdown-style blockquote: lines starting with `> ` - /// - /// This matches the Markdown-compatible syntax for blockquotes: - /// ``` - /// > I hold it that a little rebellion now and then is a good thing, - /// > and as necessary in the political world as storms in the physical. - /// > -- Thomas Jefferson, Papers of Thomas Jefferson: Volume 11 - /// ``` - /// - /// The content after `> ` on each line is joined and parsed as blocks. - /// Attribution is extracted from a line matching `> -- Author[, Citation]`. rule markdown_blockquote(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> - = lines:markdown_blockquote_content_line()+ attribution:markdown_blockquote_attribution()? - { - tracing::debug!("found markdown blockquote"); + = params:markdown_blockquote_params(start, offset) { build_quote(state, block_metadata, ¶ms) } - let content: &'input str = state.intern_join(lines.iter(), "\n"); - let content_start = start; - - let mut metadata = block_metadata.metadata.clone(); - metadata.style = Some("quote"); - if let Some((author, author_start, citation)) = attribution { - let author: &'input str = state.intern_str(&author); - let author_pos = PositionWithOffset { - offset: author_start, - position: state.line_map.offset_to_position(author_start, state.input), - }; - let attr_end_offset = author_start + author.len(); - let (attr_inlines, _) = process_inlines( - state, - block_metadata, - author_pos.offset, - attr_end_offset, - offset, - author, - )?; - metadata.attribution = Some(Attribution::new(attr_inlines)); - - if let Some((cite, cite_start)) = citation { - let cite: &'input str = state.intern_str(&cite); - let cite_pos = PositionWithOffset { - offset: cite_start, - position: state.line_map.offset_to_position(cite_start, state.input), - }; - let (cite_inlines, _) = process_inlines( - state, - block_metadata, - cite_pos.offset, - cite_start + cite.len(), - offset, - cite, - )?; - metadata.citetitle = Some(CiteTitle::new(cite_inlines)); - } - } - - let location = state.create_block_location(start, span_end, offset); - - let blocks = if content.trim().is_empty() { - Vec::new() - } else { - document_parser::blocks(content, state, content_start + offset, block_metadata.parent_section_level, None).unwrap_or_else(|e| { - adjust_and_log_parse_error(&e, content, content_start + offset, state, "Error parsing content as blocks in markdown blockquote"); - Ok(Vec::new()) - })? - }; - - Ok(Block::DelimitedBlock(DelimitedBlock { - source_text: None, - metadata, - delimiter: ">", - inner: DelimitedBlockType::DelimitedQuote(blocks), - title: block_metadata.title.clone(), - location, - open_delimiter_location: None, - close_delimiter_location: None, - })) - } + rule markdown_blockquote_params(start: usize, offset: usize) -> QuoteParams<'input> + = lines:markdown_blockquote_content_line()+ attribution:markdown_blockquote_attribution()? + { QuoteParams { start, end: span_end, offset, source: QuoteSource::Markdown(lines), attribution } } /// Match a content line of a markdown-style blockquote /// A line is content if: @@ -3579,12 +3351,12 @@ peg::parser! { /// Match an attribution line: `> -- Author[, Citation]` /// Only matches at the END of a blockquote (not followed by more `>` lines) /// Returns (author, author_start, Option<(citation, cite_start)>) - rule markdown_blockquote_attribution() -> (String, usize, Option<(String, usize)>) + rule markdown_blockquote_attribution() -> QuoteAttribution<'input> = "> -- " author_start:position!() author:$([^(',' | '\n')]+) ", " cite_start:position!() citation:$([^'\n']+) ((eol() !">") / ![_]) { - (author.trim().to_string(), author_start, Some((citation.trim().to_string(), cite_start))) + QuoteAttribution { author: author.trim(), author_start, citation: Some((citation.trim(), cite_start)) } } / "> -- " author_start:position!() author:$([^'\n']+) ((eol() !">") / ![_]) { - (author.trim().to_string(), author_start, None) + QuoteAttribution { author: author.trim(), author_start, citation: None } } // Asciidoctor lets verbatim styles override list and macro syntax. diff --git a/acdc-parser/src/grammar/document/quotes.rs b/acdc-parser/src/grammar/document/quotes.rs new file mode 100644 index 000000000..bc90402c8 --- /dev/null +++ b/acdc-parser/src/grammar/document/quotes.rs @@ -0,0 +1,130 @@ +//! Shared builders for shorthand and Markdown blockquotes. + +use crate::{ + Attribution, Block, CiteTitle, DelimitedBlock, DelimitedBlockType, Error, + grammar::{ParserState, helpers::BlockParsingMetadata, inline_processing::process_inlines}, +}; + +use super::delimited::{ContentKind, ContentParser, ContentRequest, GrammarContent, parse_content}; + +pub(super) struct QuoteAttribution<'a> { + pub(super) author: &'a str, + pub(super) author_start: usize, + pub(super) citation: Option<(&'a str, usize)>, +} + +impl<'a> QuoteAttribution<'a> { + pub(super) fn from_line(source: &'a str, start: usize) -> Self { + let (author, citation) = + source + .split_once(',') + .map_or((source.trim(), None), |(author, tail)| { + let citation_start = + start + author.len() + 1 + tail.len() - tail.trim_start().len(); + (author.trim(), Some((tail.trim(), citation_start))) + }); + Self { + author, + author_start: start, + citation, + } + } +} + +pub(super) enum QuoteSource<'a> { + Shorthand { + content: &'a str, + content_start: usize, + }, + Markdown(Vec<&'a str>), +} + +pub(super) struct QuoteParams<'a> { + pub(super) start: usize, + pub(super) end: usize, + pub(super) offset: usize, + pub(super) source: QuoteSource<'a>, + pub(super) attribution: Option>, +} + +pub(super) fn build_quote<'a>( + state: &mut ParserState<'a>, + metadata: &BlockParsingMetadata<'a>, + params: &QuoteParams<'a>, +) -> Result, Error> { + build_quote_with_parser(state, metadata, params, &mut GrammarContent) +} + +pub(super) fn build_quote_with_parser<'a>( + state: &mut ParserState<'a>, + block_metadata: &BlockParsingMetadata<'a>, + params: &QuoteParams<'a>, + parser: &mut impl ContentParser<'a>, +) -> Result, Error> { + let mut metadata = block_metadata.metadata.clone(); + metadata.style = Some("quote"); + if let Some(attribution) = ¶ms.attribution { + let (author, _) = process_inlines( + state, + block_metadata, + attribution.author_start, + attribution.author_start + attribution.author.len(), + params.offset, + attribution.author, + )?; + metadata.attribution = Some(Attribution::new(author)); + if let Some((citation, start)) = attribution.citation { + let (citation, _) = process_inlines( + state, + block_metadata, + start, + start + citation.len(), + params.offset, + citation, + )?; + metadata.citetitle = Some(CiteTitle::new(citation)); + } + } + let (content, content_start, delimiter, skip_empty, error_context) = match ¶ms.source { + QuoteSource::Shorthand { + content, + content_start, + } => ( + *content, + *content_start, + "\"", + false, + "Error parsing content as blocks in quoted paragraph", + ), + QuoteSource::Markdown(lines) => ( + state.intern_join(lines.iter(), "\n"), + params.start, + ">", + true, + "Error parsing content as blocks in markdown blockquote", + ), + }; + let blocks = if skip_empty && content.trim().is_empty() { + Vec::new() + } else { + let request = ContentRequest { + source: content, + offset: content_start + params.offset, + parent_section_level: block_metadata.parent_section_level, + context: state.block_context, + kind: ContentKind::Blocks, + error_context, + }; + parse_content(state, request, parser)? + }; + Ok(Block::DelimitedBlock(DelimitedBlock { + source_text: None, + metadata, + delimiter, + inner: DelimitedBlockType::DelimitedQuote(blocks), + title: block_metadata.title.clone(), + location: state.create_block_location(params.start, params.end, params.offset), + open_delimiter_location: None, + close_delimiter_location: None, + })) +} diff --git a/acdc-parser/src/grammar/document/table.rs b/acdc-parser/src/grammar/document/table.rs index 776254a2b..b78d1607b 100644 --- a/acdc-parser/src/grammar/document/table.rs +++ b/acdc-parser/src/grammar/document/table.rs @@ -1,5 +1,6 @@ //! Table blocks and cell content. +pub(super) mod construction; #[cfg(test)] mod tests; @@ -11,7 +12,7 @@ use crate::{ blocks::table::{CellSpecifier, MAX_TABLE_COLUMNS}, grammar::{ ParserState, - document::delimited::check_delimiters, + document::delimited::{ContentParser, GrammarContent, check_delimiters}, document_parser, helpers::BlockParsingMetadata, inline_processing::{PreparedInlines, adjust_and_log_parse_error}, @@ -20,6 +21,8 @@ use crate::{ }; use std::{borrow::Cow, cell::RefCell, rc::Rc}; +pub(super) type InitialAttributes<'a> = Vec<(AttributeName<'a>, DocumentAttributeAssignment<'a>)>; + /// The matched closing delimiter, or an unterminated table. /// An unterminated table ends at end of input and produces a warning. #[derive(Clone, Copy)] @@ -135,11 +138,55 @@ fn parse_column_spec(input: &str) -> Option<(usize, ColumnFormat, Option<&str>)> } /// Parse a table block with the selected separator and source ranges. -#[allow(clippy::too_many_lines)] pub(super) fn parse_table_block_impl<'input>( params: &TableParseParams<'_>, state: &mut ParserState<'input>, block_metadata: &BlockParsingMetadata<'input>, +) -> Result, Error> { + parse_table_with_cells(params, state, block_metadata, &mut NativeCells) +} + +trait CellParser<'a> { + fn begin_row(&mut self, _state: &ParserState<'a>) {} + fn begin_cell(&mut self) {} + fn parse( + &mut self, + content: &'a str, + state: &mut ParserState<'a>, + offset: usize, + spec: &CellSpecifier, + prepared: &mut Option>>, + ) -> Result, Error>; + fn finish_row(&mut self, _state: &mut ParserState<'a>, _destination: Option) {} +} + +#[derive(Clone, Copy)] +struct RowDestination { + part: crate::extensions::TablePart, + row: usize, +} + +struct NativeCells; + +impl<'a> CellParser<'a> for NativeCells { + fn parse( + &mut self, + content: &'a str, + state: &mut ParserState<'a>, + offset: usize, + spec: &CellSpecifier, + prepared: &mut Option>>, + ) -> Result, Error> { + parse_table_cell(content, state, offset, spec, prepared) + } +} + +#[allow(clippy::too_many_lines)] +fn parse_table_with_cells<'input>( + params: &TableParseParams<'_>, + state: &mut ParserState<'input>, + block_metadata: &BlockParsingMetadata<'input>, + cells: &mut impl CellParser<'input>, ) -> Result, Error> { let &TableParseParams { start, @@ -321,6 +368,7 @@ pub(super) fn parse_table_block_impl<'input>( let mut active_rowspans: Vec<(usize, usize, usize)> = Vec::new(); for (i, row) in raw_rows.iter().enumerate() { + cells.begin_row(state); let is_header_row = has_header; // Each raw cell produces at least one `columns` entry; duplication // produces more but is bounded by the table's column limit. @@ -335,6 +383,7 @@ pub(super) fn parse_table_block_impl<'input>( continue; } let cell_content = state.intern_str(&cell.content); + cells.begin_cell(); let mut prepared = None; // Duplicates share source text, but each parse must apply its own // footnote and document-attribute effects. @@ -352,7 +401,7 @@ pub(super) fn parse_table_block_impl<'input>( { spec.style = Some(col_format.style); } - let parsed = parse_table_cell( + let parsed = cells.parse( cell_content, state, cell.content_start, @@ -411,6 +460,7 @@ pub(super) fn parse_table_block_impl<'input>( Some(state.create_error_source_location(row_location)), )); } + cells.finish_row(state, None); continue; } @@ -450,16 +500,37 @@ pub(super) fn parse_table_block_impl<'input>( } if is_header_row { + cells.finish_row( + state, + Some(RowDestination { + part: crate::extensions::TablePart::Head, + row: 0, + }), + ); header = Some(TableRow { columns }); has_header = false; continue; } if has_footer && i == raw_rows.len() - 1 { + cells.finish_row( + state, + Some(RowDestination { + part: crate::extensions::TablePart::Foot, + row: 0, + }), + ); footer = Some(TableRow { columns }); continue; } + cells.finish_row( + state, + Some(RowDestination { + part: crate::extensions::TablePart::Body, + row: rows.len(), + }), + ); rows.push(TableRow { columns }); } @@ -608,6 +679,24 @@ fn parse_table_cell<'a>( cell_start_offset: usize, spec: &CellSpecifier, prepared: &mut Option>>, +) -> Result, Error> { + parse_table_cell_with_parser( + content, + state, + cell_start_offset, + spec, + prepared, + &mut GrammarContent, + ) +} + +fn parse_table_cell_with_parser<'a>( + content: &'a str, + state: &mut ParserState<'a>, + cell_start_offset: usize, + spec: &CellSpecifier, + prepared: &mut Option>>, + parser: &mut impl ContentParser<'a>, ) -> Result, Error> { // Literal cells keep their source text intact. Unlike listing blocks, they // do not run attribute, macro, quote, or callout substitutions. @@ -662,12 +751,8 @@ fn parse_table_cell<'a>( &mut state.document_attributes, )); - let result = document_parser::nested_document_blocks( - content, - state, - cell_start_offset, - &mut initial_attributes, - ); + let result = + parser.nested_document(state, content, cell_start_offset, &mut initial_attributes); if result.is_err() { state.footnote_tracker.borrow_mut().discard_definitions(); diff --git a/acdc-parser/src/grammar/document/table/construction.rs b/acdc-parser/src/grammar/document/table/construction.rs new file mode 100644 index 000000000..965164aee --- /dev/null +++ b/acdc-parser/src/grammar/document/table/construction.rs @@ -0,0 +1,156 @@ +//! Accepted table layout with cell construction deferred until after PEG returns. + +use std::mem; + +use super::{ + CellParser, CellSpecifier, ContentParser, PreparedTableCellParagraph, RowDestination, + TableParseParams, parse_table_cell, parse_table_cell_with_parser, parse_table_with_cells, +}; +use crate::{ + Block, DelimitedBlockType, Error, TableCell, Warning, + grammar::{ParserState, helpers::BlockParsingMetadata}, +}; + +pub(in crate::grammar::document) struct TableConstruction<'a> { + pub(in crate::grammar::document) metadata: BlockParsingMetadata<'a>, + pub(in crate::grammar::document) params: TableParseParams<'a>, +} + +struct CellRequest<'a> { + source: &'a str, + offset: usize, + spec: CellSpecifier, + group: usize, +} + +struct RowRequest<'a> { + cells: Vec>, + destination: Option, + warnings: Vec, +} + +#[derive(Default)] +pub(in crate::grammar::document) struct TableContent<'a> { + rows: Vec>, + cells: Vec>, + group: usize, + warning_start: usize, +} + +impl<'a> CellParser<'a> for TableContent<'a> { + fn begin_row(&mut self, state: &ParserState<'a>) { + self.warning_start = state.warnings.borrow().len(); + } + + fn begin_cell(&mut self) { + self.group += 1; + } + + fn parse( + &mut self, + content: &'a str, + _state: &mut ParserState<'a>, + offset: usize, + spec: &CellSpecifier, + _prepared: &mut Option>>, + ) -> Result, Error> { + self.cells.push(CellRequest { + source: content, + offset, + spec: *spec, + group: self.group, + }); + Ok(TableCell::with_format( + Vec::new(), + spec.colspan, + spec.rowspan, + spec.halign, + spec.valign, + spec.style, + )) + } + + fn finish_row(&mut self, state: &mut ParserState<'a>, destination: Option) { + self.rows.push(RowRequest { + cells: mem::take(&mut self.cells), + destination, + warnings: state.warnings.borrow_mut().split_off(self.warning_start), + }); + } +} + +impl<'a> TableConstruction<'a> { + pub(in crate::grammar::document) fn start( + self, + state: &mut ParserState<'a>, + ) -> Result<(Block<'a>, TableContent<'a>), Error> { + let mut content = TableContent::default(); + let block = parse_table_with_cells(&self.params, state, &self.metadata, &mut content)?; + Ok((block, content)) + } +} + +impl<'a> TableContent<'a> { + pub(in crate::grammar::document) fn finish( + self, + block: &mut Block<'a>, + state: &mut ParserState<'a>, + parser: &mut impl ContentParser<'a>, + ) -> Result<(), Error> { + let location = block.location().clone(); + let Block::DelimitedBlock(block) = block else { + return Ok(()); + }; + let DelimitedBlockType::DelimitedTable(table) = &mut block.inner else { + return Ok(()); + }; + let mut group = None; + let mut prepared = None; + for row in self.rows { + for (column, request) in row.cells.into_iter().enumerate() { + if group != Some(request.group) { + group = Some(request.group); + prepared = None; + } + let Some(destination) = row.destination else { + // Native numbering and diagnostics from a discarded row + // retain their established behavior. External handlers + // only run for cells in the accepted table layout. + parse_table_cell( + request.source, + state, + request.offset, + &request.spec, + &mut prepared, + )?; + continue; + }; + let cell = parse_table_cell_with_parser( + request.source, + state, + request.offset, + &request.spec, + &mut prepared, + parser, + )?; + let slot = crate::extensions::table_cell_mut( + table, + destination.part, + destination.row, + column, + ) + .ok_or_else(|| { + Error::Parse( + Box::new(state.create_error_source_location(location.clone())), + "table builder returned no accepted cell slot".into(), + ) + })?; + *slot = cell; + } + for warning in row.warnings { + state.warnings.borrow_mut().push(warning); + } + } + Ok(()) + } +} diff --git a/acdc-parser/src/grammar/document/tests.rs b/acdc-parser/src/grammar/document/tests.rs index 8c769b6b8..d49aee460 100644 --- a/acdc-parser/src/grammar/document/tests.rs +++ b/acdc-parser/src/grammar/document/tests.rs @@ -1,5 +1,7 @@ use super::{ - coordinator::BlockCursor, document as parse_document, document_parser, + construction::ConstructionMode, + coordinator::{BlockCursor, BlockStepKind}, + document as parse_document, document_parser, paragraph::paragraph_text_end, }; use crate::{ @@ -17,28 +19,33 @@ fn block_cursor_does_not_apply_later_attributes_before_advancing() let input = "before\n\n:later: value\n\n{later}"; let mut state = ParserState::new_for_test(input); let prefix = document_parser::document_prefix(input, &mut state)??; - let mut cursor = BlockCursor::new(prefix.body_offset); + let mut cursor = BlockCursor::new(prefix.body_offset, ConstructionMode::Ordered); let first = cursor.advance(input, &mut state)??; - assert!(matches!(first.block, Some(Block::Paragraph(_)))); - assert!(!first.complete); + assert!(matches!( + first.kind, + BlockStepKind::Block(Block::Paragraph(_)) + )); assert_eq!(state.document_attributes.text("later"), None); let assignment = cursor.advance(input, &mut state)??; assert!(matches!( - assignment.block, - Some(Block::DocumentAttribute(_)) + assignment.kind, + BlockStepKind::Block(Block::DocumentAttribute(_)) )); assert_eq!(state.document_attributes.text("later"), Some("value")); let last = cursor.advance(input, &mut state)??; - let Some(Block::Paragraph(paragraph)) = last.block else { + let BlockStepKind::Block(Block::Paragraph(paragraph)) = last.kind else { return Err("expected the final paragraph".into()); }; assert!( matches!(paragraph.content.as_slice(), [InlineNode::PlainText(plain)] if plain.content == "value") ); - assert!(cursor.advance(input, &mut state)??.complete); + assert!(matches!( + cursor.advance(input, &mut state)??.kind, + BlockStepKind::End(_) + )); Ok(()) } @@ -48,14 +55,14 @@ fn block_cursor_applies_a_committed_change_to_the_next_block() let input = "before\n\n{extension-value}"; let mut state = ParserState::new_for_test(input); let prefix = document_parser::document_prefix(input, &mut state)??; - let mut cursor = BlockCursor::new(prefix.body_offset); + let mut cursor = BlockCursor::new(prefix.body_offset, ConstructionMode::Ordered); let first = cursor.advance(input, &mut state)??; - assert!(first.block.is_some()); + assert!(matches!(first.kind, BlockStepKind::Block(_))); std::rc::Rc::make_mut(&mut state.document_attributes) .set_text("extension-value".into(), "after".into()); let second = cursor.advance(input, &mut state)??; - let Some(Block::Paragraph(paragraph)) = second.block else { + let BlockStepKind::Block(Block::Paragraph(paragraph)) = second.kind else { return Err("expected a paragraph after the committed change".into()); }; assert!( @@ -64,6 +71,150 @@ fn block_cursor_applies_a_committed_change_to_the_next_block() Ok(()) } +#[test] +fn block_cursor_commits_section_headers_before_their_children() +-> Result<(), Box> { + for heading in ["== Parent", "Parent\n------"] { + let input = format!( + "{heading}\n\nfirst\n\n=== Child\n\n{{committed}}\n\n:later: value\n\n== Sibling\n\nend" + ); + let mut state = ParserState::new_for_test(&input); + let prefix = document_parser::document_prefix(&input, &mut state)??; + let mut root = BlockCursor::new(prefix.body_offset, ConstructionMode::Ordered); + let first = root.advance(&input, &mut state)??; + let BlockStepKind::Block(Block::Section(parent)) = first.kind else { + return Err("expected a committed section header".into()); + }; + assert_eq!(parent.content, Vec::>::new()); + assert_eq!(state.document_attributes.text("later"), None); + assert_eq!(state.toc_entries.len(), 1); + + let mut body = root.section(&parent, &state); + assert!(matches!( + body.advance(&input, &mut state)??.kind, + BlockStepKind::Block(Block::Paragraph(_)) + )); + let next = body.advance(&input, &mut state)??; + let BlockStepKind::Block(Block::Section(child)) = next.kind else { + return Err("expected a committed child heading".into()); + }; + assert_eq!(child.content, Vec::>::new()); + assert_eq!(state.document_attributes.text("later"), None); + + std::rc::Rc::make_mut(&mut state.document_attributes) + .set_text("committed".into(), "visible".into()); + let mut child_body = body.section(&child, &state); + let next = child_body.advance(&input, &mut state)??; + let BlockStepKind::Block(Block::Paragraph(paragraph)) = next.kind else { + return Err("expected a paragraph after the committed child heading".into()); + }; + assert!(matches!( + paragraph.content.as_slice(), + [InlineNode::PlainText(plain)] if plain.content == "visible" + )); + assert_eq!(state.document_attributes.text("later"), None); + assert!(matches!( + child_body.advance(&input, &mut state)??.kind, + BlockStepKind::Block(Block::DocumentAttribute(_)) + )); + let end = child_body.advance(&input, &mut state)??; + assert!(matches!(end.kind, BlockStepKind::End(_))); + assert!( + input + .get(end.end..) + .is_some_and(|tail| tail.contains("== Sibling")) + ); + } + Ok(()) +} + +#[test] +fn section_driver_executes_accepted_handlers_once_in_source_order() +-> Result<(), Box> { + let input = "== Parent\n\n{value}\n\n=== Child\n\n{value}\n\n== Sibling\n\n{value}"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let arena = bumpalo::Bump::new(); + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut state = ParserState::new(input, &arena, std::rc::Rc::new(options)); + let mut accepted = Vec::new(); + let document = super::coordinator::document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + accepted.push(block.location().absolute_start); + if let Block::Section(section) = block { + assert_eq!(section.content, Vec::>::new()); + let value = match section.level { + 1 => "outer", + 2 => "inner", + _ => { + return Err(Error::Extension( + Box::new( + state.create_error_source_location(section.location.clone()), + ), + "unexpected section".into(), + )); + } + }; + std::rc::Rc::make_mut(&mut state.document_attributes) + .set_text("value".into(), value.into()); + } + Ok(()) + }, + )??; + assert_eq!(accepted.len(), 6); + assert!(accepted.windows(2).all(|pair| pair[0] < pair[1])); + let [Block::Section(parent), Block::Section(sibling)] = document.blocks.as_slice() else { + return Err("expected parent and sibling sections".into()); + }; + let [Block::Paragraph(outer), Block::Section(child)] = parent.content.as_slice() else { + return Err("expected paragraph and child section".into()); + }; + let [Block::Paragraph(inner)] = child.content.as_slice() else { + return Err("expected child paragraph".into()); + }; + let [Block::Paragraph(last)] = sibling.content.as_slice() else { + return Err("expected sibling paragraph".into()); + }; + for (paragraph, expected) in [(outer, "outer"), (inner, "inner"), (last, "outer")] { + assert!(matches!( + paragraph.content.as_slice(), + [InlineNode::PlainText(plain)] if plain.content == expected + )); + } + } + Ok(()) +} + +#[test] +fn section_driver_stops_before_later_children_when_a_handler_fails() +-> Result<(), Box> { + let input = "== Parent\n\nfirst\n\n=== Later\n\n:later: value"; + let mut state = ParserState::new_for_test(input); + let mut calls = 0; + let result = super::coordinator::document_with( + input, + &mut state, + ConstructionMode::Ordered, + &mut |block, state| { + calls += 1; + if matches!(block, Block::Paragraph(_)) { + return Err(Error::Extension( + Box::new(state.create_error_source_location(block.location().clone())), + "deliberate accepted-handler failure".into(), + )); + } + Ok(()) + }, + )?; + assert!(matches!(result, Err(Error::Extension(..)))); + assert_eq!(calls, 2); + assert_eq!(state.toc_entries.len(), 1); + assert_eq!(state.document_attributes.text("later"), None); + Ok(()) +} + #[test] fn paragraph_runs_stop_before_line_boundaries_and_anchor_openers() { for (source, start, end) in [ From b8ec58d284c2230f24c5b2b889ca0b1199b863c9 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 12 Nov 2026 17:30:10 +0100 Subject: [PATCH 06/55] refactor(parser): coordinate source reading with committed construction Connect the resumable preprocessor and ordered block cursor through a private source-handler seam. Apply accepted attribute assignments before advancing to later directives, while preserving include policies, source origins, bounded cell scopes, and stable input storage. Reuse the native grammar for source boundaries and preserve the recursive ordinary parsing path. Keep window coordinates separate from local inline maps and avoid repeated copies of the complete processed prefix. Retain direct local location lookup for ordinary input. Cover source order in nested lists and includes, failure stopping later include reads, caller attribute locks, selected include source maps, and compound/cell scope parity. Fix nested-list ID source locations. Validation: 12,594 workspace tests, 118 doctests, 1,253 feature-off parser tests, strict all-targets/all-features Clippy, formatting, and diff checks. The four include benchmark workloads completed. Paired ordinary parsing measurements still leave performance acceptance open; SC-535 remains In Progress. Public Registry callback migration belongs to A2. Refs SC-535. --- acdc-parser/CHANGELOG.md | 2 + acdc-parser/src/grammar/document.rs | 3 + .../grammar/document/construction/tests.rs | 1 + .../src/grammar/document/coordinator.rs | 56 +- acdc-parser/src/grammar/document/delimited.rs | 5 + acdc-parser/src/grammar/document/finish.rs | 14 +- acdc-parser/src/grammar/document/header.rs | 6 +- acdc-parser/src/grammar/document/input.rs | 39 + .../src/grammar/document/lists/callout.rs | 50 +- .../grammar/document/lists/construction.rs | 117 ++- .../src/grammar/document/lists/description.rs | 65 +- acdc-parser/src/grammar/document/metadata.rs | 2 +- acdc-parser/src/grammar/document/peg.rs | 201 +++-- acdc-parser/src/grammar/document/source.rs | 688 ++++++++++++++++++ acdc-parser/src/grammar/document/table.rs | 5 + .../src/grammar/inline_preprocessor.rs | 57 +- .../src/grammar/inline_preprocessor/tests.rs | 16 +- acdc-parser/src/grammar/inline_processing.rs | 39 +- acdc-parser/src/grammar/inlines/peg.rs | 18 +- acdc-parser/src/grammar/location_mapping.rs | 45 +- acdc-parser/src/grammar/mod.rs | 5 +- .../src/grammar/passthrough_processing.rs | 26 +- acdc-parser/src/grammar/reference_text.rs | 12 +- acdc-parser/src/grammar/source.rs | 450 ++++++++++++ acdc-parser/src/grammar/source/tests.rs | 203 ++++++ acdc-parser/src/grammar/state.rs | 183 ++++- acdc-parser/src/grammar/utf8_utils.rs | 3 + acdc-parser/src/lib.rs | 109 ++- acdc-parser/src/parsed.rs | 67 +- acdc-parser/src/preprocessor/cursor.rs | 339 ++++++++- acdc-parser/src/preprocessor/include.rs | 4 +- acdc-parser/src/preprocessor/mod.rs | 4 +- acdc-parser/src/preprocessor/source.rs | 190 +++++ acdc-parser/src/preprocessor/source/tests.rs | 141 ++++ acdc-parser/src/source_tests.rs | 488 +++++++++++++ 35 files changed, 3288 insertions(+), 365 deletions(-) create mode 100644 acdc-parser/src/grammar/document/input.rs create mode 100644 acdc-parser/src/grammar/document/source.rs create mode 100644 acdc-parser/src/grammar/source.rs create mode 100644 acdc-parser/src/grammar/source/tests.rs create mode 100644 acdc-parser/src/preprocessor/source.rs create mode 100644 acdc-parser/src/preprocessor/source/tests.rs create mode 100644 acdc-parser/src/source_tests.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index a0d156539..fe431595a 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -150,6 +150,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 to 4096 bytes. A bare caller value applies a zero-byte cap; an explicit unset disables the cap. This limit and include `depth=` accept Ruby digit separators, such as `4_096`. +- Nested list IDs specified with `[id=...]` now retain their correct source + locations inside compound blocks. - **Breaking since 0.11:** public names now distinguish table cells, reference targets, quoted spans, and UI macros. Replace `TableColumn` with `TableCell`, diff --git a/acdc-parser/src/grammar/document.rs b/acdc-parser/src/grammar/document.rs index 54e449a2e..a0a7d204a 100644 --- a/acdc-parser/src/grammar/document.rs +++ b/acdc-parser/src/grammar/document.rs @@ -8,6 +8,7 @@ mod delimited; mod doctype; mod finish; mod header; +mod input; pub(super) mod lists; mod manpage; mod metadata; @@ -17,11 +18,13 @@ mod quotes; mod references; mod revision; mod sections; +mod source; mod table; mod verbatim; pub(crate) use coordinator::document; pub(crate) use peg::document_parser; +pub(crate) use source::{SourceHandler, document_from_source}; type RecognitionError = ::peg::error::ParseError<::peg::str::LineCol>; diff --git a/acdc-parser/src/grammar/document/construction/tests.rs b/acdc-parser/src/grammar/document/construction/tests.rs index 801459aa9..571367b2a 100644 --- a/acdc-parser/src/grammar/document/construction/tests.rs +++ b/acdc-parser/src/grammar/document/construction/tests.rs @@ -36,6 +36,7 @@ fn compound_driver_preserves_existing_construction(#[case] input: &str) -> TestR fn assert_equivalent(input: &str) -> TestResult { for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + crate::source_tests::assert_equivalent(input, mode)?; let reference_arena = bumpalo::Bump::new(); let ordered_arena = bumpalo::Bump::new(); let options = Rc::new(Options::builder().with_compatibility_mode(mode).build()?); diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index 2929ac0cc..14b1f01b4 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -13,6 +13,7 @@ use super::{ doctype::is_book_doctype, document_parser, finish, header::ParsedHeader, + input::{BlockInput, ReadRequest, TextInput}, lists::ListEntry, metadata::{assign_block_caption, order_block_prefix_events}, sections::expected_child_level, @@ -26,7 +27,13 @@ pub(super) struct Execution<'handler, F> { failed: bool, } -impl Execution<'_, F> { +impl<'handler, F> Execution<'handler, F> { + pub(super) fn new(callback: &'handler mut F) -> Self { + Self { + callback, + failed: false, + } + } pub(super) fn run<'a>( &mut self, block: &Block<'a>, @@ -154,9 +161,9 @@ impl BlockCursor { /// Ordered construction enters each section after its heading recognition /// has returned. The recursive mode retains the ordinary parsing fast path. - fn collect<'a>( + pub(super) fn collect<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, blocks: &mut Vec>, accepted: &mut Execution< @@ -165,7 +172,11 @@ impl BlockCursor { >, ) -> Result, RecognitionError> { loop { - let step = match self.advance(input, state)? { + let source = match input.prepare(self, state, ReadRequest::Block) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; + let step = match self.advance(source, state)? { Ok(step) => step, Err(error) => return Ok(Err(error)), }; @@ -173,7 +184,7 @@ impl BlockCursor { BlockStepKind::End(trailing) => { blocks.extend(trailing); *blocks = order_block_prefix_events(std::mem::take(blocks)); - return Ok(Ok(step.end)); + return Ok(Ok(self.base_offset + step.end)); } kind @ (BlockStepKind::Block(_) | BlockStepKind::Delimited(_) @@ -190,7 +201,7 @@ impl BlockCursor { pub(super) fn construct<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, kind: BlockStepKind<'a>, accepted: &mut Execution< @@ -256,12 +267,9 @@ impl BlockCursor { Ok(end) => end, Err(error) => return Ok(Err(error)), }; - self.offset = end; - section.location = state.create_block_location( - section.location.absolute_start, - self.base_offset + end, - 0, - ); + self.offset = child.offset; + self.base_offset = child.base_offset; + section.location = state.create_block_location(section.location.absolute_start, end, 0); } if let Some(request) = request { let mut parser = CursorContent { accepted }; @@ -315,10 +323,17 @@ where let mut blocks = Vec::new(); let toc_start = state.toc_entries.len(); let result = cursor - .collect(request.source, state, &mut blocks, self.accepted) + .collect( + &mut TextInput(request.source), + state, + &mut blocks, + self.accepted, + ) .and_then(|result| match result { - Ok(end) => document_parser::block_sequence_end(request.source, state, end) - .map(|()| Ok(blocks)), + Ok(end) => { + document_parser::block_sequence_end(request.source, state, end - request.offset) + .map(|()| Ok(blocks)) + } Err(error) => Ok(Err(error)), }); match result { @@ -362,11 +377,11 @@ where mode: ConstructionMode::Ordered, }; let mut blocks = prefix.blocks; - let end = match cursor.collect(source, state, &mut blocks, self.accepted)? { + let end = match cursor.collect(&mut TextInput(source), state, &mut blocks, self.accepted)? { Ok(end) => end, Err(error) => return Ok(Err(error)), }; - document_parser::block_sequence_end(source, state, end)?; + document_parser::block_sequence_end(source, state, end - offset)?; Ok(Ok(blocks)) } } @@ -399,11 +414,8 @@ pub(super) fn document_with<'a>( }; let mut cursor = BlockCursor::new(prefix.body_offset, mode); let mut blocks = prefix.comments; - let mut execution = Execution { - callback: accepted, - failed: false, - }; - let end = match cursor.collect(input, state, &mut blocks, &mut execution)? { + let mut execution = Execution::new(accepted); + let end = match cursor.collect(&mut TextInput(input), state, &mut blocks, &mut execution)? { Ok(end) => end, Err(error) => return Ok(Err(error)), }; diff --git a/acdc-parser/src/grammar/document/delimited.rs b/acdc-parser/src/grammar/document/delimited.rs index ae8b781e9..a5868f3b8 100644 --- a/acdc-parser/src/grammar/document/delimited.rs +++ b/acdc-parser/src/grammar/document/delimited.rs @@ -94,8 +94,13 @@ pub(super) fn parse_content<'a>( parser: &mut impl ContentParser<'a>, ) -> Result>, Error> { let outer_context = std::mem::replace(&mut state.block_context, request.context); + let outer_scope = state.source_scope_offset; + if state.input_origin.is_some() { + state.source_scope_offset = request.offset; + } let result = parser.parse(state, request); state.block_context = outer_context; + state.source_scope_offset = outer_scope; result } diff --git a/acdc-parser/src/grammar/document/finish.rs b/acdc-parser/src/grammar/document/finish.rs index c1887c886..5960ca1b3 100644 --- a/acdc-parser/src/grammar/document/finish.rs +++ b/acdc-parser/src/grammar/document/finish.rs @@ -91,23 +91,17 @@ pub(super) fn finish<'a>( } fn document_location(state: &ParserState<'_>, start: PositionWithOffset, end: usize) -> Location { - let mut end = end.min(state.input.len()); - while end < state.input.len() && !state.input.is_char_boundary(end) { - end += 1; - } + let mut end = state.source_snap(end, crate::grammar::utf8_utils::RoundDirection::Forward); if end != 0 { - end = crate::grammar::utf8_utils::safe_decrement_offset(state.input, end); + end = state.source_step(end, crate::grammar::utf8_utils::RoundDirection::Backward); } // Whitespace-only input can put the start beyond the last content byte. let absolute_end = end.max(start.offset); let (start_position, end_position) = - if state.input.is_empty() || (start.offset == 0 && absolute_end == 0) { + if state.source_len() == 0 || (start.offset == 0 && absolute_end == 0) { (Position::new(1, 0), Position::new(1, 0)) } else { - ( - start.position, - state.line_map.offset_to_position(absolute_end, state.input), - ) + (start.position, state.source_position(absolute_end)) }; Location { absolute_start: start.offset, diff --git a/acdc-parser/src/grammar/document/header.rs b/acdc-parser/src/grammar/document/header.rs index 1eb55fe96..7b900b6b5 100644 --- a/acdc-parser/src/grammar/document/header.rs +++ b/acdc-parser/src/grammar/document/header.rs @@ -19,8 +19,10 @@ pub(in crate::grammar::document) struct ParsedHeader<'input> { /// `end` offset, which ends the last header line. pub(super) fn header_span(state: &ParserState<'_>, start: usize, end: usize) -> Location { let mut location = state.create_location(start, end); - location.absolute_end = - crate::grammar::utf8_utils::safe_decrement_offset(state.input, location.absolute_end); + location.absolute_end = state.source_step( + location.absolute_end, + crate::grammar::utf8_utils::RoundDirection::Backward, + ); location.end.column = location.end.column.saturating_sub(1); location } diff --git a/acdc-parser/src/grammar/document/input.rs b/acdc-parser/src/grammar/document/input.rs new file mode 100644 index 000000000..b50f0e8d1 --- /dev/null +++ b/acdc-parser/src/grammar/document/input.rs @@ -0,0 +1,39 @@ +//! Supply stable input to one accepted construction step. + +use crate::{Error, grammar::ParserState}; + +use super::{ + coordinator::BlockCursor, + lists::{ListKind, ListPhase}, +}; + +#[derive(Clone, Copy)] +pub(super) enum ReadRequest<'a> { + Block, + ListHead(ListKind<'a>), + ListNext(ListKind<'a>, &'a str, ListPhase), + ListEnd, +} + +pub(super) trait BlockInput<'a> { + fn prepare( + &mut self, + cursor: &mut BlockCursor, + state: &mut ParserState<'a>, + request: ReadRequest<'a>, + ) -> Result<&'a str, Error>; +} + +pub(super) struct TextInput<'a>(pub(super) &'a str); + +impl<'a> BlockInput<'a> for TextInput<'a> { + #[inline] + fn prepare( + &mut self, + _: &mut BlockCursor, + _: &mut ParserState<'a>, + _: ReadRequest<'a>, + ) -> Result<&'a str, Error> { + Ok(self.0) + } +} diff --git a/acdc-parser/src/grammar/document/lists/callout.rs b/acdc-parser/src/grammar/document/lists/callout.rs index b58fb76f9..e55cf91b4 100644 --- a/acdc-parser/src/grammar/document/lists/callout.rs +++ b/acdc-parser/src/grammar/document/lists/callout.rs @@ -9,40 +9,47 @@ use super::super::{ RecognitionError, coordinator::{BlockCursor, Execution}, document_parser, + input::{BlockInput, ReadRequest}, metadata::order_block_prefix_events, }; -use super::{CalloutItem, CalloutItemHead, ListEntry, ListKind, build_callout_list}; +use super::{CalloutItem, CalloutItemHead, ListKind, build_callout_list}; impl BlockCursor { pub(super) fn construct_callout_list<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, - entry: &ListEntry<'a>, + start: usize, metadata: &BlockParsingMetadata<'a>, accepted: &mut Execution< '_, impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, >, ) -> Result, Error>, RecognitionError> { + let source = match input.prepare(self, state, ReadRequest::ListHead(ListKind::Callout)) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let (head, (parent_scope, callouts), end) = document_parser::first_callout_list_item( - input, + source, state, self.offset, self.base_offset, metadata, )?; self.offset = end; - let result = self.collect_callout_items(input, state, entry, metadata, head, accepted); + let result = self.collect_callout_items(input, state, start, metadata, head, accepted); state.callout_list_offset = parent_scope; state.pending_callouts.clear(); result.map(|result| { result.map(|items| { - let end = items.last().map_or(self.offset, |(_, _, end)| *end); + let end = items + .last() + .map_or(self.offset + self.base_offset, |(_, _, end)| *end); build_callout_list( state, metadata, - state.create_location(entry.start + self.base_offset, end + self.base_offset), + state.create_location(start, end), items, &callouts, ) @@ -52,9 +59,9 @@ impl BlockCursor { fn collect_callout_items<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, - entry: &ListEntry<'a>, + start: usize, metadata: &BlockParsingMetadata<'a>, head: CalloutItemHead<'a>, accepted: &mut Execution< @@ -66,10 +73,11 @@ impl BlockCursor { Ok(item) => item, Err(error) => return Ok(Err(error)), }; + item.2 += self.base_offset; let shell = build_callout_list( state, metadata, - state.create_location(entry.start + self.base_offset, item.2 + self.base_offset), + state.create_location(start, item.2), Vec::new(), &[], ); @@ -88,17 +96,28 @@ impl BlockCursor { Ok(blocks) => blocks, Err(error) => return Ok(Err(error)), }; + let source = match input.prepare(self, state, ReadRequest::ListEnd) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; self.offset = - document_parser::list_item_end(input, state, self.offset, self.base_offset, true)?; + document_parser::list_item_end(source, state, self.offset, self.base_offset, true)?; if !item.0.blocks.is_empty() { - item.2 = self.offset.saturating_sub(1); - item.0.location = state - .create_location(item.0.location.absolute_start, item.2 + self.base_offset); + item.2 = self.base_offset + self.offset.saturating_sub(1); + item.0.location = state.create_location(item.0.location.absolute_start, item.2); item.0.blocks = order_block_prefix_events(item.0.blocks); } items.push(item); + let source = match input.prepare( + self, + state, + ReadRequest::ListNext(ListKind::Callout, "", super::ListPhase::Sibling), + ) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let (next, end) = document_parser::next_callout_list_item( - input, + source, state, self.offset, self.base_offset, @@ -110,6 +129,7 @@ impl BlockCursor { Ok(item) => item, Err(error) => return Ok(Err(error)), }; + item.2 += self.base_offset; } else { return Ok(Ok(items)); } diff --git a/acdc-parser/src/grammar/document/lists/construction.rs b/acdc-parser/src/grammar/document/lists/construction.rs index 75c11469f..878261563 100644 --- a/acdc-parser/src/grammar/document/lists/construction.rs +++ b/acdc-parser/src/grammar/document/lists/construction.rs @@ -1,7 +1,7 @@ //! Advance ordinary list principals and attachments at committed boundaries. use crate::{ - Block, Error, + Block, Error, ListItem, grammar::{ParserState, helpers::BlockParsingMetadata}, }; @@ -9,17 +9,18 @@ use super::super::{ RecognitionError, coordinator::{BlockCursor, Execution}, document_parser, + input::{BlockInput, ReadRequest}, metadata::order_block_prefix_events, }; use super::{ - ListEntry, ListItemHead, ListKind, ListPhase, ListStepKind, OrdinaryListLayout, - build_ordinary_list, + ListEntry, ListItemHead, ListKind, ListPhase, ListStepKind, OrdinaryListKind, + OrdinaryListLayout, build_ordinary_list, }; impl BlockCursor { pub(in crate::grammar::document) fn construct_list<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, entry: &ListEntry<'a>, parent_metadata: &BlockParsingMetadata<'a>, @@ -29,15 +30,20 @@ impl BlockCursor { >, ) -> Result, Error>, RecognitionError> { let metadata = entry.metadata.as_ref().unwrap_or(parent_metadata); + let start = entry.start + self.base_offset; self.offset = entry.body_offset; if matches!(entry.kind, ListKind::Callout) { - return self.construct_callout_list(input, state, entry, metadata, accepted); + return self.construct_callout_list(input, state, start, metadata, accepted); } if matches!(entry.kind, ListKind::Description) { - return self.construct_description_list(input, state, entry, metadata, accepted); + return self.construct_description_list(input, state, start, metadata, accepted); } + let source = match input.prepare(self, state, ReadRequest::ListHead(entry.kind)) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let (head, parent_scope, end) = document_parser::first_ordinary_list_item( - input, + source, state, self.offset, self.base_offset, @@ -45,16 +51,23 @@ impl BlockCursor { metadata, )?; self.offset = end; - let result = self.construct_ordinary_list(input, state, entry, metadata, head, accepted); + let result = self.construct_ordinary_list( + input, + state, + (entry.kind, start), + metadata, + head, + accepted, + ); state.ordinary_list_scope = parent_scope; result } fn construct_ordinary_list<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, - entry: &ListEntry<'a>, + frame: (ListKind<'a>, usize), metadata: &BlockParsingMetadata<'a>, head: ListItemHead<'a>, accepted: &mut Execution< @@ -62,16 +75,13 @@ impl BlockCursor { impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, >, ) -> Result, Error>, RecognitionError> { - let (ordered, kind) = match entry.kind { - ListKind::Unordered(kind) => (false, kind), - ListKind::Ordered(kind) => (true, kind), - ListKind::Callout | ListKind::Description => { - return Ok(Err(list_error( - state, - entry.start + self.base_offset, - "ordinary list construction received a different list kind", - ))); - } + let (list_kind, start) = frame; + let Some((ordered, kind)) = ordinary_parts(list_kind) else { + return Ok(Err(list_error( + state, + start, + "ordinary list construction received a different list kind", + ))); }; let base_marker = head.marker; let (mut item, end) = match head.finish(state, Vec::new(), self.offset, self.base_offset) { @@ -82,9 +92,9 @@ impl BlockCursor { state, metadata, OrdinaryListLayout { - start: entry.start, - end, - offset: self.base_offset, + start, + end: end + self.base_offset, + offset: 0, ordered, has_own_metadata: kind.has_own_metadata, }, @@ -93,29 +103,28 @@ impl BlockCursor { if let Err(error) = accepted.run(&block, state) { return Ok(Err(error)); } - let Some(first) = crate::extensions::ordinary_list_items_mut(&mut block).and_then(Vec::pop) - else { - return Ok(Err(list_error( - state, - entry.start + self.base_offset, - "ordinary list builder returned no first item", - ))); + item = match take_first_item(&mut block, state, start) { + Ok(item) => item, + Err(error) => return Ok(Err(error)), }; - item = first; let mut items = Vec::new(); loop { item.blocks = match self.collect_list_children( input, state, metadata, - (entry.kind, base_marker, item.marker), + (list_kind, base_marker, item.marker), accepted, )? { Ok(blocks) => blocks, Err(error) => return Ok(Err(error)), }; + let source = match input.prepare(self, state, ReadRequest::ListEnd) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; self.offset = document_parser::list_item_end( - input, + source, state, self.offset, self.base_offset, @@ -128,14 +137,22 @@ impl BlockCursor { ); item.blocks = order_block_prefix_events(item.blocks); } + let source = match input.prepare( + self, + state, + ReadRequest::ListNext(list_kind, base_marker, ListPhase::Sibling), + ) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let last_end = item.location.absolute_end; items.push(item); let step = document_parser::list_next( - input, + source, state, self.offset, self.base_offset, - entry.kind, + list_kind, base_marker, base_marker, metadata, @@ -148,8 +165,7 @@ impl BlockCursor { Err(error) => return Ok(Err(error)), }; } else { - *block.location_mut() = - state.create_location(entry.start + self.base_offset, last_end); + *block.location_mut() = state.create_location(start, last_end); if let Some(slot) = crate::extensions::ordinary_list_items_mut(&mut block) { *slot = items; } @@ -159,7 +175,7 @@ impl BlockCursor { } pub(super) fn collect_list_children<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, metadata: &BlockParsingMetadata<'a>, context: (ListKind<'a>, &'a str, &'a str), @@ -172,8 +188,13 @@ impl BlockCursor { let mut blocks = Vec::new(); let mut phase = ListPhase::AfterPrincipal; loop { + let source = + match input.prepare(self, state, ReadRequest::ListNext(kind, marker, phase)) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let step = document_parser::list_next( - input, + source, state, self.offset, self.base_offset, @@ -215,3 +236,21 @@ fn list_error(state: &ParserState<'_>, offset: usize, message: &str) -> Error { message.into(), ) } + +fn ordinary_parts(kind: ListKind<'_>) -> Option<(bool, OrdinaryListKind<'_>)> { + match kind { + ListKind::Unordered(kind) => Some((false, kind)), + ListKind::Ordered(kind) => Some((true, kind)), + ListKind::Callout | ListKind::Description => None, + } +} + +fn take_first_item<'a>( + block: &mut Block<'a>, + state: &ParserState<'a>, + start: usize, +) -> Result, Error> { + crate::extensions::ordinary_list_items_mut(block) + .and_then(Vec::pop) + .ok_or_else(|| list_error(state, start, "ordinary list builder returned no first item")) +} diff --git a/acdc-parser/src/grammar/document/lists/description.rs b/acdc-parser/src/grammar/document/lists/description.rs index edefe1f80..72cec467c 100644 --- a/acdc-parser/src/grammar/document/lists/description.rs +++ b/acdc-parser/src/grammar/document/lists/description.rs @@ -9,10 +9,10 @@ use super::super::{ RecognitionError, coordinator::{BlockCursor, BlockStepKind, Execution}, document_parser, + input::{BlockInput, ReadRequest}, }; use super::{ - DescriptionItemHead, DescriptionListScope, ListEntry, build_description_list, - warn_discarded_attachment, + DescriptionItemHead, DescriptionListScope, build_description_list, warn_discarded_attachment, }; #[derive(Default)] @@ -24,17 +24,25 @@ struct DescriptionChildren<'a> { impl BlockCursor { pub(super) fn construct_description_list<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, - entry: &ListEntry<'a>, + start: usize, metadata: &BlockParsingMetadata<'a>, accepted: &mut Execution< '_, impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, >, ) -> Result, Error>, RecognitionError> { + let source = match input.prepare( + self, + state, + ReadRequest::ListHead(super::ListKind::Description), + ) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let (head, parent_scope, end) = document_parser::first_description_list_item( - input, + source, state, self.offset, self.base_offset, @@ -44,7 +52,7 @@ impl BlockCursor { let result = self.collect_description_items( input, state, - entry, + start, metadata, (head, parent_scope), accepted, @@ -55,20 +63,16 @@ impl BlockCursor { let end = items.last().map_or(self.offset + self.base_offset, |item| { item.location.absolute_end }); - build_description_list( - metadata, - state.create_location(entry.start + self.base_offset, end), - items, - ) + build_description_list(metadata, state.create_location(start, end), items) }) }) } fn collect_description_items<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, - entry: &ListEntry<'a>, + start: usize, metadata: &BlockParsingMetadata<'a>, initial: (DescriptionItemHead<'a>, Option>), accepted: &mut Execution< @@ -80,6 +84,7 @@ impl BlockCursor { let mut items = Vec::new(); let mut first = true; loop { + let head_base = self.base_offset; let DescriptionItemHead { source, principal } = head; let principal = match principal { Ok(principal) => principal, @@ -88,9 +93,9 @@ impl BlockCursor { if first { let end = source.principal_start + source.principal_content.trim_end().len(); let location = state.create_block_location( - entry.start, - end.max(source.term.delimiter_end), - self.base_offset, + start, + end.max(source.term.delimiter_end) + head_base, + 0, ); let shell = build_description_list(metadata, location, Vec::new()); if let Err(error) = accepted.run(&shell, state) { @@ -113,9 +118,17 @@ impl BlockCursor { for error in children.errors { warn_discarded_attachment(state, &error); } - items.push(source.build(state, principal, children.blocks, self.base_offset)); + items.push(source.build(state, principal, children.blocks, head_base)); + let source = match input.prepare( + self, + state, + ReadRequest::ListNext(super::ListKind::Description, "", super::ListPhase::Sibling), + ) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let (next, end) = document_parser::next_description_list_item( - input, + source, state, self.offset, self.base_offset, @@ -133,7 +146,7 @@ impl BlockCursor { fn collect_description_children<'a>( &mut self, - input: &'a str, + input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, metadata: &BlockParsingMetadata<'a>, delimiter: &'a str, @@ -145,8 +158,20 @@ impl BlockCursor { let mut children = DescriptionChildren::default(); let mut continuing = false; loop { + let source = match input.prepare( + self, + state, + ReadRequest::ListNext( + super::ListKind::Description, + delimiter, + super::ListPhase::Attachments, + ), + ) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; let step = document_parser::description_list_next( - input, + source, state, self.offset, self.base_offset, diff --git a/acdc-parser/src/grammar/document/metadata.rs b/acdc-parser/src/grammar/document/metadata.rs index 82748e3da..3d4bafd85 100644 --- a/acdc-parser/src/grammar/document/metadata.rs +++ b/acdc-parser/src/grammar/document/metadata.rs @@ -402,7 +402,7 @@ pub(super) fn media_attributes_ahead<'input>( line_start: usize, offset: usize, ) -> Option> { - let line = state.input.get(line_start + offset..)?.lines().next()?; + let line = state.source_tail(line_start + offset)?.lines().next()?; let start = line.find('[')? + 1; let end = line.rfind(']')?; let source = line.get(start..end)?; diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 57b94902a..b3c9bf874 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -50,6 +50,7 @@ use crate::{ references::{ParsedSectionHeader, register_section_header}, revision::{IgnoredRevisionFields, RevisionInfo, process_revision_info}, sections::{apply_leveloffset, expected_child_level}, + source::{SourceLine, ordinary_kind}, table::{ InitialAttributes, PreparedTableCellParagraph, TableClosing, TableParseParams, parse_table_block_impl, @@ -117,6 +118,57 @@ peg::parser! { { trailing.transpose().map(|blocks| BlockStep::end(blocks.unwrap_or_default(), end)) } ) { step } + // Read-only line probes share the actual block recognizers. The source + // driver uses them to collect one unit, then constructs that unit once. + pub(in crate::grammar::document) rule source_line() -> SourceLine<'input> + = eol() { SourceLine::Blank } + / document_attribute_match() (eol() / ![_]) { SourceLine::Attribute } + / comment_line_prefix() source_line_tail() { SourceLine::Comment } + / &atx_heading_match() source_line_tail() { SourceLine::Heading } + / open:block_open() (eol() / ![_]) { SourceLine::Delimited { delimiter: open.1, table: false, comment: matches!(open.0, DelimitedKind::Comment) } } + / delimiter:table_delimiter() (eol() / ![_]) { SourceLine::Delimited { delimiter, table: true, comment: false } } + / (attribute_or_anchor_line_match() / title_line_match()) { SourceLine::Metadata } + / extension_macro_source() (eol() / ![_]) { SourceLine::Macro } + / (media_block_ahead_true() / toc_block_ahead()) source_line_tail() { SourceLine::Macro } + / whitespace()* marker:unordered_list_marker() whitespace() text:$([^'\n']*) (eol() / ![_]) { SourceLine::List { kind: ordinary_kind(false), marker, empty: text.trim().is_empty() } } + / whitespace()* marker:ordered_list_marker() whitespace() text:$([^'\n']*) (eol() / ![_]) { SourceLine::List { kind: ordinary_kind(true), marker, empty: text.trim().is_empty() } } + / marker:callout_list_marker() whitespace() text:$([^'\n']*) (eol() / ![_]) { SourceLine::List { kind: ListKind::Callout, marker, empty: text.trim().is_empty() } } + / term:description_list_term_source() &(whitespace() / eol() / ![_]) text:$([^'\n']*) (eol() / ![_]) { SourceLine::List { kind: ListKind::Description, marker: term.delimiter, empty: text.trim().is_empty() } } + / "+" whitespace()* (eol() / ![_]) { SourceLine::Continuation } + / ">" &(whitespace() / eol() / ![_]) source_line_tail() { SourceLine::Markdown } + / "\"" source_line_tail() { SourceLine::Quoted } + / source_line_tail() { SourceLine::Text } + + rule source_line_tail() = [^'\n']* (eol() / ![_]) + + pub(in crate::grammar::document) rule source_block_close(expected: &str, table: bool) + = ({? table.then_some(()).ok_or("ordinary delimiter") }) + delimiter:table_delimiter() (eol() / ![_]) + {? (delimiter == expected).then_some(()).ok_or("different table delimiter") } + / block_close_delim(expected) (eol() / ![_]) + + pub(in crate::grammar::document) rule source_paragraph_boundary(offset: usize, parent: Option>) + = &(eol() / ![_] / paragraph_line_boundary(offset, parent)) source_line_tail() + + #[no_eof] + pub(in crate::grammar::document) rule source_principal_line(offset: usize, kind: ListKind<'input>, marker: &str) + = kind:unordered_kind(kind) unordered_list_principal_line(offset, marker, kind.parent_other) (eol() / ![_]) + / kind:ordered_kind(kind) ordered_list_principal_line(offset, marker, kind.parent_other) (eol() / ![_]) + / callout_kind(kind) callout_list_principal_line(offset) (eol() / ![_]) + / description_kind(kind) description_list_principal_line(offset) [^'\n']+ (eol() / ![_]) + + pub(in crate::grammar::document) rule source_setext_underline(width: usize) + = setext_section_level(width, None) (eol() / ![_]) + + pub(in crate::grammar::document) rule source_document_underline(width: usize) + = document_title_underline(width) (eol() / ![_]) + + pub(in crate::grammar::document) rule source_document_title() + = &atx_heading_prefix() document_title_token() whitespace() source_line_tail() + + pub(in crate::grammar::document) rule source_quoted_paragraph() + = quoted_paragraph_params(0, 0) (eol() / ![_]) + rule ordered_construction(mode: ConstructionMode) = {? matches!(mode, ConstructionMode::Ordered).then_some(()).ok_or("recursive construction") } @@ -443,7 +495,7 @@ peg::parser! { let sub_start_offset = start + colon_pos + 1 + sub_leading; let subtitle_start = PositionWithOffset { offset: sub_start_offset, - position: state.line_map.offset_to_position(sub_start_offset, state.input), + position: state.source_position(sub_start_offset), }; let sub_end = sub_start_offset + subtitle_text.len(); let (subtitle_inlines, _) = process_inlines(state, &block_metadata, subtitle_start.offset, sub_end, 0, subtitle_text) @@ -474,14 +526,22 @@ peg::parser! { /// /// The underline must be within one character of the title width. /// Recognized in Asciidoctor mode. + rule document_title_underline(title_width: usize) + = underline:$("="+) &(eol() / ![_]) {? + if !setext::is_enabled(state.options.compatibility_mode) { + Err("setext mode not enabled") + } else if !setext::width_ok(title_width, underline.chars().count()) { + Err("underline width out of tolerance") + } else { + Ok(()) + } + } + rule document_title_setext() -> (Title<'input>, Option>) = title:setext_title_text() end:position!() eol() - underline:$("="+) &(eol() / ![_]) + document_title_underline(title.trim().chars().count()) {? - if !setext::is_document_title(state.options.compatibility_mode, title, underline) { - return Err("not a setext document title"); - } - + let title_text = title.trim(); tracing::debug!("Processing setext document title"); let block_metadata = BlockParsingMetadata::new(state.options.compatibility_mode); @@ -503,7 +563,7 @@ peg::parser! { let sub_start_offset = span_start + colon_pos + 1 + sub_leading; let subtitle_start = PositionWithOffset { offset: sub_start_offset, - position: state.line_map.offset_to_position(sub_start_offset, state.input), + position: state.source_position(sub_start_offset), }; let sub_end = sub_start_offset + subtitle_text.len(); let (subtitle_inlines, _) = process_inlines(state, &block_metadata, subtitle_start.offset, sub_end, 0, subtitle_text) @@ -1243,7 +1303,7 @@ peg::parser! { state.options.compatibility_mode, ); } - let image_ahead = media_ahead && state.input.get(block_start + offset..).is_some_and(|tail| tail.starts_with("image::")); + let image_ahead = media_ahead && state.source_tail(block_start + offset).is_some_and(|tail| tail.starts_with("image::")); let image_alt = resolve_block_content_attributes(state, &mut attributes, media_attributes.as_deref(), image_ahead)?; // Titles use the completed metadata attributes, including entries // after the title line. Only the last authored title is displayed. @@ -1370,7 +1430,7 @@ peg::parser! { let absolute_pos = pos + offset; let at_line_start = absolute_pos == 0 || { let prev_byte_pos = absolute_pos.saturating_sub(1); - state.input.as_bytes().get(prev_byte_pos).is_some_and(|&b| b == b'\n') + state.source_byte(prev_byte_pos).is_some_and(|b| b == b'\n') }; if !at_line_start { @@ -1809,10 +1869,15 @@ peg::parser! { } else { Err("registered block macro") } } - rule extension_macro(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + rule extension_macro_source() -> (&'input str, &'input str, &'input str, usize) = name:registered_macro_name() target:$([^'[' | '\n' | '\r']*) - "[" arguments:attribute_list_content(BlockAttributeMode::Macro) end:position!() trailing:$([^'\n']*) { - if !trailing.trim().is_empty() { + "[" arguments:attribute_list_content(BlockAttributeMode::Macro) end:position!() trailing:$([^'\n']*) + { (name, target, arguments, end) } + + rule extension_macro(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> + = source:extension_macro_source() { + let (name, target, arguments, end) = source; + if state.source_slice(end + offset..span_end + offset).is_some_and(|trailing| !trailing.trim().is_empty()) { state.add_warning(Warning::new(WarningKind::ContentRecovery { message: format!("trailing content after block macro {name}").into() }, Some(state.create_error_source_location(state.create_location(end + offset, span_end + offset))))); } crate::extensions::recognize(state, name, target, arguments, block_metadata.metadata.clone(), block_metadata.title.clone(), state.create_block_location(start, end, offset)) @@ -2177,7 +2242,7 @@ peg::parser! { rule nested_list_metadata(offset: usize, parent_section_level: Option) -> Result, Error> = meta_start:position!() lines:(line:( anchor:anchor(offset) { AttributeOrAnchorLine::Anchor(anchor) } - / attr:attributes_line() { AttributeOrAnchorLine::Attributes(Box::new(attr)) } + / attr:attributes_line_at(offset) { AttributeOrAnchorLine::Attributes(Box::new(attr)) } ) end:position!() eol()* { (line, end) })+ { let mut attributes = ParsedAttributeList::default(); @@ -2220,7 +2285,15 @@ peg::parser! { rule anchor_line_match() = double_open_square_bracket() [^'\'' | ',' | ']' | '[' | ' ' | '\t' | '\n' | '\r']+ - (comma() block_anchor_reftext(0) / double_close_square_bracket()) (eol() / ![_]) + (comma() block_anchor_reftext_match() / double_close_square_bracket()) (eol() / ![_]) + + rule block_anchor_reftext_match() + = text:$([^'\n' | '\r']+) {? + text.strip_suffix("]]") + .and_then(|source| resolve_block_anchor_reftext(source, &state.document_attributes, state.options.compatibility_mode)) + .map(|_| ()) + .ok_or("block anchor reference text") + } rule attribute_or_anchor_line_match() = anchor_line_match() / attributes_line_match() @@ -2252,8 +2325,8 @@ peg::parser! { rule enter_ordinary_list(offset: usize, unordered: Option<&'input str>, ordered: Option<&'input str>) -> Option> = { let parent = state.ordinary_list_scope; - let mut scope = parent.filter(|scope| scope.offset == offset) - .unwrap_or(OrdinaryListScope { offset, ..OrdinaryListScope::default() }); + let mut scope = parent.filter(|scope| scope.offset == state.list_scope_offset(offset)) + .unwrap_or(OrdinaryListScope { offset: state.list_scope_offset(offset), ..OrdinaryListScope::default() }); scope.unordered = unordered.or(scope.unordered); scope.ordered = ordered.or(scope.ordered); if let Some(marker) = unordered { @@ -2267,7 +2340,7 @@ peg::parser! { } rule ordinary_list_scope(offset: usize) -> OrdinaryListScope<'input> - = { state.ordinary_list_scope.filter(|scope| scope.offset == offset).unwrap_or_default() } + = { state.ordinary_list_scope.filter(|scope| scope.offset == state.list_scope_offset(offset)).unwrap_or_default() } rule ordinary_list_marker() -> ListMarker<'input> = whitespace()* marker:unordered_list_marker() whitespace() { ListMarker::Unordered(marker) } @@ -2337,7 +2410,10 @@ peg::parser! { / whitespace()* "[" whitespace()* "]" whitespace()* (&eol() / ![_]) // Empty block attributes rule unordered_list_principal_continuation(offset: usize, current_marker: &str, parent_ordered_marker: Option<&'input str>) -> &'input str - = eol() + = eol() line:unordered_list_principal_line(offset, current_marker, parent_ordered_marker) { line } + + rule unordered_list_principal_line(offset: usize, current_marker: &str, parent_ordered_marker: Option<&'input str>) -> &'input str + = !( &eol() / &at_list_item_start() @@ -2350,7 +2426,10 @@ peg::parser! { line:$((!eol() [_])*) { line } rule ordered_list_principal_continuation(offset: usize, current_marker: &str, parent_unordered_marker: Option<&'input str>) -> &'input str - = eol() + = eol() line:ordered_list_principal_line(offset, current_marker, parent_unordered_marker) { line } + + rule ordered_list_principal_line(offset: usize, current_marker: &str, parent_unordered_marker: Option<&'input str>) -> &'input str + = !( &eol() / &at_list_item_start() @@ -2832,7 +2911,7 @@ peg::parser! { // markers in reparsed delimited blocks outside this boundary. rule at_callout_parent_item(offset: usize) = at_callout_list_item() {? - (state.callout_list_offset == Some(offset)).then_some(()).ok_or("not a callout parent") + (state.callout_list_offset == Some(state.list_scope_offset(offset))).then_some(()).ok_or("not a callout parent") } // Save the enclosing scope for callout_list to restore after parsing its @@ -2840,7 +2919,7 @@ peg::parser! { // since child listings add their own references to the shared catalog. rule enter_callout_list(offset: usize) -> CalloutScope = { - let parent = state.callout_list_offset.replace(offset); + let parent = state.callout_list_offset.replace(state.list_scope_offset(offset)); (parent, std::mem::take(&mut state.pending_callouts)) } @@ -2951,11 +3030,7 @@ peg::parser! { // Stop at list markers, explicit continuations, blank lines, or block attributes. continuation_lines:( eol() - !at_callout_list_item() - !check_line_is_description_list(offset) - !(whitespace()* (unordered_list_marker() / ordered_list_marker() / "[" / "+" whitespace()* eol() / eol())) - line:$((!(eol()) [_])*) - { line } + line:callout_list_principal_line(offset) { line } )* first_line_end:position!() principal:list_item_principal(offset, block_metadata, first_line_start, first_line_end, first_line, &continuation_lines) @@ -2966,6 +3041,12 @@ peg::parser! { } } + rule callout_list_principal_line(offset: usize) -> &'input str + = !at_callout_list_item() + !check_line_is_description_list(offset) + !(whitespace()* (unordered_list_marker() / ordered_list_marker() / "[" / "+" whitespace()* eol() / eol())) + line:$((!eol() [_])*) { line } + rule unordered_list_head(offset: usize, metadata: &BlockParsingMetadata<'input>, marker: &'input str, item_start: usize, empty_start: usize, parent_ordered_marker: Option<&'input str>) -> ListItemHead<'input> = whitespace() checked:checklist_item()? @@ -3015,7 +3096,7 @@ peg::parser! { rule check_line_is_description_list(offset: usize) = pos:position!() {? - if find_dlist_marker(state.input.as_bytes(), pos + offset) { + if state.source_tail(pos + offset).is_some_and(|tail| find_dlist_marker(tail.as_bytes(), 0)) { Ok(()) } else { Err("no dlist marker on current line") @@ -3026,7 +3107,7 @@ peg::parser! { = at_description_scope_item(offset, state.description_list_scope) rule at_description_scope_item(offset: usize, parent: Option>) - = scope:({? parent.filter(|scope| scope.offset == offset).ok_or("no description parent") }) + = scope:({? parent.filter(|scope| scope.offset == state.list_scope_offset(offset)).ok_or("no description parent") }) (!(description_list_marker() (eol() / " " / ![_]) / eol()) [_])+ marker:description_list_marker() &(eol() / " " / ![_]) {? scope.contains(marker).then_some(()).ok_or("not a description parent item") @@ -3035,8 +3116,8 @@ peg::parser! { rule enter_description_list(offset: usize) -> Option> = { let parent = state.description_list_scope; - state.description_list_scope = Some(parent.filter(|scope| scope.offset == offset) - .unwrap_or_else(|| DescriptionListScope::new(offset))); + state.description_list_scope = Some(parent.filter(|scope| scope.offset == state.list_scope_offset(offset)) + .unwrap_or_else(|| DescriptionListScope::new(state.list_scope_offset(offset)))); parent } @@ -3225,7 +3306,7 @@ peg::parser! { // A blank line before `+` returns from a nested description to its ordinary parent. rule description_continuation_gap(offset: usize) = gap:$(eol()*) {? - (gap.is_empty() || state.ordinary_list_scope.is_none_or(|scope| scope.offset != offset)) + (gap.is_empty() || state.ordinary_list_scope.is_none_or(|scope| scope.offset != state.list_scope_offset(offset))) .then_some(()).ok_or("continuation belongs to ordinary parent") } @@ -3387,7 +3468,7 @@ peg::parser! { } }) candidate:attached_list_marker() {? let open_list_item = state.ordinary_list_scope - .filter(|scope| scope.offset == offset) + .filter(|scope| scope.offset == state.list_scope_offset(offset)) .is_some_and(|scope| scope.open.contains(candidate)); (parent.is_sibling_or_ancestor(candidate) || parent.same_ordinary_list(candidate) || open_list_item) .then_some(()).ok_or("not a sibling list item") @@ -3409,6 +3490,24 @@ peg::parser! { } }} + rule paragraph_line_boundary(offset: usize, parent_marker: Option>) + = excessive_list_marker() + / &raw_attributes_line() + / &anchor_line_match() + / example_delimiter() &(eol() / ![_]) + / listing_delimiter() + / literal_delimiter() + / sidebar_delimiter() + / quote_delimiter() + / pass_delimiter() + / table_delimiter() + / markdown_code_delimiter() + / comment_delimiter() + / open_delimiter() &(whitespace()* eol()) + / at_callout_parent_item(offset) + / attached_list_boundary(offset, parent_marker) + / &("+" whitespace()* (eol() / ![_])) // Only a standalone plus continues a list. + rule paragraph_with_list_boundary(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>, parent_marker: Option>) -> Result, Error> = admonition:(structural_block_boundaries(block_metadata) value:admonition() { value })? content_start:position!() @@ -3422,22 +3521,7 @@ peg::parser! { / !( eol()*<2,> / eol()* ![_] - / eol() &attributes_line() - / eol() &anchor_line_match() - / eol() example_delimiter() &(eol() / ![_]) - / eol() listing_delimiter() - / eol() literal_delimiter() - / eol() sidebar_delimiter() - / eol() quote_delimiter() - / eol() pass_delimiter() - / eol() table_delimiter() - / eol() markdown_code_delimiter() - / eol() comment_delimiter() - / eol() open_delimiter() &(whitespace()* eol()) - / eol() excessive_list_marker() - / eol() at_callout_parent_item(offset) - / eol() attached_list_boundary(offset, parent_marker) - / eol() &("+" whitespace()* (eol() / ![_])) // Only a standalone plus continues a list. + / eol() paragraph_line_boundary(offset, parent_marker) ) [_] )+)) { @@ -3583,10 +3667,13 @@ peg::parser! { } rule attributes_line() -> ParsedAttributeList<'input> + = attributes_line_at(0) + + rule attributes_line_at(offset: usize) -> ParsedAttributeList<'input> // Don't match empty [] followed by blank line - that's a list separator, not // block attributes. Without this, `[]\n\n` would be parsed as an empty // attributes line, breaking list separation - = !empty_list_separator() attributes:attributes() eol() { + = !empty_list_separator() attributes:attributes_at(offset) eol() { attributes } @@ -3602,6 +3689,9 @@ peg::parser! { = whitespace()* "[" whitespace()* "]" whitespace()* eol() eol() pub(in crate::grammar::document) rule attributes() -> ParsedAttributeList<'input> + = attributes_at(0) + + rule attributes_at(offset: usize) -> ParsedAttributeList<'input> = block_attribute_start() open_square_bracket() content_start:position!() @@ -3612,7 +3702,7 @@ peg::parser! { content, content_start, BlockAttributeMode::Block, - 0, + offset, ).map_err(|_| "cannot map block attribute locations") } @@ -3715,8 +3805,7 @@ peg::parser! { {? let inline_state = InlinePreprocessorParserState::new_all_enabled( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, ); let processed = inline_preprocessing::run(path, &state.document_attributes, &inline_state) @@ -3758,8 +3847,7 @@ peg::parser! { {? let inline_state = InlinePreprocessorParserState::new_all_enabled( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, ); let processed = inline_preprocessing::run(path, &state.document_attributes, &inline_state) @@ -3815,8 +3903,7 @@ peg::parser! { {? let inline_state = InlinePreprocessorParserState::new_all_enabled( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, ); let processed = inline_preprocessing::run(path, &state.document_attributes, &inline_state) @@ -3934,7 +4021,7 @@ peg::parser! { rule position() -> PositionWithOffset = offset:position!() { PositionWithOffset { offset, - position: state.line_map.offset_to_position(offset, state.input) + position: state.source_position(offset) } } diff --git a/acdc-parser/src/grammar/document/source.rs b/acdc-parser/src/grammar/document/source.rs new file mode 100644 index 000000000..410b1d8b1 --- /dev/null +++ b/acdc-parser/src/grammar/document/source.rs @@ -0,0 +1,688 @@ +//! Cooperate with the reader between committed construction steps. + +use std::{cell::RefCell, rc::Rc}; + +use crate::{ + AttributeName, Block, Document, DocumentAttributeAssignment, Error, + document_attribute::{AttributeDeclaration, RawAttributeValue}, + grammar::{ParserState, source::SourceIndex}, + preprocessor::{PreprocessorResult, SourceReader}, +}; + +use super::{ + construction::ConstructionMode, + coordinator::{BlockCursor, Execution}, + document_parser, + input::{BlockInput, ReadRequest}, + lists::{ListKind, ListPhase, OrdinaryListKind}, +}; + +type Assignments<'a> = Vec<(AttributeName<'a>, DocumentAttributeAssignment<'a>)>; +type PendingAssignments = Rc>>; + +/// A1's private execution seam. Public Registry callbacks retain their +/// existing post-acceptance timing until the A2 context contract is introduced. +pub(crate) trait SourceHandler { + fn accepted<'a>( + &mut self, + block: &Block<'a>, + state: &ParserState<'a>, + ) -> Result, Error>; +} + +#[derive(Clone, Copy)] +pub(super) enum SourceLine<'a> { + Blank, + Attribute, + Metadata, + Comment, + Heading, + Delimited { + delimiter: &'a str, + table: bool, + comment: bool, + }, + List { + kind: ListKind<'a>, + marker: &'a str, + empty: bool, + }, + Macro, + Markdown, + Quoted, + Continuation, + Text, +} + +pub(super) fn ordinary_kind(ordered: bool) -> ListKind<'static> { + let kind = OrdinaryListKind { + parent_other: None, + parent_same: None, + allow_continuation: true, + has_own_metadata: true, + }; + if ordered { + ListKind::Ordered(kind) + } else { + ListKind::Unordered(kind) + } +} + +struct SourceStart<'a> { + offset: usize, + line: &'a str, + form: SourceLine<'a>, + verbatim: bool, +} + +pub(super) struct SourceInput<'a> { + reader: Option>, + pub(super) index: Rc>, + pub(super) result: Option>, + updates: PendingAssignments, +} + +impl<'a> SourceInput<'a> { + fn new( + reader: SourceReader<'a>, + updates: PendingAssignments, + index: Rc>, + ) -> Self { + Self { + reader: Some(reader), + index, + result: None, + updates, + } + } + + fn line( + &mut self, + offset: usize, + state: &mut ParserState<'a>, + ) -> Result, Error> { + loop { + if offset < self.index.len() { + let tail = self + .index + .tail(offset) + .ok_or_else(|| source_error(state, offset, "missing emitted source line"))?; + let end = tail.find('\n').map_or(tail.len(), |end| end + 1); + return Ok(tail.get(..end)); + } + let Some(reader) = self.reader.as_mut() else { + return Ok(None); + }; + for (name, assignment) in self.updates.borrow_mut().drain(..) { + let value = match assignment { + DocumentAttributeAssignment::Set(value) => RawAttributeValue::Resolved(value), + DocumentAttributeAssignment::Unset => RawAttributeValue::Unset, + }; + reader + .options + .document_attributes + .assign_document_value(name, value, false, false, None)?; + } + if let Some(chunk) = reader.next()? { + if chunk.start != self.index.len() { + return Err(source_error( + state, + offset, + "reader emitted noncontiguous source", + )); + } + self.index.append(chunk.text); + state.source_ranges.extend(chunk.source_ranges); + state.leveloffset_ranges.extend(chunk.leveloffset_ranges); + state.leveloffset_scopes.extend(chunk.leveloffset_scopes); + } else { + let reader = self + .reader + .take() + .ok_or_else(|| source_error(state, offset, "missing source reader at EOF"))?; + let result = reader.finish()?; + self.index.seal(result.text.len()); + self.result = Some(result); + } + } + } + + fn kind(line: &'a str, state: &mut ParserState<'a>) -> SourceLine<'a> { + // Classification is read-only and shares the document grammar's raw + // recognizers. Only the accepted construction pass builds inline nodes. + document_parser::source_line(line, state).unwrap_or(SourceLine::Text) + } + + fn scan( + &mut self, + start: usize, + request: ReadRequest<'a>, + state: &mut ParserState<'a>, + ) -> Result { + let Some(unit) = self.block_start(start, request, state)? else { + return Ok(self.index.len()); + }; + let offset = unit.offset + unit.line.len(); + if let SourceLine::Delimited { + delimiter, table, .. + } = unit.form + { + return self.delimited_end(offset, delimiter, table, state); + } + if !unit.verbatim { + match unit.form { + SourceLine::Continuation + if matches!( + request, + ReadRequest::ListNext(_, _, ListPhase::AfterPrincipal) + ) => + { + return Ok(offset); + } + SourceLine::Attribute => return self.attribute_end(unit.offset, unit.line, state), + SourceLine::Comment | SourceLine::Heading | SourceLine::Macro => return Ok(offset), + SourceLine::List { + kind, + marker, + empty, + } => { + let kind = match request { + ReadRequest::ListHead(kind) => kind, + ReadRequest::Block | ReadRequest::ListNext(..) | ReadRequest::ListEnd => { + kind + } + }; + return self.principal_end(start..offset, (kind, marker, empty), state); + } + SourceLine::Markdown => return self.markdown_end(offset, state), + SourceLine::Quoted => { + if let Some(end) = self.quoted_end(start, &unit, state)? { + return Ok(end); + } + } + SourceLine::Blank + | SourceLine::Metadata + | SourceLine::Continuation + | SourceLine::Text + | SourceLine::Delimited { .. } => {} + } + } + self.paragraph_end(offset, unit.line, unit.verbatim, request, state) + } + + fn block_start( + &mut self, + start: usize, + request: ReadRequest<'a>, + state: &mut ParserState<'a>, + ) -> Result>, Error> { + let mut offset = start; + let mut style = None; + let mut pending_metadata = false; + let control = matches!( + request, + ReadRequest::ListNext(_, _, ListPhase::Attachments | ListPhase::Sibling) + | ReadRequest::ListEnd + ); + loop { + let Some(line) = self.line(offset, state)? else { + return Ok(None); + }; + let form = Self::kind(line, state); + if (pending_metadata || control) + && let SourceLine::Delimited { + delimiter, + table, + comment: true, + } = form + { + offset = self.delimited_end(offset + line.len(), delimiter, table, state)?; + continue; + } + if matches!(form, SourceLine::Blank | SourceLine::Metadata) + || pending_metadata && matches!(form, SourceLine::Attribute | SourceLine::Comment) + || control + && matches!( + form, + SourceLine::Continuation | SourceLine::Comment | SourceLine::Attribute + ) + { + pending_metadata |= matches!(form, SourceLine::Metadata); + if let Some(list) = crate::grammar::block_attribute_line( + line.trim_end_matches('\n'), + &state.document_attributes, + state.options.compatibility_mode, + ) && let Some(selected) = crate::grammar::block_attribute_style( + list, + &state.document_attributes, + state.options.compatibility_mode, + ) { + style = Some(selected); + } + offset = if matches!(form, SourceLine::Attribute) { + self.attribute_end(offset, line, state)? + } else { + offset + line.len() + }; + } else { + let verbatim = crate::grammar::style_overrides_block_form( + state.options.compatibility_mode, + style.as_deref(), + ); + return Ok(Some(SourceStart { + offset, + line, + form, + verbatim, + })); + } + } + } + + fn attribute_end( + &mut self, + start: usize, + first: &'a str, + state: &mut ParserState<'a>, + ) -> Result { + let mut end = start + first.len(); + let mut continued = first.trim_end_matches('\n').ends_with(" \\"); + // A wrap owns the next nonblank line even when it resembles a block opener. + while continued { + let Some(line) = self.line(end, state)? else { + break; + }; + if line.trim().is_empty() { + break; + } + end += line.len(); + continued = line.trim().ends_with(" \\"); + } + Ok(end.min(self.index.len())) + } + + fn delimited_end( + &mut self, + mut offset: usize, + delimiter: &str, + table: bool, + state: &mut ParserState<'a>, + ) -> Result { + while let Some(next) = self.line(offset, state)? { + offset += next.len(); + if document_parser::source_block_close(next, state, delimiter, table).is_ok() { + break; + } + } + Ok(offset.min(self.index.len())) + } + + fn metadata_end( + &mut self, + mut offset: usize, + state: &mut ParserState<'a>, + ) -> Result { + while let Some(ahead) = self.line(offset, state)? { + offset += ahead.len(); + match Self::kind(ahead, state) { + SourceLine::Delimited { + delimiter, + table, + comment: true, + } => { + offset = self.delimited_end(offset, delimiter, table, state)?; + } + SourceLine::Metadata | SourceLine::Comment | SourceLine::Blank => {} + SourceLine::Attribute => { + offset = self.attribute_end(offset - ahead.len(), ahead, state)?; + break; + } + SourceLine::Heading + | SourceLine::Delimited { .. } + | SourceLine::List { .. } + | SourceLine::Macro + | SourceLine::Markdown + | SourceLine::Quoted + | SourceLine::Continuation + | SourceLine::Text => break, + } + } + Ok(offset.min(self.index.len())) + } + + fn principal_end( + &mut self, + range: std::ops::Range, + principal: (ListKind<'a>, &'a str, bool), + state: &mut ParserState<'a>, + ) -> Result { + let (kind, marker, empty) = principal; + let mut offset = range.end; + let mut missing_principal = empty && matches!(kind, ListKind::Description); + let mut metadata_end = 0; + while let Some(next) = self.line(offset, state)? { + let next_start = offset; + let next_form = Self::kind(next, state); + offset += next.len(); + if missing_principal && matches!(next_form, SourceLine::Blank) { + continue; + } + missing_principal = false; + let mut probe = next; + if matches!(next_form, SourceLine::Metadata) { + if metadata_end <= offset { + metadata_end = self.metadata_end(offset, state)?; + } + let view = self + .index + .window(range.start..metadata_end, state.arena) + .ok_or_else(|| { + source_error(state, next_start, "missing list principal lookahead") + })?; + probe = view.get(next_start..metadata_end).ok_or_else(|| { + source_error(state, next_start, "missing list metadata lookahead") + })?; + } + if document_parser::source_principal_line(probe, state, next_start, kind, marker) + .is_err() + { + offset = offset.max(metadata_end); + break; + } + } + Ok(offset.min(self.index.len())) + } + + fn markdown_end( + &mut self, + mut offset: usize, + state: &mut ParserState<'a>, + ) -> Result { + while let Some(next) = self.line(offset, state)? { + offset += next.len(); + if !matches!(Self::kind(next, state), SourceLine::Markdown) { + break; + } + } + Ok(offset.min(self.index.len())) + } + + fn quoted_end( + &mut self, + start: usize, + unit: &SourceStart<'a>, + state: &mut ParserState<'a>, + ) -> Result, Error> { + let mut offset = unit.offset + unit.line.len(); + let mut closed = unit.line.get(1..).is_some_and(|line| line.contains('"')); + while !closed { + let Some(next) = self.line(offset, state)? else { + break; + }; + offset += next.len(); + closed = next.contains('"'); + } + if closed && let Some(next) = self.line(offset, state)? { + offset += next.len(); + if let Some(view) = self.index.window(start..offset, state.arena) + && let Some(source) = view.get(unit.offset..offset) + && document_parser::source_quoted_paragraph(source, state).is_ok() + { + return Ok(Some(offset)); + } + } + // An invalid shorthand quote remains available as an ordinary paragraph. + Ok(None) + } + + fn paragraph_end( + &mut self, + mut offset: usize, + line: &'a str, + verbatim: bool, + request: ReadRequest<'a>, + state: &mut ParserState<'a>, + ) -> Result { + let parent = match request { + ReadRequest::ListNext(ListKind::Unordered(_), marker, _) => { + Some(super::lists::ListMarker::Unordered(marker)) + } + ReadRequest::ListNext(ListKind::Ordered(_), marker, _) => { + Some(super::lists::ListMarker::Ordered(marker)) + } + ReadRequest::ListNext(ListKind::Description, marker, _) => { + Some(super::lists::ListMarker::Description(marker)) + } + ReadRequest::Block + | ReadRequest::ListHead(_) + | ReadRequest::ListNext(ListKind::Callout, ..) + | ReadRequest::ListEnd => None, + }; + let mut first = true; + while let Some(next) = self.line(offset, state)? { + let next_start = offset; + offset += next.len(); + if first + && !verbatim + && crate::grammar::setext::is_title(line.trim_end_matches('\n')) + && document_parser::source_setext_underline( + next, + state, + line.trim().chars().count(), + ) + .is_ok() + { + break; + } + first = false; + if (verbatim + && matches!( + Self::kind(next, state), + SourceLine::Blank | SourceLine::Continuation + )) + || (!verbatim + && document_parser::source_paragraph_boundary(next, state, next_start, parent) + .is_ok()) + { + break; + } + } + Ok(offset.min(self.index.len())) + } + + pub(super) fn prepare_header(&mut self, state: &mut ParserState<'a>) -> Result<&'a str, Error> { + let mut offset = 0; + let mut title = false; + let mut header_started = false; + while let Some(line) = self.line(offset, state)? { + let kind = Self::kind(line, state); + offset = if matches!(kind, SourceLine::Attribute) { + self.attribute_end(offset, line, state)? + } else { + offset + line.len() + }; + if let SourceLine::Delimited { + delimiter, + table, + comment: true, + } = kind + { + while let Some(next) = self.line(offset, state)? { + offset += next.len(); + if document_parser::source_block_close(next, state, delimiter, table).is_ok() { + break; + } + } + continue; + } + if !title + && matches!(kind, SourceLine::Text) + && crate::grammar::setext::is_title(line.trim_end_matches('\n')) + && let Some(next) = self.line(offset, state)? + && document_parser::source_document_underline( + next, + state, + line.trim().chars().count(), + ) + .is_ok() + { + title = true; + offset += next.len(); + } + header_started |= title || matches!(kind, SourceLine::Attribute | SourceLine::Metadata); + if matches!(kind, SourceLine::Blank) && header_started { + break; + } + if document_parser::source_document_title(line, state).is_ok() { + title = true; + header_started = true; + } + if !title + && !matches!( + kind, + SourceLine::Attribute + | SourceLine::Metadata + | SourceLine::Comment + | SourceLine::Blank + ) + { + break; + } + } + let view = self + .index + .window(0..offset.min(self.index.len()), state.arena) + .ok_or_else(|| source_error(state, 0, "missing document prefix window"))?; + let source = view.input; + state.set_source_view(view); + Ok(source) + } +} + +impl<'a> BlockInput<'a> for SourceInput<'a> { + fn prepare( + &mut self, + cursor: &mut BlockCursor, + state: &mut ParserState<'a>, + request: ReadRequest<'a>, + ) -> Result<&'a str, Error> { + let start = cursor.base_offset + cursor.offset; + let end = self.scan(start, request, state)?; + let active = state.source_view(); + let view = if active.origin.as_ref().is_some_and(|origin| { + Rc::ptr_eq(&origin.index, &self.index) + && origin.base <= start + && end <= origin.base + active.input.len() + && origin.base + active.input.len() <= self.index.len() + }) { + active + } else { + self.index + .window(start..end, state.arena) + .ok_or_else(|| source_error(state, start, "missing accepted source window"))? + }; + let base = view.origin.as_ref().map_or(0, |origin| origin.base); + cursor.offset = start - base; + cursor.base_offset = base; + let source = view.input; + state.set_source_view(view); + Ok(source) + } +} + +fn source_error(state: &ParserState<'_>, offset: usize, message: &str) -> Error { + Error::Parse( + Box::new(state.create_error_source_location(state.create_location(offset, offset))), + message.into(), + ) +} + +fn recognition_error(mut error: super::RecognitionError, state: &ParserState<'_>) -> Error { + let source = crate::peg_error_to_source_location(&error, state); + let offset = state.input_offset(error.location.offset); + let position = state.source_position(offset); + error.location.offset = offset; + error.location.line = position.line as usize; + error.location.column = position.column as usize; + Error::Parse(Box::new(source), error.to_string()) +} + +pub(crate) fn document_from_source<'a>( + reader: SourceReader<'a>, + state: &mut ParserState<'a>, + handler: &mut dyn SourceHandler, + finish_source: impl FnOnce(String) -> &'a str, +) -> Result<(Document<'a>, Vec), Error> { + let updates = PendingAssignments::default(); + let index = state + .input_origin + .as_ref() + .map_or_else(Rc::default, |origin| Rc::clone(&origin.index)); + let mut input = SourceInput::new(reader, Rc::clone(&updates), index); + state.set_source_view( + input + .index + .window(0..0, state.arena) + .ok_or_else(|| source_error(state, 0, "missing initial source window"))?, + ); + state.source_scope_offset = 0; + let source = input.prepare_header(state)?; + let prefix = document_parser::document_prefix(source, state) + .map_err(|error| recognition_error(error, state))??; + let mut cursor = BlockCursor::new(prefix.body_offset, ConstructionMode::Ordered); + let mut blocks = prefix.comments; + let mut callback = |block: &Block<'a>, state: &mut ParserState<'a>| { + for (name, assignment) in handler.accepted(block, state)? { + let name = state.intern_cow(name); + let value = match assignment { + DocumentAttributeAssignment::Set(value) => RawAttributeValue::Resolved(value), + DocumentAttributeAssignment::Unset => RawAttributeValue::Unset, + }; + if let Some(event) = state.apply_document_attribute( + &AttributeDeclaration { + name, + value, + ignored_value: None, + }, + false, + block.location().clone(), + ) && state.nested_parent_attributes.is_none() + { + updates.borrow_mut().push(( + name.to_owned().into(), + event.assignment().clone().into_static(), + )); + } + } + Ok(()) + }; + let end = cursor + .collect( + &mut input, + state, + &mut blocks, + &mut Execution::new(&mut callback), + ) + .map_err(|error| recognition_error(error, state))??; + let result = input + .result + .take() + .ok_or_else(|| source_error(state, end, "document ended before source exhaustion"))?; + let source = finish_source(result.text.into_owned()); + state.input = source; + state.input_origin = None; + state.source_scope_offset = 0; + state.line_map = Rc::new(crate::grammar::LineMap::new(source)); + state.source_ranges = result.source_ranges; + state.leveloffset_ranges = result.leveloffset_ranges; + state.included_files = result.included_files; + let document = super::finish::finish( + state, + prefix.start, + end, + prefix.header, + prefix.attributes, + blocks, + )?; + Ok((document, result.conditionals)) +} diff --git a/acdc-parser/src/grammar/document/table.rs b/acdc-parser/src/grammar/document/table.rs index b78d1607b..e61e1c5a3 100644 --- a/acdc-parser/src/grammar/document/table.rs +++ b/acdc-parser/src/grammar/document/table.rs @@ -745,6 +745,10 @@ fn parse_table_cell_with_parser<'a>( let outer_reftext = state.body_reftext_source; let outer_context = std::mem::replace(&mut state.block_context, BlockContext::Document); let outer_toc_len = state.toc_entries.len(); + let outer_scope = state.source_scope_offset; + if state.input_origin.is_some() { + state.source_scope_offset = cell_start_offset; + } let outer_pending_callouts = std::mem::take(&mut state.pending_callouts); initial_attributes = crate::document_attribute::initialize_nested_attributes(Rc::make_mut( @@ -768,6 +772,7 @@ fn parse_table_cell_with_parser<'a>( state.body_reftext_source = outer_reftext; state.block_context = outer_context; state.toc_entries.truncate(outer_toc_len); + state.source_scope_offset = outer_scope; state.pending_callouts = outer_pending_callouts; result } else { diff --git a/acdc-parser/src/grammar/inline_preprocessor.rs b/acdc-parser/src/grammar/inline_preprocessor.rs index 05672333f..e333ecfec 100644 --- a/acdc-parser/src/grammar/inline_preprocessor.rs +++ b/acdc-parser/src/grammar/inline_preprocessor.rs @@ -14,17 +14,13 @@ use std::{ cell::{Cell, RefCell}, mem::take, ops::Range, - rc::Rc, }; use crate::{ DocumentAttributes, Error, Location, Passthrough, PassthroughKind, Position, SourceLocation, Substitution, Warning, WarningKind, document_attribute::reference_name_len, - grammar::{ - LineMap, - utf8_utils::{RoundDirection, step_char}, - }, + grammar::{source::SourceView, utf8_utils::RoundDirection}, model::substitution::parse_passthrough_substitutions, warning::WarningCollection, }; @@ -43,10 +39,8 @@ pub(crate) struct InlinePreprocessorParserState<'a> { pub(super) passthroughs: RefCell>>, /// Current byte offset in the full document input. pub(crate) current_offset: Cell, - /// Pre-computed line map for O(log n) offset→position lookups. - pub(crate) line_map: Rc, - /// Full document input (for `LineMap` position lookups). - full_input: &'a str, + /// Stable input and its local or document-wide coordinate context. + source: SourceView<'a>, /// Arena for interning synthesized passthrough strings produced during /// preprocessing (character-replacement expansions, escape-stripped text). pub(crate) arena: &'a Bump, @@ -72,15 +66,13 @@ impl<'a> InlinePreprocessorParserState<'a> { /// /// # Arguments /// * `input` - The substring to parse - /// * `line_map` - Pre-computed line map for the full document - /// * `full_input` - The full document input (for position lookups) + /// * `source` - Stable input and its position context /// * `arena` - Arena for interning synthesized strings /// * `macros_enabled` - Whether macro substitutions are active /// * `attributes_enabled` - Whether attribute substitutions are active - pub(crate) fn new( + pub(super) fn new( input: &'a str, - line_map: Rc, - full_input: &'a str, + source: SourceView<'a>, arena: &'a Bump, macros_enabled: bool, attributes_enabled: bool, @@ -89,8 +81,7 @@ impl<'a> InlinePreprocessorParserState<'a> { pass_found_count: Cell::new(0), passthroughs: RefCell::new(Vec::new()), current_offset: Cell::new(0), - line_map, - full_input, + source, arena, source_map: RefCell::new(SourceMap::default()), input: RefCell::new(input), @@ -104,13 +95,8 @@ impl<'a> InlinePreprocessorParserState<'a> { } /// Create a new state with all substitutions enabled (macros + attributes). - pub(super) fn new_all_enabled( - input: &'a str, - line_map: Rc, - full_input: &'a str, - arena: &'a Bump, - ) -> Self { - Self::new(input, line_map, full_input, arena, true, true) + pub(super) fn new_all_enabled(input: &'a str, source: SourceView<'a>, arena: &'a Bump) -> Self { + Self::new(input, source, arena, true, true) } fn recover_stem_substitutions(&self, source: &'a str, start: Position) -> String { @@ -194,8 +180,7 @@ impl<'a> InlinePreprocessorParserState<'a> { /// Get current position using `LineMap` lookup. fn get_position(&self) -> Position { - self.line_map - .offset_to_position(self.current_offset.get(), self.full_input) + self.source.position(self.current_offset.get()) } /// Get current byte offset. @@ -221,16 +206,12 @@ impl<'a> InlinePreprocessorParserState<'a> { /// Build an inclusive diagnostic span from a half-open source range. fn source_location_for(&self, start_offset: usize, end_offset: usize) -> SourceLocation { let end_offset = if start_offset < end_offset { - step_char(self.full_input, end_offset, RoundDirection::Backward) + self.source.step(end_offset, RoundDirection::Backward) } else { start_offset }; - let start = self - .line_map - .offset_to_position(start_offset, self.full_input); - let end = self - .line_map - .offset_to_position(end_offset, self.full_input); + let start = self.source.position(start_offset); + let end = self.source.position(end_offset); SourceLocation { file: None, location: Location { @@ -334,9 +315,7 @@ impl<'a> InlinePreprocessorParserState<'a> { while let Some(relative_start) = source[search_from..].find('+') { let start = search_from + relative_start; let previous = if start == 0 { - self.full_input[..source_start.saturating_sub(1)] - .chars() - .next_back() + self.source.previous_char(source_start.saturating_sub(1)) } else { source[..start].chars().next_back() }; @@ -514,12 +493,8 @@ impl<'a> InlinePreprocessorParserState<'a> { Location { absolute_start, absolute_end, - start: self - .line_map - .offset_to_position(absolute_start, self.full_input), - end: self - .line_map - .offset_to_position(absolute_end, self.full_input), + start: self.source.position(absolute_start), + end: self.source.position(absolute_end), } } diff --git a/acdc-parser/src/grammar/inline_preprocessor/tests.rs b/acdc-parser/src/grammar/inline_preprocessor/tests.rs index d17dee3ef..3ad0978e7 100644 --- a/acdc-parser/src/grammar/inline_preprocessor/tests.rs +++ b/acdc-parser/src/grammar/inline_preprocessor/tests.rs @@ -1,3 +1,5 @@ +use std::rc::Rc; + use super::*; use crate::{AttributeValue, DocumentAttributes}; @@ -28,8 +30,11 @@ fn setup_state(content: &str) -> InlinePreprocessorParserState<'_> { pass_found_count: Cell::new(0), passthroughs: RefCell::new(Vec::new()), current_offset: Cell::new(0), - line_map: Rc::new(LineMap::new(content)), - full_input: content, + source: SourceView { + input: content, + line_map: Rc::new(crate::grammar::LineMap::new(content)), + origin: None, + }, arena, source_map: RefCell::new(SourceMap::default()), input: RefCell::new(content), @@ -743,8 +748,11 @@ fn setup_state_macros_disabled(content: &str) -> InlinePreprocessorParserState<' pass_found_count: Cell::new(0), passthroughs: RefCell::new(Vec::new()), current_offset: Cell::new(0), - line_map: Rc::new(LineMap::new(content)), - full_input: content, + source: SourceView { + input: content, + line_map: Rc::new(crate::grammar::LineMap::new(content)), + origin: None, + }, arena, source_map: RefCell::new(SourceMap::default()), input: RefCell::new(content), diff --git a/acdc-parser/src/grammar/inline_processing.rs b/acdc-parser/src/grammar/inline_processing.rs index df48b3849..6055f77b1 100644 --- a/acdc-parser/src/grammar/inline_processing.rs +++ b/acdc-parser/src/grammar/inline_processing.rs @@ -5,7 +5,7 @@ use crate::{ SourceLocation, grammar::{ inline_preprocessor::{ProcessedKind, SourceMap}, - utf8_utils, + utf8_utils::RoundDirection, }, inline_preprocessing, model::{BibliographyLabel, SourceRange, Substitution, substitution::SubstitutionPlan}, @@ -172,20 +172,16 @@ fn adjust_peg_error_position( // Resolve file and line from source ranges (for included content) let (file, position) = if let Some(range) = SourceRange::find_containing(&state.source_ranges, absolute_offset) { - let doc_position = state - .line_map - .offset_to_position(absolute_offset, state.input); + let doc_position = state.source_position(absolute_offset); ( range.file.clone(), Position::new( - state.line_map.source_line(range, absolute_offset), + state.source_line(range, absolute_offset), doc_position.column, ), ) } else { - let doc_position = state - .line_map - .offset_to_position(absolute_offset, state.input); + let doc_position = state.source_position(absolute_offset); (state.current_file.as_deref().cloned(), doc_position) }; @@ -233,19 +229,13 @@ fn preprocess_inline_content<'a>( substitutions: SubstitutionPlan, ) -> Result<(Location, ProcessedContent<'a>), Error> { // First, ensure the end position is on a valid UTF-8 boundary - let mut adjusted_end = end + offset; - if adjusted_end > 0 && adjusted_end <= state.input.len() { - // If not on a boundary, round forward to the next valid boundary - while adjusted_end < state.input.len() && !state.input.is_char_boundary(adjusted_end) { - adjusted_end += 1; - } - } + let adjusted_end = state.source_snap(end + offset, RoundDirection::Forward); // We adjust the start and end positions to account for the content start offset let content_end_offset = if adjusted_end == 0 { 0 } else { - utf8_utils::safe_decrement_offset(state.input, adjusted_end) + state.source_step(adjusted_end, RoundDirection::Backward) }; let location = state.create_location(content_start + offset, content_end_offset); @@ -272,8 +262,7 @@ fn preprocess_inline_content<'a>( let mut inline_state = InlinePreprocessorParserState::new( content, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, substitutions.enabled(&Substitution::Macros), substitutions.enabled(&Substitution::Attributes), @@ -462,7 +451,7 @@ fn parse_inline_syntax<'a>( if text.contains("[[") || text.contains("anchor:") { inline_peg_state.reference_text_context = Some(Rc::new(super::reference_text::ReferenceTextContext { - input: state.input, + source: state.source_view(), passthroughs: processed.passthroughs.clone().into(), })); } @@ -579,11 +568,11 @@ fn late_attribute_sources<'a>( && pass.location.absolute_start == replacement.absolute_start && pass.location.absolute_end == replacement.absolute_end }); - if replacement.kind.is_attribute() || attribute_passthrough { - sources.push(( - expanded..expanded + replacement.byte_len, - &state.input[replacement.absolute_start..replacement.absolute_end], - )); + if (replacement.kind.is_attribute() || attribute_passthrough) + && let Some(source) = + state.source_slice(replacement.absolute_start..replacement.absolute_end) + { + sources.push((expanded..expanded + replacement.byte_len, source)); } expanded += replacement.byte_len; original = replacement.absolute_end; @@ -620,7 +609,7 @@ fn parse_bibliography_label<'a>( let Some(start) = location.absolute_start.checked_sub(1) else { return Ok(None); }; - let Some(anchor) = state.input.get(start..location.absolute_end + 2) else { + let Some(anchor) = state.source_slice(start..location.absolute_end + 2) else { return Ok(None); }; let Some(body) = anchor diff --git a/acdc-parser/src/grammar/inlines/peg.rs b/acdc-parser/src/grammar/inlines/peg.rs index 9698d8dd7..2a6c53a7f 100644 --- a/acdc-parser/src/grammar/inlines/peg.rs +++ b/acdc-parser/src/grammar/inlines/peg.rs @@ -1316,8 +1316,7 @@ peg::parser! { check_colon_link_label(start) {? let inline_state = InlinePreprocessorParserState::new_all_enabled( target, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, ); let processed = inline_preprocessing::run(target, &state.document_attributes, &inline_state) @@ -2486,8 +2485,7 @@ peg::parser! { // Inline text was already processed; attribute values must not introduce passthroughs. let inline_state = InlinePreprocessorParserState::new( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, matches!(state.scope, ParserScope::Document), true, @@ -2509,8 +2507,7 @@ peg::parser! { {? let inline_state = InlinePreprocessorParserState::new( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, matches!(state.scope, ParserScope::Document), true, @@ -2550,8 +2547,7 @@ peg::parser! { {? let inline_state = InlinePreprocessorParserState::new( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, matches!(state.scope, ParserScope::Document), true, @@ -2610,8 +2606,7 @@ peg::parser! { {? let inline_state = InlinePreprocessorParserState::new_all_enabled( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, ); let processed = inline_preprocessing::run(path, &state.document_attributes, &inline_state) @@ -2631,8 +2626,7 @@ peg::parser! { {? let inline_state = InlinePreprocessorParserState::new_all_enabled( path, - state.line_map.clone(), - state.input, + state.source_view(), state.arena, ); let processed = inline_preprocessing::run(path, &state.document_attributes, &inline_state) diff --git a/acdc-parser/src/grammar/location_mapping.rs b/acdc-parser/src/grammar/location_mapping.rs index 5236e5719..539d51f47 100644 --- a/acdc-parser/src/grammar/location_mapping.rs +++ b/acdc-parser/src/grammar/location_mapping.rs @@ -12,7 +12,7 @@ use super::{ character_references::{restore, whole}, marked_text::map_marked_text_locations, passthrough_processing::replace_passthrough_placeholders, - utf8_utils::{self, RoundDirection, snap_to_boundary}, + utf8_utils::RoundDirection, }; /// Clamp a Location's byte offsets to valid bounds within the input string @@ -20,18 +20,18 @@ use super::{ /// /// This only operates on `absolute_start/end` - the canonical byte offsets. /// `Position` fields (line/column) are not modified. -fn clamp_location_bounds(location: &mut Location, input: &str) { - let input_len = input.len(); +fn clamp_location_bounds(location: &mut Location, state: &ParserState<'_>) { + let input_len = state.source_len(); // Clamp to input bounds location.absolute_start = location.absolute_start.min(input_len); location.absolute_end = location.absolute_end.min(input_len); // Ensure start is on a valid UTF-8 boundary (round backward) - location.absolute_start = utf8_utils::ensure_char_boundary(input, location.absolute_start); + location.absolute_start = state.source_snap(location.absolute_start, RoundDirection::Backward); // Ensure end is on a valid UTF-8 boundary (round forward) - location.absolute_end = utf8_utils::ensure_char_boundary_forward(input, location.absolute_end); + location.absolute_end = state.source_snap(location.absolute_end, RoundDirection::Forward); // Ensure start <= end if location.absolute_start > location.absolute_end { @@ -40,9 +40,9 @@ fn clamp_location_bounds(location: &mut Location, input: &str) { } /// Recursively clamp all locations in an `InlineNode` to valid bounds. -pub(super) fn clamp_inline_node_locations(node: &mut InlineNode, input: &str) { +pub(super) fn clamp_inline_node_locations(node: &mut InlineNode, state: &ParserState<'_>) { super::location_walk::walk_inline_locations_mut(node, &mut |loc| { - clamp_location_bounds(loc, input); + clamp_location_bounds(loc, state); }); } @@ -67,11 +67,7 @@ impl<'a> LocationMappingContext<'_, 'a> { .processed .source_map .map_token_position(self.base_location.absolute_start + loc.absolute_start)?; - let start = snap_to_boundary( - self.state.input, - start.min(self.state.input.len()), - RoundDirection::Backward, - ); + let start = self.state.source_snap(start, RoundDirection::Backward); Ok(self.state.create_location(start, mapped.absolute_end)) } @@ -98,22 +94,17 @@ impl<'a> LocationMappingContext<'_, 'a> { let mut mapped_abs_end = processed.source_map.map_end_position(processed_abs_end)?; // Clamp to input bounds - preprocessor expansion can produce positions beyond input length - let input_len = state.input.len(); + let input_len = state.source_len(); mapped_abs_start = mapped_abs_start.min(input_len); mapped_abs_end = mapped_abs_end.min(input_len); // Ensure mapped positions are on valid UTF-8 boundaries - mapped_abs_start = - snap_to_boundary(state.input, mapped_abs_start, RoundDirection::Backward); - mapped_abs_end = snap_to_boundary(state.input, mapped_abs_end, RoundDirection::Forward); + mapped_abs_start = state.source_snap(mapped_abs_start, RoundDirection::Backward); + mapped_abs_end = state.source_snap(mapped_abs_end, RoundDirection::Forward); // Compute human positions from the document's line map - let start_pos = state - .line_map - .offset_to_position(mapped_abs_start, state.input); - let end_pos = state - .line_map - .offset_to_position(mapped_abs_end, state.input); + let start_pos = state.source_position(mapped_abs_start); + let end_pos = state.source_position(mapped_abs_end); Ok(Location { absolute_start: mapped_abs_start, @@ -147,12 +138,8 @@ pub(super) fn extend_attribute_location_if_needed( ); // Extend location to cover the full original attribute - let start_pos = state - .line_map - .offset_to_position(attr_replacement.absolute_start, state.input); - let end_pos = state - .line_map - .offset_to_position(attr_replacement.absolute_end, state.input); + let start_pos = state.source_position(attr_replacement.absolute_start); + let end_pos = state.source_position(attr_replacement.absolute_end); location = Location { absolute_start: attr_replacement.absolute_start, absolute_end: attr_replacement.absolute_end, @@ -428,7 +415,7 @@ fn map_anchor_locations<'a>( .location .absolute_start .checked_sub(1) - .and_then(|start| state.input.get(start..anchor.location.absolute_end + 2)) + .and_then(|start| state.source_slice(start..anchor.location.absolute_end + 2)) .and_then(|source| source.strip_prefix("[[[")) .and_then(|source| source.split_once("]]]").map(|(label, _)| label)) .and_then(|source| { diff --git a/acdc-parser/src/grammar/mod.rs b/acdc-parser/src/grammar/mod.rs index bdedcdebf..c7675f11e 100644 --- a/acdc-parser/src/grammar/mod.rs +++ b/acdc-parser/src/grammar/mod.rs @@ -22,6 +22,7 @@ mod passthrough_processing; pub(crate) mod reference_text; pub(crate) mod reference_walk; pub(crate) mod setext; +mod source; mod source_remap; mod state; mod utf8_utils; @@ -29,7 +30,9 @@ mod utf8_utils; pub(crate) use attributes::{ BlockAttributeMode, block_attribute_line, block_attribute_style, style_overrides_block_form, }; -pub(crate) use document::{document as parse_document, document_parser}; +pub(crate) use document::{ + SourceHandler, document as parse_document, document_from_source, document_parser, +}; pub(crate) use inline_preprocessor::{ InlinePreprocessorParserState, ProcessedContent, inline_preprocessing, }; diff --git a/acdc-parser/src/grammar/passthrough_processing.rs b/acdc-parser/src/grammar/passthrough_processing.rs index c1e442669..3456d4e53 100644 --- a/acdc-parser/src/grammar/passthrough_processing.rs +++ b/acdc-parser/src/grammar/passthrough_processing.rs @@ -1206,12 +1206,8 @@ fn raw_segment_location( } fn raw_source_start(raw: &Raw<'_>, state: &ParserState<'_>) -> Option { - let end = step_char( - state.input, - raw.location.absolute_end, - RoundDirection::Forward, - ); - let original = state.input.get(raw.location.absolute_start..end)?; + let end = state.source_step(raw.location.absolute_end, RoundDirection::Forward); + let original = state.source_slice(raw.location.absolute_start..end)?; let escapes = original.strip_suffix(raw.content)?; escapes .bytes() @@ -1353,12 +1349,8 @@ fn parse_raw_fragments<'a>( location.absolute_start = fragment_offset(location.absolute_start, &spans, false, state); location.absolute_end = fragment_offset(location.absolute_end, &spans, true, state); - location.start = state - .line_map - .offset_to_position(location.absolute_start, state.input); - location.end = state - .line_map - .offset_to_position(location.absolute_end, state.input); + location.start = state.source_position(location.absolute_start); + location.end = state.source_position(location.absolute_end); }); } for mut warning in warnings { @@ -1713,7 +1705,7 @@ pub(super) fn process_passthrough_placeholders<'a>( // Clamp all locations to valid bounds within the input string for node in &mut result { - clamp_inline_node_locations(node, state.input); + clamp_inline_node_locations(node, state); } // Merge adjacent plain text nodes @@ -1733,11 +1725,9 @@ fn merge_adjacent_plain_text_nodes<'a>( match (result.last_mut(), node) { (Some(InlineNode::PlainText(last_plain)), InlineNode::PlainText(current_plain)) if last_plain.escaped == current_plain.escaped - && step_char( - state.input, - last_plain.location.absolute_end, - RoundDirection::Forward, - ) == current_plain.location.absolute_start => + && state + .source_step(last_plain.location.absolute_end, RoundDirection::Forward) + == current_plain.location.absolute_start => { // Merge current plain text with the last one last_plain.content = state.intern_fmt(format_args!( diff --git a/acdc-parser/src/grammar/reference_text.rs b/acdc-parser/src/grammar/reference_text.rs index 1549ae68f..1321e4e49 100644 --- a/acdc-parser/src/grammar/reference_text.rs +++ b/acdc-parser/src/grammar/reference_text.rs @@ -7,6 +7,7 @@ use super::{ attributes::{AttributeQuote, ResolvedContentAttribute, expand_attribute_list}, inline_preprocessor::SourceMap, inline_processing::process_attribute_inlines_with_substitutions, + source::SourceView, state::InlineRules, }; use crate::{ @@ -16,7 +17,7 @@ use crate::{ #[derive(Debug)] pub(super) struct ReferenceTextContext<'a> { - pub(super) input: &'a str, + pub(super) source: SourceView<'a>, pub(super) passthroughs: Rc<[crate::Passthrough<'a>]>, } @@ -116,14 +117,13 @@ pub(super) fn capture_document_attribute<'a>( ) -> usize { let text = state.intern_str(state.document_attributes.text("reftext").unwrap_or("")); let Some(last) = state - .input - .get(location.absolute_end..) + .source_tail(location.absolute_end) .and_then(|tail| tail.chars().next()) else { return capture_unknown(state, text); }; let end = location.absolute_end + last.len_utf8(); - let Some(declaration) = state.input.get(location.absolute_start..end) else { + let Some(declaration) = state.source_slice(location.absolute_start..end) else { return capture_unknown(state, text); }; let Some((_, value)) = declaration @@ -289,7 +289,7 @@ fn restore_passthroughs<'a>( passthrough.text.unwrap_or_default() } else { context - .input + .source .get(passthrough.location.absolute_start..passthrough.location.absolute_end) .or(passthrough.text) .unwrap_or_default() @@ -389,7 +389,7 @@ pub(super) fn resolve_metadata<'a>( pub(super) fn refresh_block_anchor(state: &ParserState<'_>, id: usize) -> Result { let source = source(state, id)?; let range = source.value.source_range; - let authored = state.input.get(range.clone()).ok_or_else(|| { + let authored = state.source_slice(range.clone()).ok_or_else(|| { Error::Parse( Box::new( state.create_error_source_location(state.create_location(range.start, range.end)), diff --git a/acdc-parser/src/grammar/source.rs b/acdc-parser/src/grammar/source.rs new file mode 100644 index 000000000..9206b0978 --- /dev/null +++ b/acdc-parser/src/grammar/source.rs @@ -0,0 +1,450 @@ +//! Stable, line-aligned input windows with document-wide coordinates. + +use std::{ + cell::{Cell, OnceCell, RefCell}, + ops::Range, + rc::Rc, +}; + +use bumpalo::{Bump, collections::String as BumpString}; + +use crate::{Position, model::SourceRange}; + +use super::{ + LineMap, + utf8_utils::{self, RoundDirection}, +}; + +#[derive(Debug)] +struct Chunk<'a> { + start: usize, + text: &'a str, + first_line: usize, + line_map: OnceCell>, +} + +#[derive(Debug)] +struct WindowText<'a> { + start: usize, + text: &'a str, +} + +/// The reader appends complete lines. Previously emitted text never changes; +/// a window spanning several chunks is joined once in the document arena. +#[derive(Debug, Default)] +pub(super) struct SourceIndex<'a> { + length: Cell, + chunks: RefCell>>, + windows: RefCell>>, +} + +#[derive(Clone, Debug)] +pub(super) struct WindowOrigin<'a> { + pub(super) base: usize, + pub(super) first_line: usize, + pub(super) index: Rc>, +} + +/// An owned location context can outlive advancement of the active window. +/// Ordinary and inline inputs retain a local map with no origin or index. +#[derive(Clone, Debug)] +pub(super) struct SourceView<'a> { + pub(super) input: &'a str, + pub(super) line_map: Rc, + pub(super) origin: Option>>, +} + +impl<'a> SourceIndex<'a> { + pub(super) fn append(&self, text: &'a str) -> usize { + let start = self.length.get(); + if text.is_empty() { + return start; + } + let mut chunks = self.chunks.borrow_mut(); + let first_line = chunks.last().map_or(1, |chunk| { + debug_assert!( + chunk.text.ends_with('\n'), + "source chunks end at line boundaries" + ); + chunk.first_line + chunk.text.bytes().filter(|byte| *byte == b'\n').count() + }); + chunks.push(Chunk { + start, + text, + first_line, + line_map: OnceCell::new(), + }); + self.length.set(start + text.len()); + start + } + + pub(super) fn seal(&self, length: usize) { + debug_assert!(length <= self.length.get()); + self.length.set(length); + } + + pub(super) fn len(&self) -> usize { + self.length.get() + } + + fn remember_window(&self, start: usize, text: &'a str) { + let mut windows = self.windows.borrow_mut(); + if let Some(last) = windows.last() { + debug_assert!( + start >= last.start, + "source windows advance in source order" + ); + if start + text.len() <= last.start + last.text.len() { + return; + } + } + windows.push(WindowText { start, text }); + } + + pub(super) fn window( + self: &Rc, + range: Range, + arena: &'a Bump, + ) -> Option> { + if range.start > range.end || range.end > self.len() { + return None; + } + { + let chunks = self.chunks.borrow(); + let i = chunks + .partition_point(|chunk| chunk.start <= range.start) + .checked_sub(1); + if let Some(chunk) = i.and_then(|i| chunks.get(i)) + && range.end <= chunk.start + chunk.text.len() + { + chunk + .text + .get(range.start - chunk.start..range.end - chunk.start)?; + let input = chunk + .text + .get(..chunk.text.len().min(self.len() - chunk.start))?; + let line_map = if input.len() == chunk.text.len() { + Rc::clone(chunk.line_map.get_or_init(|| Rc::new(LineMap::new(input)))) + } else { + Rc::new(LineMap::new(input)) + }; + return Some(SourceView { + input, + line_map, + origin: Some(Rc::new(WindowOrigin { + base: chunk.start, + first_line: chunk.first_line, + index: Rc::clone(self), + })), + }); + } + } + if let Some((start, input)) = self.window_text(&range) { + return Some(SourceView { + input, + line_map: Rc::new(LineMap::new(input)), + origin: Some(Rc::new(WindowOrigin { + base: start, + first_line: self.position(start).line as usize, + index: Rc::clone(self), + })), + }); + } + let start = self.line_start(range.start)?; + let mut joined = BumpString::new_in(arena); + for chunk in self.chunks.borrow().iter() { + let left = start.max(chunk.start); + let right = range.end.min(chunk.start + chunk.text.len()); + if left < right { + joined.push_str(chunk.text.get(left - chunk.start..right - chunk.start)?); + } + if chunk.start >= range.end { + break; + } + } + if joined.len() != range.end - start { + return None; + } + let input = joined.into_bump_str(); + self.remember_window(start, input); + Some(SourceView { + input, + line_map: Rc::new(LineMap::new(input)), + origin: Some(Rc::new(WindowOrigin { + base: start, + first_line: self.position(start).line as usize, + index: Rc::clone(self), + })), + }) + } + + fn window_text(&self, range: &Range) -> Option<(usize, &'a str)> { + let windows = self.windows.borrow(); + let i = windows + .partition_point(|window| window.start <= range.start) + .checked_sub(1)?; + let window = windows.get(i)?; + window + .text + .get(range.start - window.start..range.end.checked_sub(window.start)?)?; + Some((window.start, window.text)) + } + + fn line_start(&self, offset: usize) -> Option { + if offset == 0 { + return Some(0); + } + let chunks = self.chunks.borrow(); + let i = chunks + .partition_point(|chunk| chunk.start <= offset) + .checked_sub(1)?; + let chunk = chunks.get(i)?; + let prefix = chunk.text.get(..offset - chunk.start)?; + Some(chunk.start + prefix.rfind('\n').map_or(0, |offset| offset + 1)) + } + + fn get(&self, range: Range) -> Option<&'a str> { + if range.start > range.end || range.end > self.len() { + return None; + } + if let Some((start, text)) = self.window_text(&range) { + return text.get(range.start - start..range.end - start); + } + let chunks = self.chunks.borrow(); + let i = chunks + .partition_point(|chunk| chunk.start <= range.start) + .checked_sub(1)?; + let chunk = chunks.get(i)?; + chunk + .text + .get(range.start - chunk.start..range.end.checked_sub(chunk.start)?) + } + + pub(super) fn tail(&self, offset: usize) -> Option<&'a str> { + if offset > self.len() { + return None; + } + let chunks = self.chunks.borrow(); + let i = chunks + .partition_point(|chunk| chunk.start <= offset) + .checked_sub(1)?; + let chunk = chunks.get(i)?; + chunk + .text + .get(offset - chunk.start..(self.len() - chunk.start).min(chunk.text.len())) + } + + fn byte(&self, offset: usize) -> Option { + if offset >= self.len() { + return None; + } + let chunks = self.chunks.borrow(); + let i = chunks + .partition_point(|chunk| chunk.start <= offset) + .checked_sub(1)?; + let chunk = chunks.get(i)?; + chunk.text.as_bytes().get(offset - chunk.start).copied() + } + + fn snap(&self, offset: usize, direction: RoundDirection) -> usize { + let offset = offset.min(self.len()); + let chunks = self.chunks.borrow(); + let Some(chunk) = chunks + .partition_point(|chunk| chunk.start <= offset) + .checked_sub(1) + .and_then(|i| chunks.get(i)) + else { + return 0; + }; + chunk.start + utf8_utils::snap_to_boundary(chunk.text, offset - chunk.start, direction) + } + + fn position(&self, offset: usize) -> Position { + let offset = self.snap(offset, RoundDirection::Backward); + let chunks = self.chunks.borrow(); + let Some(chunk) = chunks + .partition_point(|chunk| chunk.start <= offset) + .checked_sub(1) + .and_then(|i| chunks.get(i)) + else { + return Position::new(1, 1); + }; + if let Some(map) = chunk.line_map.get() { + let mut position = map.offset_to_position(offset - chunk.start, chunk.text); + position.line = position + .line + .saturating_add(u32::try_from(chunk.first_line - 1).unwrap_or(u32::MAX)); + return position; + } + let prefix = chunk.text.get(..offset - chunk.start).unwrap_or_default(); + let line = chunk.first_line + prefix.bytes().filter(|byte| *byte == b'\n').count(); + let column = prefix + .rsplit('\n') + .next() + .unwrap_or_default() + .chars() + .count() + + 1; + Position::new( + u32::try_from(line).unwrap_or(u32::MAX), + u32::try_from(column).unwrap_or(u32::MAX), + ) + } +} + +#[cfg(test)] +mod tests; + +impl<'a> SourceView<'a> { + pub(super) fn get(&self, range: Range) -> Option<&'a str> { + slice(self.input, self.origin.as_deref(), range) + } + pub(super) fn position(&self, offset: usize) -> Position { + position(self.input, &self.line_map, self.origin.as_deref(), offset) + } + pub(super) fn snap(&self, offset: usize, direction: RoundDirection) -> usize { + snap(self.input, self.origin.as_deref(), offset, direction) + } + pub(super) fn step(&self, offset: usize, direction: RoundDirection) -> usize { + step(self.input, self.origin.as_deref(), offset, direction) + } + + pub(super) fn previous_char(&self, offset: usize) -> Option { + let end = self.snap(offset, RoundDirection::Backward); + let start = self.step(end, RoundDirection::Backward); + self.get(start..end)?.chars().next_back() + } +} + +#[inline] +pub(super) fn len(input: &str, origin: Option<&WindowOrigin<'_>>) -> usize { + origin.map_or(input.len(), |origin| origin.index.len()) +} + +#[inline] +pub(super) fn slice<'a>( + input: &'a str, + origin: Option<&WindowOrigin<'a>>, + range: Range, +) -> Option<&'a str> { + let Some(origin) = origin else { + return input.get(range); + }; + if range.start > range.end || range.end > origin.index.len() { + return None; + } + if range.start >= origin.base && range.end <= origin.base + input.len() { + input.get(range.start - origin.base..range.end - origin.base) + } else { + origin.index.get(range) + } +} + +#[inline] +pub(super) fn tail<'a>( + input: &'a str, + origin: Option<&WindowOrigin<'a>>, + offset: usize, +) -> Option<&'a str> { + let Some(origin) = origin else { + return input.get(offset..); + }; + if offset > origin.index.len() { + return None; + } + if offset >= origin.base && offset <= origin.base + input.len() { + input.get(offset - origin.base..(origin.index.len() - origin.base).min(input.len())) + } else { + origin.index.tail(offset) + } +} + +#[inline] +pub(super) fn byte(input: &str, origin: Option<&WindowOrigin<'_>>, offset: usize) -> Option { + let Some(origin) = origin else { + return input.as_bytes().get(offset).copied(); + }; + if offset >= origin.index.len() { + return None; + } + if offset >= origin.base && offset < origin.base + input.len() { + input.as_bytes().get(offset - origin.base).copied() + } else { + origin.index.byte(offset) + } +} + +#[inline] +pub(super) fn snap( + input: &str, + origin: Option<&WindowOrigin<'_>>, + offset: usize, + direction: RoundDirection, +) -> usize { + let Some(origin) = origin else { + return utf8_utils::snap_to_boundary(input, offset, direction); + }; + let offset = offset.min(origin.index.len()); + if offset >= origin.base && offset <= origin.base + input.len() { + origin.base + utf8_utils::snap_to_boundary(input, offset - origin.base, direction) + } else { + origin.index.snap(offset, direction) + } +} + +#[inline] +pub(super) fn step( + input: &str, + origin: Option<&WindowOrigin<'_>>, + offset: usize, + direction: RoundDirection, +) -> usize { + match direction { + RoundDirection::Backward => snap(input, origin, offset.saturating_sub(1), direction), + RoundDirection::Forward if offset >= len(input, origin) => len(input, origin), + RoundDirection::Forward => snap(input, origin, offset + 1, direction), + } +} + +#[inline] +pub(super) fn position( + input: &str, + map: &LineMap, + origin: Option<&WindowOrigin<'_>>, + offset: usize, +) -> Position { + let Some(origin) = origin else { + return map.offset_to_position(offset, input); + }; + let offset = offset.min(origin.index.len()); + if offset >= origin.base && offset <= origin.base + input.len() { + let mut position = map.offset_to_position(offset - origin.base, input); + position.line = position + .line + .saturating_add(u32::try_from(origin.first_line - 1).unwrap_or(u32::MAX)); + position + } else { + origin.index.position(offset) + } +} + +#[inline] +pub(super) fn source_line( + input: &str, + map: &LineMap, + origin: Option<&WindowOrigin<'_>>, + range: &SourceRange, + offset: usize, +) -> u32 { + let Some(origin) = origin else { + return map.source_line(range, offset); + }; + let start_line = origin.index.position(range.start_offset).line; + u32::try_from(range.start_line) + .unwrap_or(u32::MAX) + .saturating_add( + position(input, map, Some(origin), offset) + .line + .saturating_sub(start_line), + ) +} diff --git a/acdc-parser/src/grammar/source/tests.rs b/acdc-parser/src/grammar/source/tests.rs new file mode 100644 index 000000000..a9ca8c1dd --- /dev/null +++ b/acdc-parser/src/grammar/source/tests.rs @@ -0,0 +1,203 @@ +use std::rc::Rc; + +use crate::{ + Options, + grammar::{ParserState, state::InlineContext}, + model::SourceRange, +}; + +use super::{RoundDirection, SourceIndex}; + +type TestResult = Result<(), Box>; + +#[test] +fn windows_match_complete_input_geometry_and_keep_inline_maps_local() -> TestResult { + let arena = bumpalo::Bump::new(); + let index = Rc::new(SourceIndex::default()); + let first = "Préface.\n\n"; + let second = "== Hèading\n"; + let third = "Body 世界.\n"; + index.append(first); + let middle = index.append(second); + let end = index.append(third); + let complete = format!("{first}{second}{third}"); + let options = Rc::new(Options::default()); + let reference = ParserState::new(&complete, &arena, Rc::clone(&options)); + let view = index.window(middle..end, &arena).ok_or("missing window")?; + let saved = view.clone(); + let mut state = ParserState::new_with_source(view, &arena, options); + for offset in 0..=complete.len() + 2 { + assert_eq!( + state.create_location(offset, offset), + reference.create_location(offset, offset) + ); + } + state.set_source_view( + index + .window(end..index.len(), &arena) + .ok_or("missing final window")?, + ); + assert_eq!(state.source_slice(0..first.len()), Some(first)); + assert_eq!(saved.get(middle..end), Some(second)); + assert_eq!(saved.position(middle), reference.source_position(middle)); + assert_eq!( + saved.snap(middle + 5, RoundDirection::Backward), + reference.source_snap(middle + 5, RoundDirection::Backward) + ); + let inline = ParserState::for_inline_parsing(state.input, &state, InlineContext::default()); + assert!(inline.input_origin.is_none()); + assert!(Rc::ptr_eq(&inline.line_map, &state.line_map)); + assert_eq!(inline.create_location(0, 4).start.line, 1); + assert_eq!(inline.create_location(0, 4).absolute_start, 0); + Ok(()) +} + +#[test] +fn joined_windows_retain_source_and_reuse_unchanged_chunk_storage() -> TestResult { + let arena = bumpalo::Bump::new(); + let index = Rc::new(SourceIndex::default()); + let first = "before\nleft\n"; + let second = "right 世界\n"; + index.append(first); + let middle = index.append(second); + let single = index + .window(0..middle, &arena) + .ok_or("missing first chunk")?; + assert!(std::ptr::eq(single.input.as_ptr(), first.as_ptr())); + let again = index.window(2..4, &arena).ok_or("missing chunk subset")?; + assert!(Rc::ptr_eq(&single.line_map, &again.line_map)); + let joined = index + .window(9..index.len(), &arena) + .ok_or("missing joined window")?; + assert_eq!(joined.input, "left\nright 世界\n"); + let repeated = index + .window(9..index.len(), &arena) + .ok_or("missing retained window")?; + assert!(std::ptr::eq(joined.input.as_ptr(), repeated.input.as_ptr())); + let later = index.append("later\n"); + let state = ParserState::new_with_source( + index + .window(later..index.len(), &arena) + .ok_or("missing later window")?, + &arena, + Rc::new(Options::default()), + ); + assert_eq!(state.source_slice(7..later), Some("left\nright 世界\n")); + assert!( + state + .source_slice(std::ops::Range { start: 9, end: 8 }) + .is_none() + ); + Ok(()) +} + +#[test] +fn windows_preserve_included_diagnostic_ranges_and_final_separator_clipping() -> TestResult { + let arena = bumpalo::Bump::new(); + let index = Rc::new(SourceIndex::default()); + let first = "preamble\n"; + let included = "第一行\n"; + let last = "café 世界\n"; + index.append(first); + let included_start = index.append(included); + let last_start = index.append(last); + let complete = format!("{first}{included}{last}"); + let range = SourceRange { + start_offset: included_start, + end_offset: complete.len(), + file: Some("/virtual/part.adoc".into()), + file_chain: vec!["part.adoc".into()], + start_line: 41, + source_start_offset: 900, + column_shift: 0, + }; + let mut reference = ParserState::new(&complete, &arena, Rc::new(Options::default())); + reference.source_ranges.push(range.clone()); + let mut state = ParserState::new_with_source( + index + .window(last_start..index.len(), &arena) + .ok_or("missing last window")?, + &arena, + Rc::new(Options::default()), + ); + state.source_ranges.push(range); + for offset in last_start..complete.len() { + assert_eq!( + state.create_error_source_location(state.create_location(offset, offset)), + reference.create_error_source_location(reference.create_location(offset, offset)) + ); + } + let saved = state.source_view(); + index.seal(complete.len() - 1); + let clipped = index + .window(last_start..index.len(), &arena) + .ok_or("missing clipped EOF window")?; + assert_eq!(clipped.input, last.trim_end_matches('\n')); + state.set_source_view(clipped); + assert_eq!( + saved.position(index.len() + 1), + state.source_position(index.len()) + ); + assert_eq!( + saved.step(index.len(), RoundDirection::Backward), + state.source_step(index.len(), RoundDirection::Backward) + ); + Ok(()) +} + +#[test] +fn windowed_inline_preprocessing_matches_complete_input_nodes_and_diagnostics() -> TestResult { + use crate::grammar::{helpers::BlockParsingMetadata, inline_processing::process_inlines}; + + let arena = bumpalo::Bump::new(); + let prefix = "Before 世界.\n\n"; + let content = "café [[target,pass:[*label*]]] <> {counter:test} +raw 世界+"; + let source = format!("{prefix}{content}\n"); + for mode in [ + crate::CompatibilityMode::Asciidoctor, + crate::CompatibilityMode::Draft, + ] { + let options = Rc::new(Options::builder().with_compatibility_mode(mode).build()?); + let mut reference = ParserState::new(&source, &arena, Rc::clone(&options)); + let index = Rc::new(SourceIndex::default()); + index.append(prefix); + let start = index.append(arena.alloc_str(&format!("{content}\n"))); + let mut windowed = ParserState::new_with_source( + index + .window(start..index.len(), &arena) + .ok_or("missing inline window")?, + &arena, + options, + ); + let metadata = BlockParsingMetadata::new(mode); + let expected = process_inlines( + &mut reference, + &metadata, + start, + start + content.len(), + 0, + content, + )?; + let actual = process_inlines(&mut windowed, &metadata, 0, content.len(), start, content)?; + assert_eq!(actual, expected); + assert_eq!( + format!("{:?}", &windowed.warnings.borrow()[..]), + format!("{:?}", &reference.warnings.borrow()[..]) + ); + let count = reference.reference_text_sources.borrow().len(); + assert_eq!(windowed.reference_text_sources.borrow().len(), count); + let next = index.append("Later.\n"); + windowed.set_source_view( + index + .window(next..index.len(), &arena) + .ok_or("missing later view")?, + ); + for id in 0..count { + assert_eq!( + crate::grammar::reference_text::resolve(&windowed, id)?, + crate::grammar::reference_text::resolve(&reference, id)? + ); + } + } + Ok(()) +} diff --git a/acdc-parser/src/grammar/state.rs b/acdc-parser/src/grammar/state.rs index 2562fe053..8d1814095 100644 --- a/acdc-parser/src/grammar/state.rs +++ b/acdc-parser/src/grammar/state.rs @@ -14,8 +14,8 @@ use bumpalo::Bump; use crate::{ CalloutMarker, CaptionKind, DocumentAttribute, DocumentAttributes, Error, Footnote, - FootnoteDefinition, Location, Options, Passthrough, SourceLocation, TocEntry, Warning, - WarningKind, XrefCaptionLabel, XrefSignifier, + FootnoteDefinition, Location, Options, Passthrough, Position, SourceLocation, TocEntry, + Warning, WarningKind, XrefCaptionLabel, XrefSignifier, document_attribute::{ AttributeDeclaration, RawAttributeValue, is_header_only, normalize_toc_attributes, normalized_entry_name, starts_like_entry_name, @@ -23,6 +23,8 @@ use crate::{ grammar::{ LineMap, document::lists::{DescriptionListScope, OrdinaryListScope}, + source::{self, SourceView, WindowOrigin}, + utf8_utils::{self, RoundDirection}, }, model::{ DocumentAttributeStatus, LeveloffsetRange, REFSIG_ATTRIBUTES, SourceRange, @@ -99,6 +101,8 @@ pub(crate) struct ParserState<'a> { /// model nodes can hold `Cow::Borrowed` references into it without /// allocating per-token strings. pub(crate) input: &'a str, + pub(super) input_origin: Option>>, + pub(super) source_scope_offset: usize, /// Bump arena for transient strings that downstream inline parsing must /// borrow from with lifetime `'a`. Used for substitution buffers, escape /// unwrapping, and other grammar sites that historically built local @@ -788,6 +792,40 @@ impl<'a> ParserState<'a> { } pub(crate) fn new(input: &'a str, arena: &'a Bump, options: Rc>) -> Self { + Self::with_input(input, Rc::new(LineMap::new(input)), None, arena, options) + } + + pub(super) fn new_with_source( + view: SourceView<'a>, + arena: &'a Bump, + options: Rc>, + ) -> Self { + Self::with_input(view.input, view.line_map, view.origin, arena, options) + } + + pub(crate) fn new_source(arena: &'a Bump, options: Rc>) -> Self { + Self::new_with_source( + SourceView { + input: "", + line_map: Rc::new(LineMap::new("")), + origin: Some(Rc::new(WindowOrigin { + base: 0, + first_line: 1, + index: Rc::default(), + })), + }, + arena, + options, + ) + } + + fn with_input( + input: &'a str, + line_map: Rc, + input_origin: Option>>, + arena: &'a Bump, + options: Rc>, + ) -> Self { let substitutions = SubstitutionPlan::for_mode(options.compatibility_mode); let mut state = Self { attribute_sources: Rc::default(), @@ -804,8 +842,10 @@ impl<'a> ParserState<'a> { attribute_value_ranges: Vec::new(), late_attribute_sources: Vec::new(), last_url_boundary: None, - line_map: Rc::new(LineMap::new(input)), + line_map, input, + input_origin, + source_scope_offset: 0, arena, footnote_tracker: Rc::new(RefCell::new(FootnoteTracker::new())), xref_caption_label_snapshots: Rc::default(), @@ -864,6 +904,8 @@ impl<'a> ParserState<'a> { last_url_boundary: None, line_map: Rc::new(LineMap::new(input)), input, + input_origin: None, + source_scope_offset: 0, arena, footnote_tracker: Rc::new(RefCell::new(FootnoteTracker::new())), xref_caption_label_snapshots: Rc::default(), @@ -922,6 +964,8 @@ impl<'a> ParserState<'a> { Rc::new(LineMap::new(input)) }, input, + input_origin: None, + source_scope_offset: 0, arena: parent.arena, footnote_tracker: Rc::clone(&parent.footnote_tracker), xref_caption_label_snapshots: Rc::clone(&parent.xref_caption_label_snapshots), @@ -1026,6 +1070,86 @@ impl<'a> ParserState<'a> { } } + pub(super) fn set_source_view(&mut self, view: SourceView<'a>) { + self.input = view.input; + self.line_map = view.line_map; + self.input_origin = view.origin; + } + + #[inline] + pub(super) fn source_view(&self) -> SourceView<'a> { + SourceView { + input: self.input, + line_map: Rc::clone(&self.line_map), + origin: self.input_origin.clone(), + } + } + + #[inline] + pub(super) fn list_scope_offset(&self, offset: usize) -> usize { + self.input_origin + .as_deref() + .map_or(offset, |_| self.source_scope_offset) + } + + #[inline] + pub(crate) fn input_offset(&self, offset: usize) -> usize { + self.input_origin + .as_ref() + .map_or(offset, |origin| origin.base + offset) + } + + #[inline] + pub(crate) fn source_len(&self) -> usize { + source::len(self.input, self.input_origin.as_deref()) + } + + #[inline] + pub(super) fn source_slice(&self, range: Range) -> Option<&'a str> { + source::slice(self.input, self.input_origin.as_deref(), range) + } + + #[inline] + pub(super) fn source_tail(&self, offset: usize) -> Option<&'a str> { + source::tail(self.input, self.input_origin.as_deref(), offset) + } + + #[inline] + pub(super) fn source_byte(&self, offset: usize) -> Option { + source::byte(self.input, self.input_origin.as_deref(), offset) + } + + #[inline] + pub(crate) fn source_position(&self, offset: usize) -> Position { + source::position( + self.input, + &self.line_map, + self.input_origin.as_deref(), + offset, + ) + } + + #[inline] + pub(super) fn source_snap(&self, offset: usize, direction: RoundDirection) -> usize { + source::snap(self.input, self.input_origin.as_deref(), offset, direction) + } + + #[inline] + pub(super) fn source_step(&self, offset: usize, direction: RoundDirection) -> usize { + source::step(self.input, self.input_origin.as_deref(), offset, direction) + } + + #[inline] + pub(crate) fn source_line(&self, range: &SourceRange, offset: usize) -> u32 { + source::source_line( + self.input, + &self.line_map, + self.input_origin.as_deref(), + range, + offset, + ) + } + /// Map a diagnostic's endpoints to their original source coordinates. pub(crate) fn create_error_source_location(&self, mut location: Location) -> SourceLocation { let Some(start_range) = @@ -1038,20 +1162,18 @@ impl<'a> ParserState<'a> { }; let end_probe = location .absolute_end - .min(self.input.len().saturating_sub(1)) + .min(self.source_len().saturating_sub(1)) .max(location.absolute_start); let end_range = SourceRange::find_containing(&self.source_ranges, end_probe).unwrap_or(start_range); let start = ( start_range.source_offset(location.absolute_start), - self.line_map - .source_line(start_range, location.absolute_start), + self.source_line(start_range, location.absolute_start), start_range, ); let end = ( end_range.source_offset(location.absolute_end), - self.line_map - .source_line(end_range, location.absolute_end.min(self.input.len())), + self.source_line(end_range, location.absolute_end.min(self.source_len())), end_range, ); super::source_remap::remap_endpoints(&mut location, start, end); @@ -1078,21 +1200,32 @@ impl<'a> ParserState<'a> { /// semantics - it represents the last byte of the range, not one past it. /// When a byte lands mid-character, rounding backward includes that character. pub(crate) fn create_location(&self, start: usize, end: usize) -> Location { - use crate::grammar::utf8_utils::ensure_char_boundary; - - // Clamp to input bounds first - let clamped_start = start.min(self.input.len()); - let clamped_end = end.min(self.input.len()); - - // Ensure UTF-8 boundaries (both round backward for inclusive semantics) - let safe_start = ensure_char_boundary(self.input, clamped_start); - let safe_end = ensure_char_boundary(self.input, clamped_end); - - // Ensure start <= end - let safe_end = safe_end.max(safe_start); - - let start_pos = self.line_map.offset_to_position(safe_start, self.input); - let end_pos = self.line_map.offset_to_position(safe_end, self.input); + let (safe_start, safe_end, start_pos, end_pos) = if self.input_origin.is_none() { + // Complete inputs use the local map directly. Only resumable input + // needs document-wide coordinate lookup across retained windows. + let safe_start = + utf8_utils::snap_to_boundary(self.input, start, RoundDirection::Backward); + let safe_end = utf8_utils::snap_to_boundary(self.input, end, RoundDirection::Backward) + .max(safe_start); + ( + safe_start, + safe_end, + self.line_map.offset_to_position(safe_start, self.input), + self.line_map.offset_to_position(safe_end, self.input), + ) + } else { + let safe_start = + self.source_snap(start.min(self.source_len()), RoundDirection::Backward); + let safe_end = self + .source_snap(end.min(self.source_len()), RoundDirection::Backward) + .max(safe_start); + ( + safe_start, + safe_end, + self.source_position(safe_start), + self.source_position(safe_end), + ) + }; // Positions carry no `file` at construction (the ASG omits the primary file). // The post-parse remap pass stamps the originating file on `include::`d nodes; @@ -1117,8 +1250,6 @@ impl<'a> ParserState<'a> { end: usize, offset: usize, ) -> Location { - use crate::grammar::utf8_utils::safe_decrement_offset; - let adjusted_start = start + offset; let adjusted_end = end + offset; @@ -1126,7 +1257,7 @@ impl<'a> ParserState<'a> { let final_end = if adjusted_end == 0 { 0 } else { - safe_decrement_offset(self.input, adjusted_end) + self.source_step(adjusted_end, RoundDirection::Backward) }; // create_location handles all UTF-8 boundary enforcement diff --git a/acdc-parser/src/grammar/utf8_utils.rs b/acdc-parser/src/grammar/utf8_utils.rs index 6e0eb04ba..3ea0db6cf 100644 --- a/acdc-parser/src/grammar/utf8_utils.rs +++ b/acdc-parser/src/grammar/utf8_utils.rs @@ -93,18 +93,21 @@ pub(super) fn step_char(input: &str, offset: usize, direction: RoundDirection) - /// Safely decrement a byte offset by one character, ensuring valid UTF-8 boundary. #[inline] +#[cfg(test)] pub(super) fn safe_decrement_offset(input: &str, offset: usize) -> usize { step_char(input, offset, RoundDirection::Backward) } /// Ensure an offset is on a valid UTF-8 character boundary (round backward). #[inline] +#[cfg(test)] pub(super) fn ensure_char_boundary(input: &str, offset: usize) -> usize { snap_to_boundary(input, offset, RoundDirection::Backward) } /// Ensure an offset is on a valid UTF-8 character boundary (round forward). #[inline] +#[cfg(test)] pub(super) fn ensure_char_boundary_forward(input: &str, offset: usize) -> usize { snap_to_boundary(input, offset, RoundDirection::Forward) } diff --git a/acdc-parser/src/lib.rs b/acdc-parser/src/lib.rs index ea9164b4e..050fb84b9 100644 --- a/acdc-parser/src/lib.rs +++ b/acdc-parser/src/lib.rs @@ -434,11 +434,23 @@ fn parse_with_session( input: &str, options: &Options<'_>, session: Option<&mut extensions::Session>, +) -> Result { + parse_with_source_handler(input, options, session, None) +} + +fn parse_with_source_handler( + input: &str, + options: &Options<'_>, + session: Option<&mut extensions::Session>, + handler: Option<&mut dyn grammar::SourceHandler>, ) -> Result { let options = options .clone() .prepare_for_parse(document_attribute::InputKind::String); let warnings_handle: Rc> = Rc::default(); + if let Some(handler) = handler { + return parse_ordered_source(input, options, None, warnings_handle, session, handler); + } let result = { let _span = tracing::info_span!("preprocess").entered(); Preprocessor::process(input, &options, Rc::clone(&warnings_handle))? @@ -503,22 +515,24 @@ fn peg_error_to_source_location( error: &peg::error::ParseError, state: &grammar::ParserState, ) -> SourceLocation { - let offset = error.location.offset; + let offset = state.input_offset(error.location.offset); + let position = if state.input_offset(0) == 0 { + Position::from_line_col(error.location.line, error.location.column) + } else { + state.source_position(offset) + }; if let Some(range) = model::SourceRange::find_containing(&state.source_ranges, offset) { SourceLocation { file: range.file.clone(), location: crate::Location::point(Position::new( - state.line_map.source_line(range, offset), - u32::try_from(error.location.column).unwrap_or(u32::MAX), + state.source_line(range, offset), + position.column, )), } } else { SourceLocation { file: state.current_file.as_deref().cloned(), - location: crate::Location::point(Position::from_line_col( - error.location.line, - error.location.column, - )), + location: crate::Location::point(position), } } } @@ -578,25 +592,7 @@ fn parse_input( state.add_warning(Warning::new(WarningKind::DeprecatedToc2Attribute, None)); } let result = match grammar::parse_document(&owner.source, &mut state) { - Ok(Ok(mut doc)) => { - grammar::reference_text::finish_document(&mut state, &mut doc)?; - if let Some(session) = session - && session.process(&mut doc, &state)? - { - doc.renumber_captions(); - extensions::finalization::repair_macros(&mut doc)?; - } - // Rewrite every node's location from preprocessed coordinates to the - // original source (file + line + byte offset). No-op when the - // preprocessor recorded no ranges (no includes/edits). - grammar::remap_document_to_source( - &mut doc, - &state.source_ranges, - &owner.source, - &state.line_map, - ); - Ok(doc) - } + Ok(Ok(doc)) => finish_parsed_document(doc, &mut state, session, &owner.source), Ok(Err(e)) => Err(e), Err(error) => { tracing::error!("error parsing document content"); @@ -610,6 +606,64 @@ fn parse_input( ) } +#[inline] +fn finish_parsed_document<'a>( + mut doc: Document<'a>, + state: &mut grammar::ParserState<'a>, + session: Option<&mut extensions::Session>, + source: &'a str, +) -> Result, Error> { + grammar::reference_text::finish_document(state, &mut doc)?; + if let Some(session) = session + && session.process(&mut doc, state)? + { + doc.renumber_captions(); + extensions::finalization::repair_macros(&mut doc)?; + } + grammar::remap_document_to_source(&mut doc, &state.source_ranges, source, &state.line_map); + Ok(doc) +} + +fn parse_ordered_source( + input: &str, + options: Options<'_>, + file_path: Option, + warnings_handle: Rc>, + session: Option<&mut extensions::Session>, + handler: &mut dyn grammar::SourceHandler, +) -> Result { + let owner = parsed::OwnedInput::new(input.into()); + let warnings_for_state = Rc::clone(&warnings_handle); + let options = options.into_static(); + ParseResult::try_new_with_metadata(owner, warnings_handle, move |owner| { + let reader = preprocessor::SourceReader::new( + &owner.source, + file_path.as_deref(), + &options, + Rc::clone(&warnings_for_state), + &owner.arena, + )?; + let mut state = + grammar::ParserState::new_source(&owner.arena, Rc::new(reader.options.clone())); + state.current_file = file_path.clone().map(std::sync::Arc::new); + state.warnings = warnings_for_state; + state.warn_unsupported_compat_mode(None); + if state.document_attributes.contains_key("toc2") { + state.add_warning(Warning::new(WarningKind::DeprecatedToc2Attribute, None)); + } + let result = grammar::document_from_source(reader, &mut state, handler, |source| { + owner.finish_source(source) + }) + .and_then(|(document, conditionals)| { + let source_files = parsed::SourceFiles::new(file_path, &state.source_ranges); + finish_parsed_document(document, &mut state, session, owner.preprocessed_source()) + .map(|document| (document, source_files, conditionals)) + }); + state.emit_warnings(); + result + }) +} + /// Parse inline `AsciiDoc` content from a string. /// /// The result owns its inline nodes without a block document. Use it for fragments @@ -694,6 +748,9 @@ pub fn parse_inline(input: &str, options: &Options<'_>) -> Result, pub(crate) arena: Bump, + processed_source: OnceCell>, } impl OwnedInput { @@ -80,7 +81,22 @@ impl OwnedInput { // first ~10 chunk-grow round-trips through the global allocator // on documents larger than a few KB. let arena = Bump::with_capacity(source.len()); - Self { source, arena } + Self { + source, + arena, + processed_source: OnceCell::new(), + } + } + + pub(crate) fn finish_source(&self, source: String) -> &str { + self.processed_source + .get_or_init(|| source.into_boxed_str()) + } + + pub(crate) fn preprocessed_source(&self) -> &str { + self.processed_source + .get() + .map_or(&self.source, AsRef::as_ref) } } @@ -178,6 +194,47 @@ impl ParseResult { builder: impl for<'a> FnOnce(&'a OwnedInput) -> Result, E>, ) -> Result { let cell = ParsedDocumentCell::try_new(owner, builder)?; + Ok(Self::from_cell( + cell, + warnings_handle, + source_files, + conditionals, + )) + } + + pub(crate) fn try_new_with_metadata( + owner: OwnedInput, + warnings_handle: Rc>, + builder: impl for<'a> FnOnce( + &'a OwnedInput, + ) -> Result< + (Document<'a>, SourceFiles, Vec), + E, + >, + ) -> Result { + let mut metadata = (SourceFiles::default(), Vec::new()); + let cell = ParsedDocumentCell::try_new(owner, |owner| { + builder(owner).map(|(document, source_files, conditionals)| { + metadata = (source_files, conditionals); + document + }) + })?; + let (source_files, conditionals) = metadata; + Ok(Self::from_cell( + cell, + warnings_handle, + source_files, + conditionals, + )) + } + + #[inline] + fn from_cell( + cell: ParsedDocumentCell, + warnings_handle: Rc>, + source_files: SourceFiles, + conditionals: Vec, + ) -> Self { let warnings = recover_warnings(warnings_handle); let source_recovery = warnings .iter() @@ -195,13 +252,13 @@ impl ParseResult { ) }) .map(|warning| Box::new(Warning::new(warning.kind.clone(), warning.location.clone()))); - Ok(Self { + Self { cell, warnings, source_recovery, source_files, conditionals, - }) + } } /// Read the document through typed handles and iterators. @@ -263,7 +320,7 @@ impl ParseResult { /// caller input. #[must_use] pub fn preprocessed_source(&self) -> &str { - &self.cell.borrow_owner().source + self.cell.borrow_owner().preprocessed_source() } /// Resolve a location from this result's AST to its original source file and position. diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs index fdf99e662..c3135f0ee 100644 --- a/acdc-parser/src/preprocessor/cursor.rs +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -25,6 +25,7 @@ pub(super) struct InputCursor<'input> { conditionals: Vec>, front_matter: Option, include: Option>, + bulk_consumed: bool, } struct IncludeFrame<'input> { @@ -32,9 +33,335 @@ struct IncludeFrame<'input> { cursor: Box>, input_line: usize, scope: Option, + pending_blank: Option>, + prefix_emitted: bool, + emitted_end: usize, +} + +/// Stable text emitted by one reader advance, in this cursor's coordinates. +/// The final separator is provisional until the enclosing source reaches EOF. +pub(super) struct Emission<'input> { + pub(super) start: usize, + pub(super) text: &'input str, + pub(super) source_ranges: Vec, + pub(super) leveloffset_ranges: Vec, + pub(super) leveloffset_scopes: Vec, +} + +pub(super) enum Advance<'input> { + Progress(Vec>), + End, +} + +impl Emission<'_> { + fn prepend_include(&mut self, include: &IncludeResult, base: usize) { + self.start += base; + for range in &mut self.source_ranges { + range.start_offset += base; + range.end_offset += base; + range.file_chain.insert(0, include.target.clone()); + } + for range in &mut self.leveloffset_ranges { + range.start_offset += base; + range.end_offset += base; + } + for scope in &mut self.leveloffset_scopes { + scope.range.start += base; + scope.range.end += base; + } + if let Some(value) = include.effective_leveloffset.filter(|value| *value != 0) { + self.leveloffset_ranges.insert( + 0, + crate::model::LeveloffsetRange::new( + self.start, + self.start + self.text.len(), + value, + ), + ); + } + } + + fn take_final_blank(&mut self) -> Option { + if self.text != "\n" && !self.text.ends_with("\n\n") { + return None; + } + let split = self.start + self.text.len() - 1; + let source_ranges = self + .source_ranges + .iter() + .filter_map(|range| { + if range.end_offset <= split { + return None; + } + let mut tail = range.clone(); + let local_start = range.start_offset.saturating_sub(self.start); + let prefix = self.text.get(local_start..split - self.start)?; + tail.start_offset = split; + tail.start_line += prefix.bytes().filter(|byte| *byte == b'\n').count(); + tail.source_start_offset += prefix.len(); + Some(tail) + }) + .collect(); + let leveloffset_ranges = self + .leveloffset_ranges + .iter() + .filter(|range| range.end_offset > split) + .map(|range| crate::model::LeveloffsetRange::new(split, range.end_offset, range.value)) + .collect(); + let blank = Self { + start: split, + text: "\n", + source_ranges, + leveloffset_ranges, + leveloffset_scopes: self + .leveloffset_scopes + .iter() + .filter(|scope| scope.range.end > split) + .cloned() + .map(|mut scope| { + scope.range.start = split.max(scope.range.start); + scope + }) + .collect(), + }; + self.text = self.text.get(..self.text.len() - 1)?; + for range in &mut self.source_ranges { + range.end_offset = range.end_offset.min(split); + } + self.source_ranges + .retain(|range| range.start_offset < range.end_offset); + for range in &mut self.leveloffset_ranges { + range.end_offset = range.end_offset.min(split); + } + self.leveloffset_ranges + .retain(|range| range.start_offset < range.end_offset); + for scope in &mut self.leveloffset_scopes { + scope.range.end = scope.range.end.min(split); + } + self.leveloffset_scopes + .retain(|scope| scope.range.start < scope.range.end); + Some(blank) + } } impl<'input> InputCursor<'input> { + pub(super) fn can_finish_without_reading(&mut self) -> bool { + self.lines.peek().is_none() + && self + .include + .as_mut() + .is_none_or(|include| include.cursor.can_finish_without_reading()) + } + + /// The ordered consumer sees included output as it is read. The ordinary + /// `advance`/`read_all` path continues to merge each include only once. + pub(super) fn advance_emitted( + &mut self, + options: &mut Options<'_>, + ) -> Result, Error> { + if let Some(include) = self.include.take() { + return self.advance_include_emitted(include, options); + } + let start = self.out.byte_offset; + let source_count = self.out.source_ranges.len(); + let level_count = self.out.leveloffset_ranges.len(); + let scope_count = self.out.leveloffset_scopes.len(); + let origin = self.out.origin_of_line(self.line_number); + // A source with no preprocessing effects can be handed over as one + // borrowed chunk. Its blocks still commit individually in the driver. + self.skip_unchanged_input(options, true); + if self.out.byte_offset == start { + let Some(line) = self.lines.next() else { + return Ok(Advance::End); + }; + self.process_line(line, options)?; + self.line_number += 1; + } + let Some(text) = self.emitted_text(start) else { + return Ok(Advance::Progress(Vec::new())); + }; + let end = start + text.len(); + let mut source_ranges: Vec<_> = self + .out + .source_ranges + .iter() + .skip(source_count) + .filter(|range| range.end_offset > start) + .cloned() + .collect(); + if source_ranges.is_empty() { + source_ranges.push(crate::model::SourceRange { + start_offset: start, + end_offset: end, + file: self.out.source_file.as_deref().cloned(), + file_chain: Vec::new(), + start_line: origin.line, + source_start_offset: origin.offset, + column_shift: origin.column_shift, + }); + } + Ok(Advance::Progress(vec![Emission { + start, + text, + source_ranges, + leveloffset_ranges: self + .out + .leveloffset_ranges + .iter() + .skip(level_count) + .cloned() + .collect(), + leveloffset_scopes: self + .out + .leveloffset_scopes + .iter() + .skip(scope_count) + .cloned() + .collect(), + }])) + } + + fn advance_include_emitted( + &mut self, + mut include: IncludeFrame<'input>, + options: &mut Options<'_>, + ) -> Result, Error> { + let prefix_len = include.scope.as_ref().map_or(0, |scope| scope.prefix.len()); + if !include.prefix_emitted { + include.prefix_emitted = true; + if let Some(scope) = &include.scope { + let start = self.out.byte_offset; + let emission = Emission { + start, + text: self.arena.alloc_str(&scope.prefix), + source_ranges: Vec::new(), + leveloffset_ranges: Vec::new(), + leveloffset_scopes: vec![super::LeveloffsetScope { + range: start..start + prefix_len, + assignment: scope.current.clone(), + }], + }; + include.emitted_end = start + prefix_len; + self.include = Some(include); + return Ok(Advance::Progress(vec![emission])); + } + } + match include.cursor.advance_emitted(options)? { + Advance::Progress(emissions) => { + let mut output = Vec::new(); + for mut emission in emissions { + emission.prepend_include(&include.result, self.out.byte_offset + prefix_len); + if let Some(blank) = include.pending_blank.take() { + output.push(blank); + } + include.pending_blank = emission.take_final_blank(); + if !emission.text.is_empty() { + output.push(emission); + } + } + if let Some(last) = output.last() { + include.emitted_end = last.start + last.text.len(); + } + self.include = Some(include); + Ok(Advance::Progress(output)) + } + Advance::End => { + // The enclosing include removes one final newline. A + // pending empty line is therefore never exposed as text. + let result = include.cursor.read_all(options)?; + let suffix_start = self.out.byte_offset + prefix_len + result.text.len(); + // The child's provisional final newline can already serve + // as the first newline of the generated scope suffix. + let suffix_skip = include.emitted_end.saturating_sub(suffix_start); + let start = self.out.byte_offset; + let scope_count = self.out.leveloffset_scopes.len(); + let scoped = include.scope.is_some(); + self.finish_include( + include.result, + result, + include.input_line, + include.scope, + options, + )?; + let mut emissions = Vec::new(); + if scoped + && let Some(text) = self + .emitted_text(start) + .and_then(|text| text.get(suffix_start - start + suffix_skip..)) + { + emissions.push(Emission { + start: suffix_start + suffix_skip, + text, + source_ranges: Vec::new(), + leveloffset_ranges: Vec::new(), + leveloffset_scopes: self + .out + .leveloffset_scopes + .iter() + .skip(scope_count) + .filter(|scope| scope.range.end > suffix_start) + .cloned() + .collect(), + }); + } + Ok(Advance::Progress(emissions)) + } + } + } + + fn emitted_text(&self, start: usize) -> Option<&'input str> { + let mut remaining = self.out.byte_offset.checked_sub(start)?; + if remaining == 0 { + return None; + } + if start == 0 + && self.out.borrowed_run.is_none() + && let [Cow::Borrowed(text)] = self.out.output.as_slice() + && std::ptr::eq(text.as_ptr(), self.out.input.as_ptr()) + && text.len() == self.out.input.len() + { + return Some(self.arena.alloc_str(&format!("{text}\n"))); + } + let borrowed = self + .out + .borrowed_run + .as_ref() + .and_then(|range| self.out.input.get(range.clone())); + let mut pieces = Vec::new(); + for text in borrowed + .into_iter() + .chain(self.out.output.iter().rev().map(Cow::as_ref)) + { + let length = remaining.min(text.len() + 1); + let suffix = text.get(text.len() + 1 - length..)?; + pieces.push(suffix); + remaining -= length; + if remaining == 0 { + break; + } + } + if remaining != 0 { + return None; + } + if pieces.len() == 1 { + let text = pieces.pop()?; + let offset = (text.as_ptr() as usize).checked_sub(self.out.input.as_ptr() as usize); + if let Some(offset) = offset + && let Some(with_separator) = self.out.input.get(offset..offset + text.len() + 1) + && with_separator.ends_with('\n') + { + return Some(with_separator); + } + return Some(self.arena.alloc_str(&format!("{text}\n"))); + } + let mut joined = String::new(); + for piece in pieces.into_iter().rev() { + joined.push_str(piece); + joined.push('\n'); + } + Some(self.arena.alloc_str(&joined)) + } + pub(super) fn new( preprocessor: &Preprocessor, input: &'input str, @@ -74,6 +401,7 @@ impl<'input> InputCursor<'input> { conditionals: Vec::new(), front_matter, include: None, + bulk_consumed: false, } } @@ -259,6 +587,9 @@ impl<'input> InputCursor<'input> { cursor: Box::new(cursor), input_line: self.line_number, scope: input.scope, + pending_blank: None, + prefix_emitted: false, + emitted_end: self.out.byte_offset, }); } else { self.accept_include(included, self.line_number, options); @@ -298,8 +629,9 @@ impl<'input> InputCursor<'input> { Ok(()) } - fn skip_unchanged_include(&mut self, options: &Options<'_>) { - if self.preprocessor.include_context.depth == 0 + fn skip_unchanged_input(&mut self, options: &Options<'_>, include_root: bool) { + if (!include_root && self.preprocessor.include_context.depth == 0) + || self.bulk_consumed || self.line_number != 1 || self.front_matter.is_some() || self @@ -315,6 +647,7 @@ impl<'input> InputCursor<'input> { ) else { return; }; + self.bulk_consumed = true; for line in self.lines.by_ref() { self.out.note_source_line(self.line_number); self.out.byte_offset += line.len() + 1; @@ -328,7 +661,7 @@ impl<'input> InputCursor<'input> { mut self, options: &mut Options<'_>, ) -> Result, Error> { - self.skip_unchanged_include(options); + self.skip_unchanged_input(options, false); loop { if let Some(include) = self.include.take() { let result = include.cursor.read_all(options)?; diff --git a/acdc-parser/src/preprocessor/include.rs b/acdc-parser/src/preprocessor/include.rs index bf203d82e..736c34ace 100644 --- a/acdc-parser/src/preprocessor/include.rs +++ b/acdc-parser/src/preprocessor/include.rs @@ -392,10 +392,10 @@ pub(super) struct IncludeInput { #[derive(Debug)] pub(super) struct IncludeScope { - current: DocumentAttributeAssignment<'static>, + pub(super) current: DocumentAttributeAssignment<'static>, previous: DocumentAttributeAssignment<'static>, mode: CompatibilityMode, - prefix: String, + pub(super) prefix: String, suffix: String, } diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index ef37b0881..184847ad9 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -28,10 +28,12 @@ mod cursor; mod include; #[cfg(test)] mod include_budget_tests; +mod source; mod tag; use comment::CommentScanner; use include::{Include, IncludeResult, LocationContext}; +pub(crate) use source::SourceReader; /// Allows Secure-mode fallback processing when include loading is disabled. #[derive(Clone, Copy, Debug, Default)] @@ -48,7 +50,7 @@ impl IncludeSourceProvider for DeniedIncludeSourceProvider { /// Accepted value for a generated include scope entry. Its public text can /// remain literal when the grammar does not recognize an attribute entry. -#[derive(Debug)] +#[derive(Clone, Debug)] pub(crate) struct LeveloffsetScope { pub(crate) range: Range, pub(crate) assignment: crate::DocumentAttributeAssignment<'static>, diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs new file mode 100644 index 000000000..1e1557d16 --- /dev/null +++ b/acdc-parser/src/preprocessor/source.rs @@ -0,0 +1,190 @@ +//! Reader facade used by the ordered source-processing driver. + +use std::{ + cell::RefCell, + collections::{HashSet, VecDeque}, + path::Path, + rc::Rc, +}; + +use bumpalo::Bump; + +use crate::{ + Error, Options, + model::{LeveloffsetRange, SourceRange}, + warning::WarningCollection, +}; + +use super::{ + Preprocessor, PreprocessorResult, SourceOrigin, + cursor::{Advance, Emission, InputCursor}, + skim_front_matter, +}; + +pub(crate) struct SourceChunk<'a> { + pub(crate) start: usize, + pub(crate) text: &'a str, + pub(crate) source_ranges: Vec, + pub(crate) leveloffset_ranges: Vec, + pub(crate) leveloffset_scopes: Vec, +} + +pub(crate) struct SourceReader<'a> { + cursor: Option>, + unchanged: Option<&'a str>, + result: Option>, + pending: VecDeque>, + pub(crate) options: Options<'static>, +} + +impl<'a> SourceReader<'a> { + pub(crate) fn new( + input: &'a str, + file: Option<&Path>, + options: &Options<'_>, + warnings: Rc>, + arena: &'a Bump, + ) -> Result { + let origin = match file { + Some(file) => SourceOrigin::entry_file(file, options.base_dir.as_deref())?, + None => SourceOrigin::memory(options.base_dir.as_deref()), + }; + let preprocessor = Preprocessor::new(options, warnings); + let normalized = Preprocessor::normalize(input); + let normalized = match normalized { + std::borrow::Cow::Borrowed(text) => text, + std::borrow::Cow::Owned(text) => arena.alloc_str(&text), + }; + let front_matter = options + .document_attributes + .contains_key("skip-front-matter") + .then(|| skim_front_matter(normalized.lines())) + .flatten(); + let mut options = options.clone().into_static(); + if front_matter.is_none() + && let Some(scanner) = preprocessor.try_pass_through( + normalized, + crate::grammar::setext::is_enabled(options.compatibility_mode), + &options, + ) + { + return Ok(Self { + cursor: None, + unchanged: Some(normalized), + result: Some(PreprocessorResult { + text: std::borrow::Cow::Owned(normalized.to_owned()), + leveloffset_ranges: Preprocessor::initial_leveloffset_ranges( + normalized.len(), + &options, + ), + leveloffset_scopes: Vec::new(), + source_ranges: Vec::new(), + included_files: HashSet::default(), + conditionals: Vec::new(), + front_matter: None, + comment_context: scanner.block_context(), + }), + pending: VecDeque::new(), + options, + }); + } + let cursor = InputCursor::new( + &preprocessor, + normalized, + Some(&origin), + &mut options, + Vec::new(), + front_matter, + arena, + ); + Ok(Self { + cursor: Some(cursor), + unchanged: None, + result: None, + pending: VecDeque::new(), + options, + }) + } + + pub(crate) fn next(&mut self) -> Result>, Error> { + if let Some(text) = self.unchanged.take() { + return Ok((!text.is_empty()).then_some(SourceChunk { + start: 0, + text, + source_ranges: Vec::new(), + leveloffset_ranges: Vec::new(), + leveloffset_scopes: Vec::new(), + })); + } + loop { + if let Some(emission) = self.pending.pop_front() { + return Ok(Some(SourceChunk { + start: emission.start, + text: emission.text, + source_ranges: emission.source_ranges, + leveloffset_ranges: emission.leveloffset_ranges, + leveloffset_scopes: emission.leveloffset_scopes, + })); + } + let Some(cursor) = &mut self.cursor else { + return Ok(None); + }; + match cursor.advance_emitted(&mut self.options)? { + Advance::Progress(emissions) => { + self.pending.extend(emissions); + self.finish_if_exhausted()?; + } + Advance::End => return Ok(None), + } + } + } + + fn finish_if_exhausted(&mut self) -> Result<(), Error> { + if !self + .cursor + .as_mut() + .is_some_and(InputCursor::can_finish_without_reading) + { + return Ok(()); + } + let mut cursor = self + .cursor + .take() + .ok_or_else(|| std::io::Error::other("missing exhausted source cursor"))?; + while let Advance::Progress(emissions) = cursor.advance_emitted(&mut self.options)? { + self.pending.extend(emissions); + } + let result = cursor.read_all(&mut self.options)?; + let end = result.text.len(); + for emission in &mut self.pending { + emission.text = emission + .text + .get(..end.saturating_sub(emission.start).min(emission.text.len())) + .unwrap_or_default(); + for range in &mut emission.source_ranges { + range.end_offset = range.end_offset.min(end); + } + for range in &mut emission.leveloffset_ranges { + range.end_offset = range.end_offset.min(end); + } + for scope in &mut emission.leveloffset_scopes { + scope.range.end = scope.range.end.min(end); + } + } + self.pending.retain(|emission| !emission.text.is_empty()); + self.result = Some(result); + Ok(()) + } + + pub(crate) fn finish(mut self) -> Result, Error> { + if let Some(result) = self.result { + return Ok(result); + } + self.cursor + .ok_or_else(|| std::io::Error::other("missing source cursor"))? + .read_all(&mut self.options) + } +} + +#[cfg(test)] +mod tests; diff --git a/acdc-parser/src/preprocessor/source/tests.rs b/acdc-parser/src/preprocessor/source/tests.rs new file mode 100644 index 000000000..a39e3f7da --- /dev/null +++ b/acdc-parser/src/preprocessor/source/tests.rs @@ -0,0 +1,141 @@ +use std::rc::Rc; + +use crate::{CompatibilityMode, IncludeLoader, Options, SafeMode}; + +use super::{Preprocessor, SourceReader}; + +type TestResult = Result<(), Box>; + +#[test] +fn emitted_sources_preserve_complete_preprocessing_and_include_separators() -> TestResult { + let directory = tempfile::tempdir()?; + let file = directory.path().join("part.adoc"); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::System) + .with_base_dir(directory.path()) + .build()?; + for included in [ + "", + "\n", + "\n\n", + "a", + "a\n", + "a\n\n", + "a\n\n\n", + "é\r\n世界\n", + ":active:\n\nifdef::active[]\nselected\nendif::[]\n\n", + ] { + std::fs::write(&file, included)?; + for source in [ + "include::part.adoc[]", + "include::part.adoc[leveloffset=+1]", + "before\n\ninclude::part.adoc[]\n\nafter", + "before\n\ninclude::part.adoc[leveloffset=+1]\n\nafter", + "include::part.adoc[]\ninclude::part.adoc[]\nafter", + ] { + let arena = bumpalo::Bump::new(); + let expected = Preprocessor::process(source, &options, Rc::default())?; + let mut reader = SourceReader::new(source, None, &options, Rc::default(), &arena)?; + let mut text = String::new(); + while let Some(chunk) = reader.next()? { + assert_eq!( + chunk.start, + text.len(), + "{included:?} in {source:?}; emitted {text:?}, next {:?}", + chunk.text + ); + text.push_str(chunk.text); + assert!( + chunk + .source_ranges + .iter() + .all(|range| range.end_offset <= text.len()) + ); + } + let actual = reader.finish()?; + text.truncate(actual.text.len()); + assert_eq!(text, expected.text, "{included:?} in {source:?}"); + assert_eq!(actual.text, expected.text); + assert_eq!( + format!("{:?}", actual.source_ranges), + format!("{:?}", expected.source_ranges) + ); + } + } + } + Ok(()) +} + +#[test] +fn emitted_nested_include_pauses_before_later_directives() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write( + directory.path().join("outer.adoc"), + "configure::[]\n\nifdef::enabled[]\ninclude::inner.adoc[leveloffset=+1]\nendif::[]", + )?; + std::fs::write(directory.path().join("inner.adoc"), "== Inner\n\nText.")?; + let options = Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::System) + .with_base_dir(directory.path()) + .build()?; + let arena = bumpalo::Bump::new(); + let mut reader = SourceReader::new( + "include::outer.adoc[leveloffset=+1]\n\nAfter.", + None, + &options, + Rc::default(), + &arena, + )?; + let prefix = reader.next()?.ok_or("missing include scope")?; + assert_eq!(prefix.text, ":leveloffset: +1\n\n"); + assert_eq!(prefix.leveloffset_scopes.len(), 1); + let first = reader.next()?.ok_or("missing configure macro")?; + assert_eq!(first.text, "configure::[]\n"); + assert_eq!( + first + .source_ranges + .first() + .ok_or("missing source range")? + .file_chain, + ["outer.adoc"] + ); + reader + .options + .document_attributes + .set_text("enabled".into(), "".into()); + let mut text = format!("{}{}", prefix.text, first.text); + let mut inner = false; + while let Some(chunk) = reader.next()? { + eprintln!( + "chunk {} expected {}: {:?}", + chunk.start, + text.len(), + chunk.text + ); + assert_eq!(chunk.start, text.len()); + for range in &chunk.source_ranges { + if range.file_chain == ["outer.adoc", "inner.adoc"] { + inner = true; + assert_eq!( + chunk + .leveloffset_ranges + .iter() + .last() + .map(|offset| offset.value), + Some(2) + ); + } + } + text.push_str(chunk.text); + } + let result = reader.finish()?; + text.truncate(result.text.len()); + assert_eq!(text, result.text); + assert!(inner); + assert!(text.contains("== Inner")); + Ok(()) +} diff --git a/acdc-parser/src/source_tests.rs b/acdc-parser/src/source_tests.rs new file mode 100644 index 000000000..751c63d52 --- /dev/null +++ b/acdc-parser/src/source_tests.rs @@ -0,0 +1,488 @@ +use crate::{ + AttributeName, Block, CompatibilityMode, DocumentAttributeAssignment, Error, IncludeLoader, + Options, SafeMode, + extensions::{BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry}, + grammar::{ParserState, SourceHandler}, +}; + +type TestResult = Result<(), Box>; + +#[rstest::rstest] +#[case::setext("Title\n=====\nAuthor Name\n:thing: Value\n\nBody.")] +#[case::comment("////\nIgnored.\n\n:thing: hidden\n////\n= Title\nAuthor Name\n\nBody.")] +#[case::comment_gap("////\nIgnored.\n////\n\n\n= Title\n\nBody.")] +#[case::attributes(":thing: Value\n// Retained.\n= Title\n\nBody.")] +#[case::leading_blanks("\n\n= Title\n\nBody.")] +#[case::empty("")] +#[case::blank("\n\n")] +fn source_driver_preserves_prefix_forms(#[case] input: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + assert_equivalent(input, mode)?; + } + Ok(()) +} + +#[test] +fn source_driver_preserves_list_marker_matching() -> TestResult { + let input = include_str!("../fixtures/tests/list_marker_matching.adoc"); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + assert_equivalent(input, mode)?; + } + Ok(()) +} + +#[rstest::rstest] +#[case::untitled_header(":label: first \\\n= value owned by the attribute\n\nBody {label}.")] +#[case::header("= Document\n:label: first \\\n* value owned by the attribute\n\nBody {label}.")] +#[case::body("Before.\n\n:label: first \\\n* value owned by the attribute\n\nBody {label}.")] +#[case::attachment("* Item\n+\n:label: first \\\n* value owned by the attribute\n\nBody {label}.")] +#[case::hard_wrap( + "= Document\n:label: first + \\\n* value owned by the attribute\n\nBody {label}." +)] +#[case::eof(":label: first \\")] +fn source_driver_keeps_wrapped_attribute_entries_whole(#[case] input: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + assert_equivalent(input, mode)?; + } + Ok(()) +} +impl SourceHandler for () { + fn accepted<'a>( + &mut self, + _: &Block<'a>, + _: &ParserState<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, Error> { + Ok(Vec::new()) + } +} + +#[test] +fn source_driver_preserves_selected_include_origins_and_nested_base_directory() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::create_dir(directory.path().join("parts"))?; + std::fs::write( + directory.path().join("parts/outer.adoc"), + "Excluded.\n// tag::selected[]\n == Included\n\n include::inner.adoc[]\n// end::selected[]\nExcluded again.", + )?; + std::fs::write( + directory.path().join("parts/inner.adoc"), + "[id=target]\nCafé 世界 {counter:unsupported}.\n", + )?; + let input = + "= Entry\n\ninclude::parts/outer.adoc[tag=selected,indent=0,leveloffset=+1]\n\nAfter."; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let prepared = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::System) + .with_base_dir(directory.path()) + .build()? + .prepare_for_parse(crate::document_attribute::InputKind::String); + let warnings = std::rc::Rc::default(); + let preprocessed = crate::preprocessor::Preprocessor::process( + input, + &prepared, + std::rc::Rc::clone(&warnings), + )?; + let expected = crate::parse_input(preprocessed, prepared.clone(), None, warnings, None)?; + let actual = crate::parse_ordered_source( + input, + prepared, + None, + std::rc::Rc::default(), + None, + &mut (), + )?; + assert_eq!(actual.preprocessed_source(), expected.preprocessed_source()); + assert_eq!(actual.document_storage(), expected.document_storage()); + assert_eq!(actual.warnings(), expected.warnings()); + assert!( + actual.warnings().iter().any(|warning| matches!( + warning.kind, + crate::WarningKind::UnsupportedCounter { .. } + )) + ); + } + Ok(()) +} + +#[test] +fn nested_list_id_keeps_its_authored_position_in_a_compound_body() -> TestResult { + let input = "Before.\n\n====\n. Parent\n[id=child]\n.. Child\n===="; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let parsed = crate::parse(input, &options)?; + let Some(Block::DelimitedBlock(example)) = parsed.document_storage().blocks.get(1) else { + return Err("missing example".into()); + }; + let crate::DelimitedBlockType::DelimitedExample(body) = &example.inner else { + return Err("missing example body".into()); + }; + let Some(Block::OrderedList(parent)) = body.first() else { + return Err("missing parent list".into()); + }; + let Some(Block::OrderedList(child)) = + parent.items.first().and_then(|item| item.blocks.first()) + else { + return Err("missing child list".into()); + }; + let id = child.metadata.id.as_ref().ok_or("missing child ID")?; + assert_eq!(id.location.start, crate::Position::new(5, 5)); + assert_eq!( + id.location.absolute_start, + input.find("child").ok_or("missing authored ID")? + ); + } + Ok(()) +} + +pub(crate) fn assert_equivalent(input: &str, mode: CompatibilityMode) -> TestResult { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for input in [ + input.to_owned(), + format!("ifdef::source-driver-disabled[]\nremoved\nendif::[]\n{input}"), + ] { + let prepared = options + .clone() + .prepare_for_parse(crate::document_attribute::InputKind::String); + let warnings = std::rc::Rc::default(); + let preprocessed = crate::preprocessor::Preprocessor::process( + &input, + &prepared, + std::rc::Rc::clone(&warnings), + )?; + let expected = crate::parse_input(preprocessed, prepared.clone(), None, warnings, None)?; + let actual = crate::parse_ordered_source( + &input, + prepared, + None, + std::rc::Rc::default(), + None, + &mut (), + )?; + assert_eq!( + actual.preprocessed_source(), + expected.preprocessed_source(), + "{mode:?}" + ); + assert!( + actual.document_storage() == expected.document_storage(), + "{mode:?}: {}", + difference( + &serde_json::to_value(actual.document_storage())?, + &serde_json::to_value(expected.document_storage())?, + "document" + ) + .unwrap_or_else(|| "unserialized document state differs".into()) + ); + assert_eq!(actual.warnings(), expected.warnings(), "{mode:?}"); + } + Ok(()) +} + +fn difference( + actual: &serde_json::Value, + expected: &serde_json::Value, + path: &str, +) -> Option { + if actual == expected { + return None; + } + match (actual, expected) { + (serde_json::Value::Object(actual), serde_json::Value::Object(expected)) => { + for key in actual.keys().chain(expected.keys()) { + if let Some(difference) = + difference(&actual[key], &expected[key], &format!("{path}.{key}")) + { + return Some(difference); + } + } + } + (serde_json::Value::Array(actual), serde_json::Value::Array(expected)) + if actual.len() == expected.len() => + { + for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { + if let Some(difference) = difference(actual, expected, &format!("{path}[{index}]")) + { + return Some(difference); + } + } + } + _ => return Some(format!("{path}: actual {actual}, expected {expected}")), + } + None +} + +#[rstest::rstest] +#[case::unordered("* Parent\n+\n")] +#[case::ordered(". Parent\n+\n")] +#[case::nested("* Parent\n** Child\n+\n")] +#[case::description("term:: Parent\n+\n")] +#[case::callout("----\ncode <1>\n----\n\n<1> Parent\n+\n")] +fn source_driver_commits_list_attachment_before_later_directives( + #[case] prefix: &str, +) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = options(mode)?; + let input = format!( + "{prefix}configure::attached[]\n\nifdef::enabled[]\nSelected {{enabled}}.\nendif::[]" + ); + let mut handler = Configure::default(); + let parsed = crate::parse_with_source_handler(&input, &options, None, Some(&mut handler))?; + assert_eq!(handler.events, ["attached"]); + assert!( + parsed + .conditionals() + .next() + .ok_or("missing conditional")? + .is_active() + ); + assert!(serde_json::to_string(parsed.document_storage())?.contains("Selected yes.")); + } + Ok(()) +} + +#[test] +fn source_driver_preserves_reader_attributes_from_parser_lookahead() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = options(mode)?; + let mut handler = Configure::default(); + let parsed = crate::parse_with_source_handler( + "Paragraph.\n:reader-only:\n\nconfigure::first[]\n\nifdef::reader-only[]\nSelected {enabled}.\nendif::[]", + &options, + None, + Some(&mut handler), + )?; + assert!( + parsed + .conditionals() + .next() + .ok_or("missing conditional")? + .is_active() + ); + assert!(serde_json::to_string(parsed.document_storage())?.contains("Selected yes.")); + } + Ok(()) +} + +#[rstest::rstest] +#[case::compound("--\n", "\n--", true)] +#[case::table_cell("[cols=a]\n|===\na|", "\n|===", false)] +fn source_driver_preserves_buffered_body_and_cell_attribute_scope( + #[case] prefix: &str, + #[case] suffix: &str, + #[case] propagates: bool, +) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = options(mode)?; + let input = format!( + "{prefix}configure::inside[]\n\nifdef::enabled[]\nEarly.\nendif::[]{suffix}\n\nifdef::enabled[]\nLater.\nendif::[]" + ); + let mut handler = Configure::default(); + let parsed = crate::parse_with_source_handler(&input, &options, None, Some(&mut handler))?; + assert_eq!(handler.events, ["inside"]); + assert_eq!( + parsed + .conditionals() + .map(crate::ConditionalEvaluation::is_active) + .collect::>(), + [false, propagates] + ); + assert!(!parsed.preprocessed_source().contains("Early.")); + assert_eq!(parsed.preprocessed_source().contains("Later."), propagates); + } + Ok(()) +} + +#[test] +fn source_driver_respects_caller_attribute_locks_for_parser_and_reader() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write( + directory.path().join("caller.adoc"), + "Caller file {enabled}.", + )?; + std::fs::write(directory.path().join("yes.adoc"), "Wrong file.")?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = options(mode)? + .into_builder() + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::System) + .with_base_dir(directory.path()) + .with_attribute("enabled", "caller") + .build()?; + let mut handler = Configure::default(); + let parsed = crate::parse_with_source_handler( + "configure::locked[]\n\ninclude::{enabled}.adoc[]", + &options, + None, + Some(&mut handler), + )?; + assert_eq!(handler.events, ["locked"]); + assert!(parsed.preprocessed_source().contains("Caller file")); + assert!(serde_json::to_string(parsed.document_storage())?.contains("Caller file caller.")); + } + Ok(()) +} + +struct Failed; + +impl SourceHandler for Failed { + fn accepted<'a>( + &mut self, + block: &Block<'a>, + _: &ParserState<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, Error> { + if let Block::Extension(extension) = block { + Err(Error::Extension( + Box::new(extension.invocation.location.clone()), + "stop source processing".into(), + )) + } else { + Ok(Vec::new()) + } + } +} + +struct CountReads(std::sync::Arc); + +impl crate::IncludeSourceProvider for CountReads { + fn open( + &self, + _: &crate::IncludeSourceTarget, + ) -> Result { + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok(crate::IncludeSource::from_bytes(b"Later include.".to_vec())) + } +} + +#[rstest::rstest] +#[case::top("", "")] +#[case::section("== Section\n\n", "")] +#[case::list("* Item\n+\n", "")] +#[case::description("term:: Item\n+\n", "")] +#[case::compound("--\n", "\n--")] +#[case::table_cell("[cols=a]\n|===\na|", "\n|===")] +fn source_driver_handler_failure_prevents_later_include_reads( + #[case] prefix: &str, + #[case] suffix: &str, +) -> TestResult { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let reads = Arc::new(AtomicUsize::default()); + let options = options(mode)? + .into_builder() + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::Custom(Arc::new(CountReads(Arc::clone( + &reads, + ))))) + .with_base_dir("/virtual") + .build()?; + let input = format!("{prefix}configure::fail[]{suffix}\n\ninclude::later.adoc[]"); + let result = crate::parse_with_source_handler(&input, &options, None, Some(&mut Failed)); + assert!(matches!(result, Err(Error::Extension(..))), "{result:?}"); + assert_eq!(reads.load(Ordering::Relaxed), 0); + } + Ok(()) +} + +struct Never; + +impl BlockMacroProcessor for Never { + fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + Err("public callbacks must retain their post-acceptance boundary".into()) + } +} + +#[derive(Default)] +struct Configure { + events: Vec, +} + +impl SourceHandler for Configure { + fn accepted<'a>( + &mut self, + block: &Block<'a>, + _: &ParserState<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, Error> { + let Block::Extension(extension) = block else { + return Ok(Vec::new()); + }; + self.events.push(extension.invocation.target.to_string()); + Ok(vec![( + "enabled".into(), + DocumentAttributeAssignment::Set("yes".into()), + )]) + } +} + +fn options(mode: CompatibilityMode) -> Result, Box> { + let mut registry = Registry::builder(); + registry.register(BlockMacro::new("configure", || Never))?; + let mut options = Options::builder().with_compatibility_mode(mode).build()?; + options.extensions = Some(registry.build()); + Ok(options) +} + +#[test] +fn source_driver_commits_macro_before_reading_later_conditionals() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = options(mode)?; + let mut handler = Configure::default(); + let parsed = crate::parse_with_source_handler( + "configure::first[]\n\nifdef::enabled[]\nSelected {enabled}.\nendif::[]", + &options, + None, + Some(&mut handler), + )?; + assert_eq!(handler.events, ["first"]); + assert!(parsed.preprocessed_source().contains("Selected {enabled}.")); + assert!( + parsed + .conditionals() + .next() + .ok_or("missing conditional")? + .is_active() + ); + let document = serde_json::to_string(parsed.document_storage())?; + assert!(document.contains("Selected yes."), "{document}"); + } + Ok(()) +} + +#[test] +fn source_driver_commits_inside_include_before_later_directives() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write( + directory.path().join("outer.adoc"), + "== Included\n\nconfigure::inside[]\n\nifdef::enabled[]\ninclude::inner.adoc[leveloffset=+1]\nendif::[]", + )?; + std::fs::write( + directory.path().join("inner.adoc"), + "== Inner\n\nSelected {enabled}.", + )?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = options(mode)? + .into_builder() + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::System) + .with_base_dir(directory.path()) + .build()?; + let mut handler = Configure::default(); + let parsed = crate::parse_with_source_handler( + "include::outer.adoc[]\n\n== After\n\nLast.", + &options, + None, + Some(&mut handler), + )?; + assert_eq!(handler.events, ["inside"]); + let document = serde_json::to_string(parsed.document_storage())?; + assert!(document.contains("Selected yes."), "{document}"); + assert!(document.contains("inner.adoc")); + assert!(parsed.preprocessed_source().contains("== Inner")); + } + Ok(()) +} From 1dcc2452de18ec7b56b301f3e0fdeb33745399db Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 12 Nov 2026 21:39:45 +0100 Subject: [PATCH 07/55] perf(parser): preserve fast paths in committed source construction Keep ordinary documents on the direct shared grammar and reuse unchanged source storage in the ordered driver. Reduce deferred-block copies and list allocations, and narrow the source-handler context to host-owned effects. Preserve fatal source failures through nested-list recovery. Cover source order, buffered input, attribute-driven styles, and retained source storage. Refs SC-535. --- acdc-parser/CHANGELOG.md | 8 +- acdc-parser/benches/parser_bench.rs | 84 +++++- .../src/grammar/document/construction.rs | 61 ++--- .../src/grammar/document/coordinator.rs | 56 +++- acdc-parser/src/grammar/document/input.rs | 5 + acdc-parser/src/grammar/document/lists.rs | 24 +- .../grammar/document/lists/construction.rs | 55 ++-- .../src/grammar/document/lists/description.rs | 18 +- acdc-parser/src/grammar/document/peg.rs | 218 ++++++++++------ acdc-parser/src/grammar/document/source.rs | 242 +++++++++++++---- acdc-parser/src/grammar/source.rs | 15 +- acdc-parser/src/grammar/source/tests.rs | 34 +++ acdc-parser/src/grammar/state.rs | 17 +- acdc-parser/src/lib.rs | 68 +++-- acdc-parser/src/parsed.rs | 51 +++- acdc-parser/src/preprocessor/cursor.rs | 4 +- acdc-parser/src/preprocessor/mod.rs | 15 +- acdc-parser/src/preprocessor/source.rs | 74 ++++-- acdc-parser/src/preprocessor/source/tests.rs | 2 +- acdc-parser/src/source_tests.rs | 244 +++++++++++++++++- 20 files changed, 962 insertions(+), 333 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index fe431595a..78cbe2fc1 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -201,10 +201,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 cannot change later includes or conditionals, unlike source-changing Asciidoctor extensions. -- Faster parsing of paragraphs, mixed ASCII and Unicode text, formatting, inline - passthroughs, and duplicated ordinary table cells (`3*|text`) in both - compatibility modes, including text expanded from attributes, while - preserving substitution rules and source locations. +- Faster parsing of paragraphs, deeply nested blocks, mixed ASCII and Unicode + text, formatting, inline passthroughs, and duplicated ordinary table cells + (`3*|text`) in both compatibility modes, including text expanded from + attributes, while preserving substitution rules and source locations. - Keyboard macros with deeply nested brackets no longer abort parsing with a stack overflow when `:experimental:` is enabled. Both compatibility modes diff --git a/acdc-parser/benches/parser_bench.rs b/acdc-parser/benches/parser_bench.rs index dd0ef640c..2e93d2286 100644 --- a/acdc-parser/benches/parser_bench.rs +++ b/acdc-parser/benches/parser_bench.rs @@ -1,6 +1,10 @@ -use std::{fs, hint::black_box, time::Duration}; +use std::{fmt::Write as _, fs, hint::black_box, time::Duration}; -use acdc_parser::{Options, Parser, parse, parse_file}; +use acdc_parser::{ + Options, Parser, + extensions::{BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry}, + parse, parse_file, +}; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; #[allow(clippy::expect_used)] @@ -201,11 +205,85 @@ fn diagnostic_collection_benchmark(c: &mut Criterion) { group.finish(); } +struct CheapMacro; + +impl BlockMacroProcessor for CheapMacro { + fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result { + black_box(invocation); + Ok(BlockMacroOutput::None) + } +} + +#[allow(clippy::expect_used)] +fn extension_benchmark(c: &mut Criterion) { + let mut group = c.benchmark_group("extensions"); + let options = Options::default(); + let ordinary = include_str!("../fixtures/tests/basic_header.adoc"); + let empty = Registry::default(); + let mut builder = Registry::builder(); + for index in 0..100 { + builder + .register(BlockMacro::new(format!("cheap{index}"), || CheapMacro)) + .expect("valid benchmark registration"); + } + let registered = builder.build(); + group.bench_function("empty_registry", |b| { + b.iter(|| black_box(empty.parse(black_box(ordinary), &options))); + }); + group.bench_function("unused_registrations_100", |b| { + b.iter(|| black_box(registered.parse(black_box(ordinary), &options))); + }); + let macros = "cheap0::target[]\n\n".repeat(1000); + assert!(registered.parse(¯os, &options).is_ok()); + group.bench_function("cheap_callbacks_1000", |b| { + b.iter(|| black_box(registered.parse(black_box(¯os), &options))); + }); + let mut nested = String::new(); + for section in 0..1000 { + writeln!( + nested, + "== Section {section}\n\n====\n****\n* Parent\n** Child\n****\n====\n" + ) + .expect("write benchmark input"); + } + assert!(parse(&nested, &options).is_ok()); + group.bench_function("large_nested", |b| { + b.iter(|| black_box(parse(black_box(&nested), &options))); + }); + group.finish(); +} + +// This only uses the standard library. It controls for machine drift and +// binary layout without exercising the parser's changed coordinate adapters. +#[inline(never)] +fn source_line_lengths(input: &str) -> usize { + input.lines().map(str::len).sum() +} + +#[inline(never)] +fn source_checksum(input: &str) -> u64 { + input.bytes().fold(0_u64, |checksum, byte| { + checksum.wrapping_mul(31).wrapping_add(u64::from(byte)) + }) +} + +fn unchanged_control_benchmark(c: &mut Criterion) { + let input = include_str!("../../ARCHITECTURE.adoc"); + c.bench_function("unchanged/source_line_lengths", |b| { + b.iter(|| black_box(source_line_lengths(black_box(input)))); + }); + c.bench_function("unchanged/source_checksum", |b| { + b.iter(|| black_box(source_checksum(black_box(input)))); + }); +} + criterion_group!( benches, parse_benchmark, inline_scanning_benchmark, attribute_declaration_benchmark, - diagnostic_collection_benchmark + diagnostic_collection_benchmark, + extension_benchmark, + unchanged_control_benchmark ); criterion_main!(benches); diff --git a/acdc-parser/src/grammar/document/construction.rs b/acdc-parser/src/grammar/document/construction.rs index 903835d9d..844655e76 100644 --- a/acdc-parser/src/grammar/document/construction.rs +++ b/acdc-parser/src/grammar/document/construction.rs @@ -1,7 +1,5 @@ //! Requests retained after a block recognizer has returned. -use std::ops::ControlFlow; - use crate::{ Block, Error, grammar::{ParserState, helpers::BlockParsingMetadata}, @@ -12,56 +10,27 @@ use super::{ delimited::{ ContentParser, ContentRequest, DelimitedParams, build_delimited_block_with_parser, }, - lists::{ListEntry, ListKind}, metadata::assign_block_caption, quotes::{QuoteParams, build_quote_with_parser}, - table::{TableParseParams, construction::TableConstruction}, }; -/// Shared block dispatch retains the metadata until its content form commits. -pub(super) type RecognizedContent<'a> = ControlFlow, Block<'a>>; - -pub(super) enum DeferredContent<'a> { - Delimited(DelimitedParams<'a>), - Table(TableParseParams<'a>), - Quote(QuoteParams<'a>), - List { - start: usize, - body_offset: usize, - kind: ListKind<'a>, - }, -} - +/// Attach metadata after the content alternative commits. Keeping the final +/// step representation avoids copying ready blocks through another large enum. +#[inline] pub(super) fn commit_content<'a>( - state: &mut ParserState<'a>, + state: &ParserState<'a>, metadata: BlockParsingMetadata<'a>, - content: RecognizedContent<'a>, + mut content: BlockStepKind<'a>, ) -> BlockStepKind<'a> { - match content { - ControlFlow::Continue(mut block) => { - assign_block_caption(state, &mut block); - BlockStepKind::Block(block) - } - ControlFlow::Break(DeferredContent::Delimited(params)) => { - BlockStepKind::Delimited(DelimitedConstruction { metadata, params }) - } - ControlFlow::Break(DeferredContent::Table(params)) => { - BlockStepKind::Table(TableConstruction { metadata, params }) - } - ControlFlow::Break(DeferredContent::Quote(params)) => { - BlockStepKind::Quote(QuoteConstruction { metadata, params }) - } - ControlFlow::Break(DeferredContent::List { - start, - body_offset, - kind, - }) => BlockStepKind::List(ListEntry { - start, - body_offset, - metadata: Some(metadata), - kind, - }), + match &mut content { + BlockStepKind::Block(block) => assign_block_caption(state, block), + BlockStepKind::Delimited(request) => request.metadata = metadata, + BlockStepKind::Table(request) => request.metadata = metadata, + BlockStepKind::Quote(request) => request.metadata = metadata, + BlockStepKind::List(entry) => entry.metadata = Some(Box::new(metadata)), + BlockStepKind::End(_) => {} } + content } /// Ordinary parsing retains complete PEG construction. The ordered mode @@ -78,8 +47,8 @@ pub(super) struct DelimitedConstruction<'a> { } pub(super) struct QuoteConstruction<'a> { - metadata: BlockParsingMetadata<'a>, - params: QuoteParams<'a>, + pub(super) metadata: BlockParsingMetadata<'a>, + pub(super) params: QuoteParams<'a>, } impl<'a> QuoteConstruction<'a> { diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index 14b1f01b4..34fa71961 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -34,6 +34,7 @@ impl<'handler, F> Execution<'handler, F> { failed: false, } } + #[inline] pub(super) fn run<'a>( &mut self, block: &Block<'a>, @@ -89,6 +90,7 @@ impl<'a> BlockStep<'a> { } impl<'a> BlockStepKind<'a> { + #[inline] pub(super) fn into_ready(self, state: &ParserState<'a>) -> Result, Error> { if let Self::Block(block) = self { Ok(block) @@ -124,6 +126,7 @@ impl BlockCursor { } } + #[inline] pub(super) fn advance<'a>( &mut self, input: &'a str, @@ -186,29 +189,36 @@ impl BlockCursor { *blocks = order_block_prefix_events(std::mem::take(blocks)); return Ok(Ok(self.base_offset + step.end)); } + BlockStepKind::Block(block) if !matches!(block, Block::Section(_)) => { + if let Err(error) = accepted.run(&block, state) { + return Ok(Err(error)); + } + blocks.push(block); + continue; + } kind @ (BlockStepKind::Block(_) | BlockStepKind::Delimited(_) | BlockStepKind::Table(_) | BlockStepKind::List(_) | BlockStepKind::Quote(_)) => kind, }; - match self.construct(input, state, kind, accepted)? { - Ok(block) => blocks.push(block), - Err(error) => return Ok(Err(error)), + if let Err(error) = self.construct_into(input, state, kind, blocks, accepted)? { + return Ok(Err(error)); } } } - pub(super) fn construct<'a>( + pub(super) fn construct_into<'a>( &mut self, input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, kind: BlockStepKind<'a>, + output: &mut Vec>, accepted: &mut Execution< '_, impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, >, - ) -> Result, Error>, RecognitionError> { + ) -> Result, RecognitionError> { let needs_caption = matches!( &kind, BlockStepKind::Delimited(_) | BlockStepKind::Table(_) | BlockStepKind::Quote(_) @@ -216,13 +226,14 @@ impl BlockCursor { let mut table_content = None; let (mut block, request) = match kind { BlockStepKind::List(entry) => { - return self.construct_list( + return self.construct_list_into( input, state, &entry, &crate::grammar::helpers::BlockParsingMetadata::new( state.options.compatibility_mode, ), + output, accepted, ); } @@ -294,7 +305,8 @@ impl BlockCursor { } assign_block_caption(state, &mut block); } - Ok(Ok(block)) + output.push(block); + Ok(Ok(())) } } @@ -392,16 +404,34 @@ pub(crate) fn document<'a>( ) -> Result, Error>, RecognitionError> { // Registry callbacks still run after parsing. A registry alone must not // change construction or diagnostic order before source handlers are wired. - document_with( - input, + let prefix = match document_parser::document_prefix(input, state)? { + Ok(prefix) => prefix, + Err(error) => return Ok(Err(error)), + }; + let mut blocks = prefix.comments; + let end = match document_parser::remaining_blocks(input, state, prefix.body_offset)? { + Ok((body, end)) => { + if blocks.is_empty() { + blocks = body; + } else { + blocks.extend(body); + } + end + } + Err(error) => return Ok(Err(error)), + }; + Ok(finish::finish( state, - ConstructionMode::Recursive, - &mut |_, _| Ok(()), - ) + prefix.start, + end, + prefix.header, + prefix.attributes, + order_block_prefix_events(blocks), + )) } /// Internal accepted-block execution boundary for documents and containers. -/// Source reading still advances independently of these commits. +/// Complete input uses the same ordered builders as the resumable source path. pub(super) fn document_with<'a>( input: &'a str, state: &mut ParserState<'a>, diff --git a/acdc-parser/src/grammar/document/input.rs b/acdc-parser/src/grammar/document/input.rs index b50f0e8d1..0c2c1d112 100644 --- a/acdc-parser/src/grammar/document/input.rs +++ b/acdc-parser/src/grammar/document/input.rs @@ -16,6 +16,11 @@ pub(super) enum ReadRequest<'a> { } pub(super) trait BlockInput<'a> { + /// Source failures cannot be recovered as malformed nested content. + fn failed(&self) -> bool { + false + } + fn prepare( &mut self, cursor: &mut BlockCursor, diff --git a/acdc-parser/src/grammar/document/lists.rs b/acdc-parser/src/grammar/document/lists.rs index a75bfe252..15dd97e24 100644 --- a/acdc-parser/src/grammar/document/lists.rs +++ b/acdc-parser/src/grammar/document/lists.rs @@ -13,7 +13,7 @@ use crate::{ model::ListLevel, }; use bumpalo::collections::String as BumpString; -use std::{collections::VecDeque, ops::ControlFlow}; +use std::collections::VecDeque; use super::metadata::order_block_prefix_events; @@ -36,7 +36,9 @@ pub(super) struct OrdinaryListKind<'a> { pub(super) struct ListEntry<'a> { pub(super) start: usize, pub(super) body_offset: usize, - pub(super) metadata: Option>, + // Most implicit ordinary children inherit their parent's metadata. Keep + // that request small; other contexts retain their own metadata separately. + pub(super) metadata: Option>>, pub(super) kind: ListKind<'a>, } @@ -47,8 +49,22 @@ pub(super) enum ListPhase { Sibling, } -pub(super) type ListStepKind<'a> = - ControlFlow, Error>, Option>>; +pub(super) enum ListStepKind<'a> { + List(ListEntry<'a>), + // Keep the common principal/sibling steps small. Only an attached block + // needs storage for the much larger general construction request. + Block(Box, Error>>), + Continue(Option>), +} + +impl<'a> ListStepKind<'a> { + pub(super) fn block(result: Result, Error>) -> Self { + match result { + Ok(super::coordinator::BlockStepKind::List(entry)) => Self::List(entry), + result @ (Ok(_) | Err(_)) => Self::Block(Box::new(result)), + } + } +} pub(super) struct ListStep<'a> { pub(super) kind: ListStepKind<'a>, diff --git a/acdc-parser/src/grammar/document/lists/construction.rs b/acdc-parser/src/grammar/document/lists/construction.rs index 878261563..71158796d 100644 --- a/acdc-parser/src/grammar/document/lists/construction.rs +++ b/acdc-parser/src/grammar/document/lists/construction.rs @@ -18,25 +18,30 @@ use super::{ }; impl BlockCursor { - pub(in crate::grammar::document) fn construct_list<'a>( + pub(in crate::grammar::document) fn construct_list_into<'a>( &mut self, input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, entry: &ListEntry<'a>, parent_metadata: &BlockParsingMetadata<'a>, + output: &mut Vec>, accepted: &mut Execution< '_, impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, >, - ) -> Result, Error>, RecognitionError> { - let metadata = entry.metadata.as_ref().unwrap_or(parent_metadata); + ) -> Result, RecognitionError> { + let metadata = entry.metadata.as_deref().unwrap_or(parent_metadata); let start = entry.start + self.base_offset; self.offset = entry.body_offset; if matches!(entry.kind, ListKind::Callout) { - return self.construct_callout_list(input, state, start, metadata, accepted); + return self + .construct_callout_list(input, state, start, metadata, accepted) + .map(|result| result.map(|block| output.push(block))); } if matches!(entry.kind, ListKind::Description) { - return self.construct_description_list(input, state, start, metadata, accepted); + return self + .construct_description_list(input, state, start, metadata, accepted) + .map(|result| result.map(|block| output.push(block))); } let source = match input.prepare(self, state, ReadRequest::ListHead(entry.kind)) { Ok(source) => source, @@ -54,9 +59,9 @@ impl BlockCursor { let result = self.construct_ordinary_list( input, state, - (entry.kind, start), + (entry.kind, start, head), metadata, - head, + output, accepted, ); state.ordinary_list_scope = parent_scope; @@ -67,15 +72,15 @@ impl BlockCursor { &mut self, input: &mut impl BlockInput<'a>, state: &mut ParserState<'a>, - frame: (ListKind<'a>, usize), + frame: (ListKind<'a>, usize, ListItemHead<'a>), metadata: &BlockParsingMetadata<'a>, - head: ListItemHead<'a>, + output: &mut Vec>, accepted: &mut Execution< '_, impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, >, - ) -> Result, Error>, RecognitionError> { - let (list_kind, start) = frame; + ) -> Result, RecognitionError> { + let (list_kind, start, head) = frame; let Some((ordered, kind)) = ordinary_parts(list_kind) else { return Ok(Err(list_error( state, @@ -103,11 +108,11 @@ impl BlockCursor { if let Err(error) = accepted.run(&block, state) { return Ok(Err(error)); } - item = match take_first_item(&mut block, state, start) { + let mut items = Vec::new(); + item = match take_first_item(&mut block, state, start, &mut items) { Ok(item) => item, Err(error) => return Ok(Err(error)), }; - let mut items = Vec::new(); loop { item.blocks = match self.collect_list_children( input, @@ -169,7 +174,8 @@ impl BlockCursor { if let Some(slot) = crate::extensions::ordinary_list_items_mut(&mut block) { *slot = items; } - return Ok(Ok(block)); + output.push(block); + return Ok(Ok(())); } } } @@ -206,11 +212,13 @@ impl BlockCursor { )?; self.offset = step.end; let child = match step.kind { - ListStepKind::Break(Ok(super::super::coordinator::BlockStepKind::List(entry))) => { - self.construct_list(input, state, &entry, metadata, accepted)? + ListStepKind::List(entry) => { + self.construct_list_into(input, state, &entry, metadata, &mut blocks, accepted)? } - ListStepKind::Break(Ok(kind)) => self.construct(input, state, kind, accepted)?, - ListStepKind::Break(Err(error)) => Err(error), + ListStepKind::Block(child) => match *child { + Ok(kind) => self.construct_into(input, state, kind, &mut blocks, accepted)?, + Err(error) => Err(error), + }, ListStepKind::Continue(None) if phase == ListPhase::AfterPrincipal => { phase = ListPhase::Attachments; continue; @@ -218,9 +226,10 @@ impl BlockCursor { ListStepKind::Continue(None | Some(_)) => break, }; match child { - Ok(block) => blocks.push(block), + Ok(()) => {} Err(_) if !accepted.failed() + && !input.failed() && matches!(kind, ListKind::Unordered(_) | ListKind::Ordered(_)) => {} Err(error) => return Ok(Err(error)), } @@ -249,8 +258,12 @@ fn take_first_item<'a>( block: &mut Block<'a>, state: &ParserState<'a>, start: usize, + items: &mut Vec>, ) -> Result, Error> { - crate::extensions::ordinary_list_items_mut(block) - .and_then(Vec::pop) + let slot = crate::extensions::ordinary_list_items_mut(block) + .ok_or_else(|| list_error(state, start, "ordinary list builder returned no first item"))?; + *items = std::mem::take(slot); + items + .pop() .ok_or_else(|| list_error(state, start, "ordinary list builder returned no first item")) } diff --git a/acdc-parser/src/grammar/document/lists/description.rs b/acdc-parser/src/grammar/document/lists/description.rs index 72cec467c..e06be8e8d 100644 --- a/acdc-parser/src/grammar/document/lists/description.rs +++ b/acdc-parser/src/grammar/document/lists/description.rs @@ -185,17 +185,23 @@ impl BlockCursor { return Ok(Ok(children)); }; let child = match child { - Ok(BlockStepKind::List(entry)) => { - self.construct_list(input, state, &entry, metadata, accepted)? + Ok(BlockStepKind::List(entry)) => self.construct_list_into( + input, + state, + &entry, + metadata, + &mut children.blocks, + accepted, + )?, + Ok(kind) => { + self.construct_into(input, state, kind, &mut children.blocks, accepted)? } - Ok(kind) => self.construct(input, state, kind, accepted)?, Err(error) => Err(error), }; match child { - Ok(block) => children.blocks.push(block), - Err(error) if accepted.failed() => return Ok(Err(error)), + Err(error) if accepted.failed() || input.failed() => return Ok(Err(error)), Err(error) if step.warn_on_error => children.errors.push(error), - Err(_) => {} + Ok(()) | Err(_) => {} } } } diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index b3c9bf874..7a85512d3 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -19,7 +19,9 @@ use crate::{ }, document::{ author::{derive_author_attrs, register_author_attrs}, - construction::{ConstructionMode, DeferredContent, RecognizedContent, commit_content}, + construction::{ + ConstructionMode, DelimitedConstruction, QuoteConstruction, commit_content, + }, coordinator::{BlockParent, BlockStep, BlockStepKind, DocumentPrefix, NestedPrefix}, delimited::{DelimitedKind, DelimitedParams, build_delimited_block}, doctype::{is_book_doctype, is_manpage_doctype}, @@ -38,9 +40,9 @@ use crate::{ }, metadata::{ AttributeBlockForm, AttributeOrAnchorLine, BlockMetadataLine, MetadataComment, - ParsedAttributeList, RawAttributeList, TitleSource, finish_block_parsing_metadata, - media_attributes_ahead, merge_macro_metadata, metadata_comment, - metadata_marks_discrete_heading, order_block_prefix_events, + ParsedAttributeList, RawAttributeList, TitleSource, assign_block_caption, + finish_block_parsing_metadata, media_attributes_ahead, merge_macro_metadata, + metadata_comment, metadata_marks_discrete_heading, order_block_prefix_events, parse_block_attribute_list, push_metadata_anchor, resolve_block_content_attributes, resolve_title, route_block_positions, route_media_attributes, select_heading_style, thematic_break_anchors, @@ -53,7 +55,7 @@ use crate::{ source::{SourceLine, ordinary_kind}, table::{ InitialAttributes, PreparedTableCellParagraph, TableClosing, TableParseParams, - parse_table_block_impl, + construction::TableConstruction, parse_table_block_impl, }, }, helpers::{ @@ -105,11 +107,21 @@ peg::parser! { } }} + // Inactive source handling can collect the complete body directly. + // Reuse ordinary construction without moving each accepted block + // through the ordered driver's larger construction-request enum. + pub(in crate::grammar::document) rule remaining_blocks(offset: usize) -> Result<(Vec>, usize), Error> + = resume_at(offset) blocks:blocks(0, None, None) end:position!() eol()* + { blocks.map(|blocks| (blocks, end)) } + #[no_eof] pub(in crate::grammar::document) rule next_block(offset: usize, base_offset: usize, parent: BlockParent, mode: ConstructionMode) -> Result, Error> = resume_at(offset) step:( !trailing_block_metadata_match() - block:recognized_block(base_offset, parent.level, parent.kind, mode) + block:( + ordered_construction(mode) block:recognized_block(base_offset, parent.level, parent.kind, mode) { block } + / recursive_construction(mode) block:block(base_offset, parent.level, parent.kind) { block.map(BlockStepKind::Block) } + ) end:position!() { block.map(|kind| BlockStep { kind, end }) } / eol()* &same_or_higher_level_section(base_offset, parent.level) @@ -170,7 +182,18 @@ peg::parser! { = quoted_paragraph_params(0, 0) (eol() / ![_]) rule ordered_construction(mode: ConstructionMode) - = {? matches!(mode, ConstructionMode::Ordered).then_some(()).ok_or("recursive construction") } + = #{|_, position| if matches!(mode, ConstructionMode::Ordered) { + peg::RuleResult::Matched(position, ()) + } else { + peg::RuleResult::Failed + }} + + rule recursive_construction(mode: ConstructionMode) + = #{|_, position| if matches!(mode, ConstructionMode::Recursive) { + peg::RuleResult::Matched(position, ()) + } else { + peg::RuleResult::Failed + }} pub(in crate::grammar::document) rule block_sequence_end(offset: usize) = resume_at(offset) eol()* @@ -749,7 +772,7 @@ peg::parser! { } pub(in crate::grammar::document) rule blocks(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result>, Error> - = blocks:(!trailing_block_metadata_match() block:block(offset, parent_section_level, direct_parent_section_kind, ConstructionMode::Recursive) { block })* + = blocks:(!trailing_block_metadata_match() block:block(offset, parent_section_level, direct_parent_section_kind) { block })* trailing:trailing_block_metadata(offset)? { let mut blocks = blocks.into_iter().collect::, Error>>()?; @@ -841,9 +864,19 @@ peg::parser! { blocks.into_iter().collect() } - rule block(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option, mode: ConstructionMode) -> Result, Error> - = value:recognized_block(offset, parent_section_level, direct_parent_section_kind, mode) - { value.and_then(|value| value.into_ready(state)) } + // Ordinary children return blocks directly instead of copying them + // through the ordered driver's deferred-construction representation. + // Both dispatchers use the same syntax recognizers and node builders. + rule block(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result, Error> + = eol()* !same_or_higher_level_section(offset, parent_section_level) + block:( + comment_line_block(offset) + / document_attribute_block(offset) + / &"[" block:discrete_header(offset) { block } + / section(offset, parent_section_level, direct_parent_section_kind, ConstructionMode::Recursive) + / section_setext(offset, parent_section_level, direct_parent_section_kind, ConstructionMode::Recursive) + / block_generic(offset, parent_section_level) + ) { block } rule recognized_block(offset: usize, parent_section_level: Option, direct_parent_section_kind: Option, mode: ConstructionMode) -> Result, Error> = eol()* @@ -861,7 +894,34 @@ peg::parser! { section:section(offset, parent_section_level, direct_parent_section_kind, mode) { section.map(BlockStepKind::Block) } / // Legacy underlined sections are recognized in Asciidoctor mode. section_setext:section_setext(offset, parent_section_level, direct_parent_section_kind, mode) { section_setext.map(BlockStepKind::Block) } / - block_generic(offset, parent_section_level, mode) + ( + start:position!() + block_metadata:(bm:block_metadata(offset, parent_section_level) {? + bm.map_err(|_| { + tracing::error!("error parsing block metadata in block_generic"); + "block metadata parse error" + }) + }) + block:( + ordered_construction(mode) params:generic_delimited_params(start, offset) { Ok(BlockStepKind::Delimited(DelimitedConstruction { metadata: BlockParsingMetadata::default(), params })) } + / ordered_construction(mode) params:table_params(start, offset) { Ok(BlockStepKind::Table(TableConstruction { metadata: BlockParsingMetadata::default(), params })) } + / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim.map(BlockStepKind::Block) } + / recovered:excessive_list_item(start, offset, &block_metadata) { recovered.map(BlockStepKind::Block) } + / extension:extension_macro(start, offset, &block_metadata) { extension.map(BlockStepKind::Block) } + / image:image(start, offset, &block_metadata) { image.map(BlockStepKind::Block) } + / audio:audio(start, offset, &block_metadata) { audio.map(BlockStepKind::Block) } + / video:video(start, offset, &block_metadata) { video.map(BlockStepKind::Block) } + / toc:toc(start, offset, &block_metadata) { toc.map(BlockStepKind::Block) } + / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break.map(BlockStepKind::Block) } + / page_break:page_break(start, offset, &block_metadata) { page_break.map(BlockStepKind::Block) } + / ordered_construction(mode) body_offset:position!() kind:committed_list_kind(offset, &block_metadata, true) { Ok(BlockStepKind::List(ListEntry { start, body_offset, metadata: None, kind })) } + / ordered_construction(mode) params:quoted_paragraph_params(start, offset) { Ok(BlockStepKind::Quote(QuoteConstruction { metadata: BlockParsingMetadata::default(), params })) } + / ordered_construction(mode) params:markdown_blockquote_params(start, offset) { Ok(BlockStepKind::Quote(QuoteConstruction { metadata: BlockParsingMetadata::default(), params })) } + / paragraph:paragraph(start, offset, &block_metadata) { paragraph.map(BlockStepKind::Block) } + ) { + block.map(|content| commit_content(state, block_metadata, content)) + } + ) ) { block } @@ -1456,43 +1516,37 @@ peg::parser! { } rule section_content(mode: ConstructionMode, offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result>, Error> - = recursive_section_content(mode) blocks:blocks(offset, parent_section_level, direct_parent_section_kind) { blocks } + = recursive_construction(mode) blocks:blocks(offset, parent_section_level, direct_parent_section_kind) { blocks } / { Ok(vec![]) } - rule recursive_section_content(mode: ConstructionMode) - = {? matches!(mode, ConstructionMode::Recursive).then_some(()).ok_or("section body belongs to the coordinator") } - - rule block_generic(offset: usize, parent_section_level: Option, mode: ConstructionMode) -> Result, Error> + rule block_generic(offset: usize, parent_section_level: Option) -> Result, Error> = start:position!() - block_metadata:(bm:block_metadata(offset, parent_section_level) {? - bm.map_err(|_| { + block_metadata:(metadata:block_metadata(offset, parent_section_level) {? + metadata.map_err(|_| { tracing::error!("error parsing block metadata in block_generic"); "block metadata parse error" }) - }) - block:( - ordered_construction(mode) params:generic_delimited_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Delimited(params))) } - / ordered_construction(mode) params:table_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Table(params))) } - / delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block.map(RecognizedContent::Continue) } - / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim.map(RecognizedContent::Continue) } - / recovered:excessive_list_item(start, offset, &block_metadata) { recovered.map(RecognizedContent::Continue) } - / extension:extension_macro(start, offset, &block_metadata) { extension.map(RecognizedContent::Continue) } - / image:image(start, offset, &block_metadata) { image.map(RecognizedContent::Continue) } - / audio:audio(start, offset, &block_metadata) { audio.map(RecognizedContent::Continue) } - / video:video(start, offset, &block_metadata) { video.map(RecognizedContent::Continue) } - / toc:toc(start, offset, &block_metadata) { toc.map(RecognizedContent::Continue) } - / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break.map(RecognizedContent::Continue) } - / page_break:page_break(start, offset, &block_metadata) { page_break.map(RecognizedContent::Continue) } - / ordered_construction(mode) body_offset:position!() kind:committed_list_kind(offset, &block_metadata, true) { Ok(RecognizedContent::Break(DeferredContent::List { start, body_offset, kind })) } - / list:list(start, offset, &block_metadata) { list.map(RecognizedContent::Continue) } - / ordered_construction(mode) params:quoted_paragraph_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } - / quoted_paragraph:quoted_paragraph(start, offset, &block_metadata) { quoted_paragraph.map(RecognizedContent::Continue) } - / ordered_construction(mode) params:markdown_blockquote_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } - / markdown_blockquote:markdown_blockquote(start, offset, &block_metadata) { markdown_blockquote.map(RecognizedContent::Continue) } - / paragraph:paragraph(start, offset, &block_metadata) { paragraph.map(RecognizedContent::Continue) } - ) { - block.map(|content| commit_content(state, block_metadata, content)) - } + }) + block:( + delimited_block(start, offset, &block_metadata) + / styled_verbatim_paragraph(start, offset, &block_metadata) + / excessive_list_item(start, offset, &block_metadata) + / extension_macro(start, offset, &block_metadata) + / image(start, offset, &block_metadata) + / audio(start, offset, &block_metadata) + / video(start, offset, &block_metadata) + / toc(start, offset, &block_metadata) + / thematic_break(start, offset, &block_metadata) + / page_break(start, offset, &block_metadata) + / list(start, offset, &block_metadata) + / quoted_paragraph(start, offset, &block_metadata) + / markdown_blockquote(start, offset, &block_metadata) + / paragraph(start, offset, &block_metadata) + ) { + let mut block = block?; + assign_block_caption(state, &mut block); + Ok(block) + } // Block parsing for continuation context - lists inside continuations cannot consume // further continuations (those belong to the parent item that started the continuation) @@ -1535,28 +1589,28 @@ peg::parser! { comment:(eol()* comment_start:position!() c:( comment_line_block_keep_eol(offset) / comment_block(comment_start, offset, &block_metadata) - ) { c }) { comment.map(RecognizedContent::Continue) } - / ordered_construction(mode) params:generic_delimited_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Delimited(params))) } - / ordered_construction(mode) params:table_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Table(params))) } - / delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block.map(RecognizedContent::Continue) } - / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim.map(RecognizedContent::Continue) } - / recovered:excessive_list_item(start, offset, &block_metadata) { recovered.map(RecognizedContent::Continue) } - / extension:extension_macro(start, offset, &block_metadata) { extension.map(RecognizedContent::Continue) } - / image:image(start, offset, &block_metadata) { image.map(RecognizedContent::Continue) } - / audio:audio(start, offset, &block_metadata) { audio.map(RecognizedContent::Continue) } - / video:video(start, offset, &block_metadata) { video.map(RecognizedContent::Continue) } - / toc:toc(start, offset, &block_metadata) { toc.map(RecognizedContent::Continue) } - / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break.map(RecognizedContent::Continue) } - / page_break:page_break(start, offset, &block_metadata) { page_break.map(RecognizedContent::Continue) } + ) { c }) { comment.map(BlockStepKind::Block) } + / ordered_construction(mode) params:generic_delimited_params(start, offset) { Ok(BlockStepKind::Delimited(DelimitedConstruction { metadata: BlockParsingMetadata::default(), params })) } + / ordered_construction(mode) params:table_params(start, offset) { Ok(BlockStepKind::Table(TableConstruction { metadata: BlockParsingMetadata::default(), params })) } + / recursive_construction(mode) delimited_block:delimited_block(start, offset, &block_metadata) { delimited_block.map(BlockStepKind::Block) } + / verbatim:styled_verbatim_paragraph(start, offset, &block_metadata) { verbatim.map(BlockStepKind::Block) } + / recovered:excessive_list_item(start, offset, &block_metadata) { recovered.map(BlockStepKind::Block) } + / extension:extension_macro(start, offset, &block_metadata) { extension.map(BlockStepKind::Block) } + / image:image(start, offset, &block_metadata) { image.map(BlockStepKind::Block) } + / audio:audio(start, offset, &block_metadata) { audio.map(BlockStepKind::Block) } + / video:video(start, offset, &block_metadata) { video.map(BlockStepKind::Block) } + / toc:toc(start, offset, &block_metadata) { toc.map(BlockStepKind::Block) } + / thematic_break:thematic_break(start, offset, &block_metadata) { thematic_break.map(BlockStepKind::Block) } + / page_break:page_break(start, offset, &block_metadata) { page_break.map(BlockStepKind::Block) } // Lists in continuation context cannot consume further continuations - / ordered_construction(mode) body_offset:position!() kind:committed_list_kind(offset, &block_metadata, false) { Ok(RecognizedContent::Break(DeferredContent::List { start, body_offset, kind })) } - / list:list_with_continuation(start, offset, &block_metadata, false) { list.map(RecognizedContent::Continue) } - / ordered_construction(mode) params:quoted_paragraph_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } - / quoted_paragraph:quoted_paragraph(start, offset, &block_metadata) { quoted_paragraph.map(RecognizedContent::Continue) } - / ordered_construction(mode) params:markdown_blockquote_params(start, offset) { Ok(RecognizedContent::Break(DeferredContent::Quote(params))) } - / markdown_blockquote:markdown_blockquote(start, offset, &block_metadata) { markdown_blockquote.map(RecognizedContent::Continue) } + / ordered_construction(mode) body_offset:position!() kind:committed_list_kind(offset, &block_metadata, false) { Ok(BlockStepKind::List(ListEntry { start, body_offset, metadata: None, kind })) } + / recursive_construction(mode) list:list_with_continuation(start, offset, &block_metadata, false) { list.map(BlockStepKind::Block) } + / ordered_construction(mode) params:quoted_paragraph_params(start, offset) { Ok(BlockStepKind::Quote(QuoteConstruction { metadata: BlockParsingMetadata::default(), params })) } + / recursive_construction(mode) quoted_paragraph:quoted_paragraph(start, offset, &block_metadata) { quoted_paragraph.map(BlockStepKind::Block) } + / ordered_construction(mode) params:markdown_blockquote_params(start, offset) { Ok(BlockStepKind::Quote(QuoteConstruction { metadata: BlockParsingMetadata::default(), params })) } + / recursive_construction(mode) markdown_blockquote:markdown_blockquote(start, offset, &block_metadata) { markdown_blockquote.map(BlockStepKind::Block) } / !(eol()+ attached_list_marker()) - paragraph:paragraph_with_list_boundary(start, offset, &block_metadata, parent_marker) { paragraph.map(RecognizedContent::Continue) } + paragraph:paragraph_with_list_boundary(start, offset, &block_metadata, parent_marker) { paragraph.map(BlockStepKind::Block) } ) { block.map(|content| commit_content(state, block_metadata, content)) } @@ -2019,15 +2073,15 @@ peg::parser! { rule native_list_entry(offset: usize, entry: &ListEntry<'input>, parent_metadata: &BlockParsingMetadata<'input>) -> Result, Error> = kind:unordered_kind(entry.kind) parent:nested_same(kind) - list:unordered_list_nested(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), parent, kind.parent_other, kind.has_own_metadata) { list } + list:unordered_list_nested(entry.start, offset, entry.metadata.as_deref().unwrap_or(parent_metadata), parent, kind.parent_other, kind.has_own_metadata) { list } / kind:unordered_kind(entry.kind) parent_is_none(kind.parent_same) - list:unordered_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), kind.parent_other, kind.allow_continuation, !kind.has_own_metadata) { list } + list:unordered_list(entry.start, offset, entry.metadata.as_deref().unwrap_or(parent_metadata), kind.parent_other, kind.allow_continuation, !kind.has_own_metadata) { list } / kind:ordered_kind(entry.kind) parent:nested_same(kind) - list:ordered_list_nested(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), parent, kind.parent_other, kind.has_own_metadata) { list } + list:ordered_list_nested(entry.start, offset, entry.metadata.as_deref().unwrap_or(parent_metadata), parent, kind.parent_other, kind.has_own_metadata) { list } / kind:ordered_kind(entry.kind) parent_is_none(kind.parent_same) - list:ordered_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata), kind.parent_other, kind.allow_continuation, !kind.has_own_metadata) { list } - / callout_kind(entry.kind) list:callout_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata)) { list } - / description_kind(entry.kind) list:description_list(entry.start, offset, entry.metadata.as_ref().unwrap_or(parent_metadata)) { list } + list:ordered_list(entry.start, offset, entry.metadata.as_deref().unwrap_or(parent_metadata), kind.parent_other, kind.allow_continuation, !kind.has_own_metadata) { list } + / callout_kind(entry.kind) list:callout_list(entry.start, offset, entry.metadata.as_deref().unwrap_or(parent_metadata)) { list } + / description_kind(entry.kind) list:description_list(entry.start, offset, entry.metadata.as_deref().unwrap_or(parent_metadata)) { list } rule description_list_ahead(offset: usize) = !at_list_item_start() !at_callout_list_item() !at_description_parent_item(offset) @@ -2049,13 +2103,13 @@ peg::parser! { rule unordered_child_entry_with_metadata(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> ListEntry<'input> = start:position!() own:parsed_nested_list_metadata(offset, metadata.parent_section_level) nested_list_metadata_gap()* kind:unordered_child_kind(offset, current_marker, parent_ordered_marker, true) nested_kind_allowed(kind, &own) - { ListEntry { start, body_offset: span_end, metadata: Some(own), kind } } + { ListEntry { start, body_offset: span_end, metadata: Some(Box::new(own)), kind } } rule unordered_child_entry(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_ordered_marker: Option<&'input str>) -> ListEntry<'input> = start:position!() kind:unordered_child_kind(offset, current_marker, parent_ordered_marker, false) content_metadata:( - callout_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } - / description_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } + callout_kind(kind) child:nested_list_content_metadata(metadata) { Some(Box::new(child)) } + / description_kind(kind) child:nested_list_content_metadata(metadata) { Some(Box::new(child)) } / { None } ) { ListEntry { start, body_offset: start, metadata: content_metadata, kind } } @@ -2072,13 +2126,13 @@ peg::parser! { rule ordered_child_entry_with_metadata(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> ListEntry<'input> = start:position!() own:parsed_nested_list_metadata(offset, metadata.parent_section_level) nested_list_metadata_gap()* kind:ordered_child_kind(offset, current_marker, parent_unordered_marker, true) nested_kind_allowed(kind, &own) - { ListEntry { start, body_offset: span_end, metadata: Some(own), kind } } + { ListEntry { start, body_offset: span_end, metadata: Some(Box::new(own)), kind } } rule ordered_child_entry(offset: usize, metadata: &BlockParsingMetadata<'input>, current_marker: &'input str, parent_unordered_marker: Option<&'input str>) -> ListEntry<'input> = start:position!() kind:ordered_child_kind(offset, current_marker, parent_unordered_marker, false) content_metadata:( - callout_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } - / description_kind(kind) child:nested_list_content_metadata(metadata) { Some(child) } + callout_kind(kind) child:nested_list_content_metadata(metadata) { Some(Box::new(child)) } + / description_kind(kind) child:nested_list_content_metadata(metadata) { Some(Box::new(child)) } / { None } ) { ListEntry { start, body_offset: start, metadata: content_metadata, kind } } @@ -2157,7 +2211,7 @@ peg::parser! { kind:unordered_kind(kind) entry:unordered_child_after_principal(base, metadata, marker, kind.parent_other) { entry } / kind:ordered_kind(kind) entry:ordered_child_after_principal(base, metadata, marker, kind.parent_other) { entry } / callout_kind(kind) entry:callout_child_after_principal(base, metadata) { entry } - ) end:position!() { ListStep { kind: ListStepKind::Break(Ok(BlockStepKind::List(entry))), end } } + ) end:position!() { ListStep { kind: ListStepKind::List(entry), end } } / list_phase(phase, ListPhase::Attachments) !at_list_separator() value:( parent:(kind:unordered_kind(kind) { (Some(ListMarker::Unordered(marker)), kind.allow_continuation) } @@ -2166,11 +2220,11 @@ peg::parser! { (list_continuation_immediate_prefix(base) / list_continuation_allowed(parent.1) list_continuation_ancestor_prefix(base)) block:recognized_block_in_continuation(base, metadata.parent_section_level, parent.0, ConstructionMode::Ordered) - end:position!() { ListStep { kind: ListStepKind::Break(block), end } } + end:position!() { ListStep { kind: ListStepKind::block(block), end } } / entry:( kind:unordered_kind(kind) entry:unordered_child_after_attachment(base, metadata, marker, kind.parent_other) { entry } / kind:ordered_kind(kind) entry:ordered_child_after_attachment(base, metadata, marker, kind.parent_other) { entry } - ) end:position!() { ListStep { kind: ListStepKind::Break(Ok(BlockStepKind::List(entry))), end } } + ) end:position!() { ListStep { kind: ListStepKind::List(entry), end } } ) { value } / list_phase(phase, ListPhase::Sibling) head:( kind:unordered_kind(kind) @@ -2979,11 +3033,11 @@ peg::parser! { start:position!() metadata:parsed_nested_list_metadata(offset, block_metadata.parent_section_level) kind:callout_child_kind(offset) body_offset:position!() - { ListEntry { start, body_offset, metadata: Some(metadata), kind } } + { ListEntry { start, body_offset, metadata: Some(Box::new(metadata)), kind } } / eol()* callout_child_marker(offset) start:position!() metadata:nested_list_content_metadata(block_metadata) kind:callout_child_kind(offset) body_offset:position!() - { ListEntry { start, body_offset, metadata: Some(metadata), kind } } + { ListEntry { start, body_offset, metadata: Some(Box::new(metadata)), kind } } ) { child } rule callout_child_kind(offset: usize) -> ListKind<'input> @@ -3279,7 +3333,7 @@ peg::parser! { { ListEntry { start, body_offset, metadata: None, kind } } / !at_callout_parent_item(offset) &at_callout_list_item() start:position!() metadata:nested_list_content_metadata(block_metadata) - { ListEntry { start, body_offset: start, metadata: Some(metadata), kind: ListKind::Callout } } + { ListEntry { start, body_offset: start, metadata: Some(Box::new(metadata)), kind: ListKind::Callout } } rule description_ordinary_child_kind(offset: usize, own: bool) -> ListKind<'input> = scope:ordinary_list_scope(offset) kind:( @@ -3301,7 +3355,7 @@ peg::parser! { &at_callout_list_item() structural_block_boundaries(&metadata) { ListKind::Callout } / kind:description_ordinary_child_kind(offset, true) { kind } ) body_offset:position!() - { ListEntry { start, body_offset, metadata: Some(metadata), kind } } + { ListEntry { start, body_offset, metadata: Some(Box::new(metadata)), kind } } // A blank line before `+` returns from a nested description to its ordinary parent. rule description_continuation_gap(offset: usize) diff --git a/acdc-parser/src/grammar/document/source.rs b/acdc-parser/src/grammar/document/source.rs index 410b1d8b1..09149335d 100644 --- a/acdc-parser/src/grammar/document/source.rs +++ b/acdc-parser/src/grammar/document/source.rs @@ -1,17 +1,20 @@ //! Cooperate with the reader between committed construction steps. -use std::{cell::RefCell, rc::Rc}; +use std::{borrow::Cow, cell::RefCell, rc::Rc}; use crate::{ - AttributeName, Block, Document, DocumentAttributeAssignment, Error, + AttributeName, Block, Document, DocumentAttributeAssignment, DocumentAttributes, Error, document_attribute::{AttributeDeclaration, RawAttributeValue}, - grammar::{ParserState, source::SourceIndex}, + grammar::{ + LineMap, ParserState, + source::{SourceIndex, SourceView}, + }, preprocessor::{PreprocessorResult, SourceReader}, }; use super::{ construction::ConstructionMode, - coordinator::{BlockCursor, Execution}, + coordinator::{BlockCursor, Execution, document_with}, document_parser, input::{BlockInput, ReadRequest}, lists::{ListKind, ListPhase, OrdinaryListKind}, @@ -26,8 +29,8 @@ pub(crate) trait SourceHandler { fn accepted<'a>( &mut self, block: &Block<'a>, - state: &ParserState<'a>, - ) -> Result, Error>; + attributes: &DocumentAttributes<'a>, + ) -> Result, String>; } #[derive(Clone, Copy)] @@ -78,8 +81,9 @@ struct SourceStart<'a> { pub(super) struct SourceInput<'a> { reader: Option>, pub(super) index: Rc>, - pub(super) result: Option>, + pub(super) result: Option>, updates: PendingAssignments, + failed: bool, } impl<'a> SourceInput<'a> { @@ -93,6 +97,7 @@ impl<'a> SourceInput<'a> { index, result: None, updates, + failed: false, } } @@ -103,9 +108,10 @@ impl<'a> SourceInput<'a> { ) -> Result, Error> { loop { if offset < self.index.len() { - let tail = self - .index - .tail(offset) + let tail = state + .source_tail(offset) + .filter(|tail| !tail.is_empty()) + .or_else(|| self.index.tail(offset)) .ok_or_else(|| source_error(state, offset, "missing emitted source line"))?; let end = tail.find('\n').map_or(tail.len(), |end| end + 1); return Ok(tail.get(..end)); @@ -119,7 +125,7 @@ impl<'a> SourceInput<'a> { DocumentAttributeAssignment::Unset => RawAttributeValue::Unset, }; reader - .options + .options_mut() .document_attributes .assign_document_value(name, value, false, false, None)?; } @@ -150,6 +156,15 @@ impl<'a> SourceInput<'a> { fn kind(line: &'a str, state: &mut ParserState<'a>) -> SourceLine<'a> { // Classification is read-only and shares the document grammar's raw // recognizers. Only the accepted construction pass builds inline nodes. + if line == "\n" { + return SourceLine::Blank; + } + // Alphabetic lines can introduce a macro or a description item. All + // other block openers start with punctuation, digits, or whitespace. + // These reject filters avoid starting PEG for ordinary prose lines. + if is_prose_line(line) { + return SourceLine::Text; + } document_parser::source_line(line, state).unwrap_or(SourceLine::Text) } @@ -462,6 +477,9 @@ impl<'a> SourceInput<'a> { while let Some(next) = self.line(offset, state)? { let next_start = offset; offset += next.len(); + if next == "\n" { + break; + } if first && !verbatim && crate::grammar::setext::is_title(line.trim_end_matches('\n')) @@ -481,8 +499,11 @@ impl<'a> SourceInput<'a> { SourceLine::Blank | SourceLine::Continuation )) || (!verbatim - && document_parser::source_paragraph_boundary(next, state, next_start, parent) - .is_ok()) + && (next == "\n" + || document_parser::source_paragraph_boundary( + next, state, next_start, parent, + ) + .is_ok())) { break; } @@ -559,8 +580,25 @@ impl<'a> SourceInput<'a> { } } -impl<'a> BlockInput<'a> for SourceInput<'a> { - fn prepare( +impl<'a> SourceInput<'a> { + #[inline] + fn buffered_prose(&self, cursor: &mut BlockCursor, state: &ParserState<'a>) -> Option<&'a str> { + let start = cursor.base_offset + cursor.offset; + if let Some(origin) = state.input_origin.as_ref().filter(|origin| { + Rc::ptr_eq(&origin.index, &self.index) + && origin.base <= start + && origin.base + state.input.len() <= self.index.len() + }) && let Some(tail) = state.input.get(start - origin.base..) + && complete_prose_prefix(tail) + { + cursor.offset = start - origin.base; + cursor.base_offset = origin.base; + return Some(state.input); + } + None + } + + fn prepare_window( &mut self, cursor: &mut BlockCursor, state: &mut ParserState<'a>, @@ -568,19 +606,20 @@ impl<'a> BlockInput<'a> for SourceInput<'a> { ) -> Result<&'a str, Error> { let start = cursor.base_offset + cursor.offset; let end = self.scan(start, request, state)?; - let active = state.source_view(); - let view = if active.origin.as_ref().is_some_and(|origin| { + if let Some(origin) = state.input_origin.as_ref().filter(|origin| { Rc::ptr_eq(&origin.index, &self.index) && origin.base <= start - && end <= origin.base + active.input.len() - && origin.base + active.input.len() <= self.index.len() + && end <= origin.base + state.input.len() + && origin.base + state.input.len() <= self.index.len() }) { - active - } else { - self.index - .window(start..end, state.arena) - .ok_or_else(|| source_error(state, start, "missing accepted source window"))? - }; + cursor.offset = start - origin.base; + cursor.base_offset = origin.base; + return Ok(state.input); + } + let view = self + .index + .window(start..end, state.arena) + .ok_or_else(|| source_error(state, start, "missing accepted source window"))?; let base = view.origin.as_ref().map_or(0, |origin| origin.base); cursor.offset = start - base; cursor.base_offset = base; @@ -590,6 +629,50 @@ impl<'a> BlockInput<'a> for SourceInput<'a> { } } +impl<'a> BlockInput<'a> for SourceInput<'a> { + #[inline] + fn prepare( + &mut self, + cursor: &mut BlockCursor, + state: &mut ParserState<'a>, + request: ReadRequest<'a>, + ) -> Result<&'a str, Error> { + if matches!(request, ReadRequest::Block) + && let Some(source) = self.buffered_prose(cursor, state) + { + return Ok(source); + } + let result = self.prepare_window(cursor, state, request); + self.failed |= result.is_err(); + result + } + + fn failed(&self) -> bool { + self.failed + } +} + +fn is_prose_line(line: &str) -> bool { + line.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && !line.contains("::") + && !line.contains(";;") +} + +/// A blank after a few ordinary lines proves the first block can commit +/// within the existing buffer. Bound the probe so adjacent headings without +/// blank lines cannot repeatedly scan the remainder of a large source chunk. +fn complete_prose_prefix(source: &str) -> bool { + for line in source.trim_start_matches('\n').lines().take(4) { + if line.is_empty() { + return true; + } + if !is_prose_line(line) { + return false; + } + } + false +} + fn source_error(state: &ParserState<'_>, offset: usize, message: &str) -> Error { Error::Parse( Box::new(state.create_error_source_location(state.create_location(offset, offset))), @@ -608,12 +691,33 @@ fn recognition_error(mut error: super::RecognitionError, state: &ParserState<'_> } pub(crate) fn document_from_source<'a>( - reader: SourceReader<'a>, + mut reader: SourceReader<'a>, state: &mut ParserState<'a>, handler: &mut dyn SourceHandler, - finish_source: impl FnOnce(String) -> &'a str, -) -> Result<(Document<'a>, Vec), Error> { + conditionals: &mut Vec, + finish_source: impl FnOnce(Cow<'a, str>) -> &'a str, +) -> Result, Error> { + if let Some(result) = reader.take_pass_through() { + let source = finish_source(result.text); + if !std::ptr::eq(state.input, source) { + state.set_source_view(SourceView { + input: source, + line_map: Rc::new(LineMap::new(source)), + origin: None, + }); + } + let mut callback = |block: &Block<'a>, state: &mut ParserState<'a>| { + execute_source_handler(handler, block, state, None) + }; + let document = document_with(source, state, ConstructionMode::Ordered, &mut callback) + .map_err(|error| recognition_error(error, state))??; + *conditionals = result.conditionals; + return Ok(document); + } let updates = PendingAssignments::default(); + let mut callback = |block: &Block<'a>, state: &mut ParserState<'a>| { + execute_source_handler(handler, block, state, Some(&updates)) + }; let index = state .input_origin .as_ref() @@ -631,31 +735,6 @@ pub(crate) fn document_from_source<'a>( .map_err(|error| recognition_error(error, state))??; let mut cursor = BlockCursor::new(prefix.body_offset, ConstructionMode::Ordered); let mut blocks = prefix.comments; - let mut callback = |block: &Block<'a>, state: &mut ParserState<'a>| { - for (name, assignment) in handler.accepted(block, state)? { - let name = state.intern_cow(name); - let value = match assignment { - DocumentAttributeAssignment::Set(value) => RawAttributeValue::Resolved(value), - DocumentAttributeAssignment::Unset => RawAttributeValue::Unset, - }; - if let Some(event) = state.apply_document_attribute( - &AttributeDeclaration { - name, - value, - ignored_value: None, - }, - false, - block.location().clone(), - ) && state.nested_parent_attributes.is_none() - { - updates.borrow_mut().push(( - name.to_owned().into(), - event.assignment().clone().into_static(), - )); - } - } - Ok(()) - }; let end = cursor .collect( &mut input, @@ -668,7 +747,7 @@ pub(crate) fn document_from_source<'a>( .result .take() .ok_or_else(|| source_error(state, end, "document ended before source exhaustion"))?; - let source = finish_source(result.text.into_owned()); + let source = finish_source(result.text); state.input = source; state.input_origin = None; state.source_scope_offset = 0; @@ -684,5 +763,58 @@ pub(crate) fn document_from_source<'a>( prefix.attributes, blocks, )?; - Ok((document, result.conditionals)) + *conditionals = result.conditionals; + Ok(document) +} + +#[inline] +fn execute_source_handler<'a>( + handler: &mut dyn SourceHandler, + block: &Block<'a>, + state: &mut ParserState<'a>, + updates: Option<&PendingAssignments>, +) -> Result<(), Error> { + let assignments = handler + .accepted(block, &state.document_attributes) + .map_err(|message| { + Error::Extension( + Box::new(state.create_error_source_location(block.location().clone())), + message, + ) + })?; + if !assignments.is_empty() { + apply_assignments(assignments, block, state, updates); + } + Ok(()) +} + +fn apply_assignments<'a>( + assignments: Assignments<'a>, + block: &Block<'a>, + state: &mut ParserState<'a>, + updates: Option<&PendingAssignments>, +) { + for (name, assignment) in assignments { + let name = state.intern_cow(name); + let value = match assignment { + DocumentAttributeAssignment::Set(value) => RawAttributeValue::Resolved(value), + DocumentAttributeAssignment::Unset => RawAttributeValue::Unset, + }; + if let Some(event) = state.apply_document_attribute( + &AttributeDeclaration { + name, + value, + ignored_value: None, + }, + false, + block.location().clone(), + ) && state.nested_parent_attributes.is_none() + && let Some(updates) = updates + { + updates.borrow_mut().push(( + name.to_owned().into(), + event.assignment().clone().into_static(), + )); + } + } } diff --git a/acdc-parser/src/grammar/source.rs b/acdc-parser/src/grammar/source.rs index 9206b0978..d27640006 100644 --- a/acdc-parser/src/grammar/source.rs +++ b/acdc-parser/src/grammar/source.rs @@ -152,15 +152,17 @@ impl<'a> SourceIndex<'a> { } let start = self.line_start(range.start)?; let mut joined = BumpString::new_in(arena); - for chunk in self.chunks.borrow().iter() { + let chunks = self.chunks.borrow(); + let first = chunks.partition_point(|chunk| chunk.start + chunk.text.len() <= start); + for chunk in chunks.iter().skip(first) { + if chunk.start >= range.end { + break; + } let left = start.max(chunk.start); let right = range.end.min(chunk.start + chunk.text.len()); if left < right { joined.push_str(chunk.text.get(left - chunk.start..right - chunk.start)?); } - if chunk.start >= range.end { - break; - } } if joined.len() != range.end - start { return None; @@ -296,19 +298,24 @@ impl<'a> SourceIndex<'a> { mod tests; impl<'a> SourceView<'a> { + #[inline] pub(super) fn get(&self, range: Range) -> Option<&'a str> { slice(self.input, self.origin.as_deref(), range) } + #[inline] pub(super) fn position(&self, offset: usize) -> Position { position(self.input, &self.line_map, self.origin.as_deref(), offset) } + #[inline] pub(super) fn snap(&self, offset: usize, direction: RoundDirection) -> usize { snap(self.input, self.origin.as_deref(), offset, direction) } + #[inline] pub(super) fn step(&self, offset: usize, direction: RoundDirection) -> usize { step(self.input, self.origin.as_deref(), offset, direction) } + #[inline] pub(super) fn previous_char(&self, offset: usize) -> Option { let end = self.snap(offset, RoundDirection::Backward); let start = self.step(end, RoundDirection::Backward); diff --git a/acdc-parser/src/grammar/source/tests.rs b/acdc-parser/src/grammar/source/tests.rs index a9ca8c1dd..483afb526 100644 --- a/acdc-parser/src/grammar/source/tests.rs +++ b/acdc-parser/src/grammar/source/tests.rs @@ -10,6 +10,40 @@ use super::{RoundDirection, SourceIndex}; type TestResult = Result<(), Box>; +#[test] +fn advancing_windows_retain_linear_source_storage() -> TestResult { + for blocks in [100, 1000] { + let arena = bumpalo::Bump::new(); + let index = Rc::new(SourceIndex::default()); + let mut first = None; + for _ in 0..blocks { + let start = index.append("First line.\n"); + index.append("Second 世界.\n\n"); + let window = index + .window(start..index.len(), &arena) + .ok_or("missing advancing window")?; + assert_eq!(window.input, "First line.\nSecond 世界.\n\n"); + first.get_or_insert(window); + } + assert_eq!( + index + .windows + .borrow() + .iter() + .map(|window| window.text.len()) + .sum::(), + index.len(), + "joined windows must not retain growing document prefixes" + ); + assert!(arena.allocated_bytes() <= 4 * index.len() + 4096); + assert_eq!( + first.ok_or("missing first window")?.input, + "First line.\nSecond 世界.\n\n" + ); + } + Ok(()) +} + #[test] fn windows_match_complete_input_geometry_and_keep_inline_maps_local() -> TestResult { let arena = bumpalo::Bump::new(); diff --git a/acdc-parser/src/grammar/state.rs b/acdc-parser/src/grammar/state.rs index 8d1814095..4e617f16b 100644 --- a/acdc-parser/src/grammar/state.rs +++ b/acdc-parser/src/grammar/state.rs @@ -795,6 +795,7 @@ impl<'a> ParserState<'a> { Self::with_input(input, Rc::new(LineMap::new(input)), None, arena, options) } + #[cfg(test)] pub(super) fn new_with_source( view: SourceView<'a>, arena: &'a Bump, @@ -803,22 +804,6 @@ impl<'a> ParserState<'a> { Self::with_input(view.input, view.line_map, view.origin, arena, options) } - pub(crate) fn new_source(arena: &'a Bump, options: Rc>) -> Self { - Self::new_with_source( - SourceView { - input: "", - line_map: Rc::new(LineMap::new("")), - origin: Some(Rc::new(WindowOrigin { - base: 0, - first_line: 1, - index: Rc::default(), - })), - }, - arena, - options, - ) - } - fn with_input( input: &'a str, line_map: Rc, diff --git a/acdc-parser/src/lib.rs b/acdc-parser/src/lib.rs index 050fb84b9..aa022f1f4 100644 --- a/acdc-parser/src/lib.rs +++ b/acdc-parser/src/lib.rs @@ -438,6 +438,7 @@ fn parse_with_session( parse_with_source_handler(input, options, session, None) } +#[inline] fn parse_with_source_handler( input: &str, options: &Options<'_>, @@ -632,36 +633,47 @@ fn parse_ordered_source( session: Option<&mut extensions::Session>, handler: &mut dyn grammar::SourceHandler, ) -> Result { - let owner = parsed::OwnedInput::new(input.into()); + let owner = + parsed::OwnedInput::new(Preprocessor::normalize(input).into_owned().into_boxed_str()); let warnings_for_state = Rc::clone(&warnings_handle); let options = options.into_static(); - ParseResult::try_new_with_metadata(owner, warnings_handle, move |owner| { - let reader = preprocessor::SourceReader::new( - &owner.source, - file_path.as_deref(), - &options, - Rc::clone(&warnings_for_state), - &owner.arena, - )?; - let mut state = - grammar::ParserState::new_source(&owner.arena, Rc::new(reader.options.clone())); - state.current_file = file_path.clone().map(std::sync::Arc::new); - state.warnings = warnings_for_state; - state.warn_unsupported_compat_mode(None); - if state.document_attributes.contains_key("toc2") { - state.add_warning(Warning::new(WarningKind::DeprecatedToc2Attribute, None)); - } - let result = grammar::document_from_source(reader, &mut state, handler, |source| { - owner.finish_source(source) - }) - .and_then(|(document, conditionals)| { - let source_files = parsed::SourceFiles::new(file_path, &state.source_ranges); - finish_parsed_document(document, &mut state, session, owner.preprocessed_source()) - .map(|document| (document, source_files, conditionals)) - }); - state.emit_warnings(); - result - }) + ParseResult::try_new_with_metadata( + owner, + warnings_handle, + move |owner, source_files, conditionals| { + let reader = preprocessor::SourceReader::from_normalized( + &owner.source, + file_path.as_deref(), + options, + Rc::clone(&warnings_for_state), + &owner.arena, + )?; + let mut state = grammar::ParserState::new( + reader.pass_through_input().unwrap_or(""), + &owner.arena, + Rc::clone(&reader.options), + ); + state.current_file = file_path.clone().map(std::sync::Arc::new); + state.warnings = warnings_for_state; + state.warn_unsupported_compat_mode(None); + if state.document_attributes.contains_key("toc2") { + state.add_warning(Warning::new(WarningKind::DeprecatedToc2Attribute, None)); + } + let result = grammar::document_from_source( + reader, + &mut state, + handler, + conditionals, + |source| owner.finish_source(source), + ) + .and_then(|document| { + *source_files = parsed::SourceFiles::new(file_path, &state.source_ranges); + finish_parsed_document(document, &mut state, session, owner.preprocessed_source()) + }); + state.emit_warnings(); + result + }, + ) } /// Parse inline `AsciiDoc` content from a string. diff --git a/acdc-parser/src/parsed.rs b/acdc-parser/src/parsed.rs index c2a4c79c6..93f57d572 100644 --- a/acdc-parser/src/parsed.rs +++ b/acdc-parser/src/parsed.rs @@ -14,6 +14,7 @@ //! AST) without paying for an empty arena. use std::{ + borrow::Cow, cell::{OnceCell, RefCell}, collections::HashMap, path::{Path, PathBuf}, @@ -88,9 +89,13 @@ impl OwnedInput { } } - pub(crate) fn finish_source(&self, source: String) -> &str { - self.processed_source - .get_or_init(|| source.into_boxed_str()) + pub(crate) fn finish_source<'a>(&'a self, source: Cow<'a, str>) -> &'a str { + match source { + Cow::Borrowed(source) if std::ptr::eq(source, self.source.as_ref()) => &self.source, + source @ (Cow::Borrowed(_) | Cow::Owned(_)) => self + .processed_source + .get_or_init(|| source.into_owned().into_boxed_str()), + } } pub(crate) fn preprocessed_source(&self) -> &str { @@ -100,6 +105,30 @@ impl OwnedInput { } } +#[cfg(test)] +mod source_storage_tests { + #[test] + fn ordered_pass_through_keeps_one_complete_source_buffer() -> Result<(), crate::Error> { + for paragraphs in [100, 1000] { + let input = "A *formatted* paragraph.\n\n".repeat(paragraphs); + let parsed = crate::parse_with_source_handler( + &input, + &crate::Options::default(), + None, + Some(&mut ()), + )?; + let owner = parsed.cell.borrow_owner(); + assert!(owner.processed_source.get().is_none()); + assert!(std::ptr::eq( + parsed.preprocessed_source(), + owner.source.as_ref() + )); + assert!(owner.arena.allocated_bytes() <= 8 * input.len() + 16_384); + } + Ok(()) + } +} + // `self_cell!`'s `dependent:` slot takes a bare identifier and expands it // internally as `$Dependent<'a>`. `Document` already fits, so it goes in // directly. `Vec>` doesn't — hence the `InlineAst` alias. @@ -207,19 +236,15 @@ impl ParseResult { warnings_handle: Rc>, builder: impl for<'a> FnOnce( &'a OwnedInput, - ) -> Result< - (Document<'a>, SourceFiles, Vec), - E, - >, + &mut SourceFiles, + &mut Vec, + ) -> Result, E>, ) -> Result { - let mut metadata = (SourceFiles::default(), Vec::new()); + let mut source_files = SourceFiles::default(); + let mut conditionals = Vec::new(); let cell = ParsedDocumentCell::try_new(owner, |owner| { - builder(owner).map(|(document, source_files, conditionals)| { - metadata = (source_files, conditionals); - document - }) + builder(owner, &mut source_files, &mut conditionals) })?; - let (source_files, conditionals) = metadata; Ok(Self::from_cell( cell, warnings_handle, diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs index c3135f0ee..0ab4b16d7 100644 --- a/acdc-parser/src/preprocessor/cursor.rs +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -7,7 +7,8 @@ use crate::{Error, Options}; use super::{ CommentScanner, ConditionalFrame, DirectiveContext, Preprocessor, PreprocessorResult, PreprocessorState, SkimmedFrontMatter, SourceLineOrigin, SourceOrigin, attribute, - consume_front_matter, has_attribute_continuation, has_include_directive_shape, + consume_front_matter, has_attribute_continuation, has_attribute_driven_styles, + has_include_directive_shape, include::{IncludeResult, IncludeScope}, is_escaped_directive, skim_front_matter, }; @@ -634,6 +635,7 @@ impl<'input> InputCursor<'input> { || self.bulk_consumed || self.line_number != 1 || self.front_matter.is_some() + || include_root && has_attribute_driven_styles(self.out.input) || self .preprocessor .nested_attributes_must_propagate(self.out.input) diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index 184847ad9..58870d8f8 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -219,6 +219,13 @@ fn is_escaped_directive(line: &str) -> bool { }) } +fn has_attribute_driven_styles(text: &str) -> bool { + text.contains('{') + && text + .lines() + .any(|line| line.starts_with('[') && line.contains('{')) +} + /// Caller permissions, include limits, and block state for one parse. #[derive(Debug, Clone)] struct IncludeContext { @@ -806,7 +813,7 @@ impl Preprocessor { /// `Cow::Borrowed` (optionally trimming a single trailing newline to match /// `str::lines`'s drop-trailing-empty behavior). Slow path: rebuild the /// buffer line-by-line as before. - fn normalize(input: &str) -> Cow<'_, str> { + pub(crate) fn normalize(input: &str) -> Cow<'_, str> { // Match the original behavior of `input.lines()`: a single trailing // newline (`\n` or `\r\n`) is dropped. let trimmed = input @@ -865,11 +872,7 @@ impl Preprocessor { self.include_context.block_context.clone(), options.compatibility_mode, ); - let mut style_options = (text.contains('{') - && text - .lines() - .any(|line| line.starts_with('[') && line.contains('{'))) - .then(|| options.clone()); + let mut style_options = has_attribute_driven_styles(text).then(|| options.clone()); for line in text.lines() { if scanner.preserves_comment_line(line) { scanner.record(line, attributes); diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs index 1e1557d16..5b4e45d94 100644 --- a/acdc-parser/src/preprocessor/source.rs +++ b/acdc-parser/src/preprocessor/source.rs @@ -1,6 +1,7 @@ //! Reader facade used by the ordered source-processing driver. use std::{ + borrow::Cow, cell::RefCell, collections::{HashSet, VecDeque}, path::Path, @@ -18,7 +19,7 @@ use crate::{ use super::{ Preprocessor, PreprocessorResult, SourceOrigin, cursor::{Advance, Emission, InputCursor}, - skim_front_matter, + has_attribute_driven_styles, skim_front_matter, }; pub(crate) struct SourceChunk<'a> { @@ -32,12 +33,13 @@ pub(crate) struct SourceChunk<'a> { pub(crate) struct SourceReader<'a> { cursor: Option>, unchanged: Option<&'a str>, - result: Option>, + result: Option>, pending: VecDeque>, - pub(crate) options: Options<'static>, + pub(crate) options: Rc>, } impl<'a> SourceReader<'a> { + #[cfg(test)] pub(crate) fn new( input: &'a str, file: Option<&Path>, @@ -45,23 +47,46 @@ impl<'a> SourceReader<'a> { warnings: Rc>, arena: &'a Bump, ) -> Result { - let origin = match file { - Some(file) => SourceOrigin::entry_file(file, options.base_dir.as_deref())?, - None => SourceOrigin::memory(options.base_dir.as_deref()), - }; - let preprocessor = Preprocessor::new(options, warnings); let normalized = Preprocessor::normalize(input); let normalized = match normalized { std::borrow::Cow::Borrowed(text) => text, std::borrow::Cow::Owned(text) => arena.alloc_str(&text), }; + Self::from_normalized( + normalized, + file, + options.clone().into_static(), + warnings, + arena, + ) + } + + /// The caller owns normalization so its retained source can be borrowed + /// directly. Normalization removes one trailing newline and must run once. + pub(crate) fn from_normalized( + normalized: &'a str, + file: Option<&Path>, + options: Options<'static>, + warnings: Rc>, + arena: &'a Bump, + ) -> Result { + let mut options = Rc::new(options); + let origin = match file { + Some(file) => SourceOrigin::entry_file(file, options.base_dir.as_deref())?, + None => SourceOrigin::memory(options.base_dir.as_deref()), + }; + let preprocessor = Preprocessor::new(&options, warnings); let front_matter = options .document_attributes .contains_key("skip-front-matter") .then(|| skim_front_matter(normalized.lines())) .flatten(); - let mut options = options.clone().into_static(); + // A committed callback can change an attribute used by a later style. + // That can expose directives previously hidden in a comment block, so + // those sources must keep the scanner resumable even if today's values + // would allow the complete input to pass through unchanged. if front_matter.is_none() + && !has_attribute_driven_styles(normalized) && let Some(scanner) = preprocessor.try_pass_through( normalized, crate::grammar::setext::is_enabled(options.compatibility_mode), @@ -72,7 +97,7 @@ impl<'a> SourceReader<'a> { cursor: None, unchanged: Some(normalized), result: Some(PreprocessorResult { - text: std::borrow::Cow::Owned(normalized.to_owned()), + text: Cow::Borrowed(normalized), leveloffset_ranges: Preprocessor::initial_leveloffset_ranges( normalized.len(), &options, @@ -92,7 +117,7 @@ impl<'a> SourceReader<'a> { &preprocessor, normalized, Some(&origin), - &mut options, + Rc::make_mut(&mut options), Vec::new(), front_matter, arena, @@ -106,6 +131,21 @@ impl<'a> SourceReader<'a> { }) } + pub(crate) fn options_mut(&mut self) -> &mut Options<'static> { + Rc::make_mut(&mut self.options) + } + + /// The preprocessor has proved that this complete source needs no edits. + /// No reader advancement is needed while its committed blocks execute. + pub(crate) fn pass_through_input(&self) -> Option<&'a str> { + self.unchanged + } + + pub(crate) fn take_pass_through(&mut self) -> Option> { + self.unchanged.take()?; + self.result.take() + } + pub(crate) fn next(&mut self) -> Result>, Error> { if let Some(text) = self.unchanged.take() { return Ok((!text.is_empty()).then_some(SourceChunk { @@ -129,7 +169,7 @@ impl<'a> SourceReader<'a> { let Some(cursor) = &mut self.cursor else { return Ok(None); }; - match cursor.advance_emitted(&mut self.options)? { + match cursor.advance_emitted(Rc::make_mut(&mut self.options))? { Advance::Progress(emissions) => { self.pending.extend(emissions); self.finish_if_exhausted()?; @@ -151,10 +191,12 @@ impl<'a> SourceReader<'a> { .cursor .take() .ok_or_else(|| std::io::Error::other("missing exhausted source cursor"))?; - while let Advance::Progress(emissions) = cursor.advance_emitted(&mut self.options)? { + while let Advance::Progress(emissions) = + cursor.advance_emitted(Rc::make_mut(&mut self.options))? + { self.pending.extend(emissions); } - let result = cursor.read_all(&mut self.options)?; + let result = cursor.read_all(Rc::make_mut(&mut self.options))?; let end = result.text.len(); for emission in &mut self.pending { emission.text = emission @@ -176,13 +218,13 @@ impl<'a> SourceReader<'a> { Ok(()) } - pub(crate) fn finish(mut self) -> Result, Error> { + pub(crate) fn finish(mut self) -> Result, Error> { if let Some(result) = self.result { return Ok(result); } self.cursor .ok_or_else(|| std::io::Error::other("missing source cursor"))? - .read_all(&mut self.options) + .read_all(Rc::make_mut(&mut self.options)) } } diff --git a/acdc-parser/src/preprocessor/source/tests.rs b/acdc-parser/src/preprocessor/source/tests.rs index a39e3f7da..890496964 100644 --- a/acdc-parser/src/preprocessor/source/tests.rs +++ b/acdc-parser/src/preprocessor/source/tests.rs @@ -104,7 +104,7 @@ fn emitted_nested_include_pauses_before_later_directives() -> TestResult { ["outer.adoc"] ); reader - .options + .options_mut() .document_attributes .set_text("enabled".into(), "".into()); let mut text = format!("{}{}", prefix.text, first.text); diff --git a/acdc-parser/src/source_tests.rs b/acdc-parser/src/source_tests.rs index 751c63d52..38afa3e8e 100644 --- a/acdc-parser/src/source_tests.rs +++ b/acdc-parser/src/source_tests.rs @@ -1,12 +1,98 @@ use crate::{ - AttributeName, Block, CompatibilityMode, DocumentAttributeAssignment, Error, IncludeLoader, - Options, SafeMode, + AttributeName, Block, CompatibilityMode, DocumentAttributeAssignment, DocumentAttributes, + Error, IncludeLoader, Options, SafeMode, extensions::{BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry}, - grammar::{ParserState, SourceHandler}, + grammar::SourceHandler, }; type TestResult = Result<(), Box>; +#[derive(Default)] +struct CountAccepted(usize); + +impl SourceHandler for CountAccepted { + fn accepted<'a>( + &mut self, + _: &Block<'a>, + _: &DocumentAttributes<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, String> { + self.0 += 1; + Ok(Vec::new()) + } +} + +// Keep the A1 seam private while measuring it in optimized builds. Run this +// ignored test alone through nextest with --release and --nocapture. The +// output directory and order can be set for paired, alternating runs. +#[test] +#[ignore = "on-demand Criterion measurement of the private source driver"] +fn benchmark_ordered_source_driver() -> TestResult { + use std::{hint::black_box, time::Duration}; + + use criterion::{BenchmarkId, Criterion}; + + let output = std::env::var_os("ACDC_SOURCE_BENCH_OUTPUT") + .ok_or("set ACDC_SOURCE_BENCH_OUTPUT to the Criterion output directory")?; + let mut criterion = Criterion::default() + .sample_size(30) + .warm_up_time(Duration::from_secs(1)) + .measurement_time(Duration::from_secs(2)) + .nresamples(10_000) + .without_plots() + .output_directory(std::path::Path::new(&output)); + let directory = tempfile::tempdir()?; + std::fs::write( + directory.path().join("part.adoc"), + "Included paragraph.\n\n".repeat(100), + )?; + let options = Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_base_dir(directory.path()) + .build()?; + let nested = "====\n****\n* Parent\n** Child\n****\n====\n\n".repeat(1000); + let includes = "include::part.adoc[]\n\n".repeat(20); + let paragraphs = "A cheap callback follows this paragraph.\n\n".repeat(1000); + let inputs = [ + ("basic", include_str!("../fixtures/tests/basic_header.adoc")), + ("cheap_callbacks_1000", ¶graphs), + ("large_nested", &nested), + ("includes", &includes), + ]; + let ordered_first = std::env::var_os("ACDC_SOURCE_BENCH_ORDERED_FIRST").is_some(); + let order = if ordered_first { + [true, false] + } else { + [false, true] + }; + let mut group = criterion.benchmark_group("source_driver"); + for (name, input) in inputs { + for ordered in order { + let path = if ordered { "ordered" } else { "native" }; + let mut handler = CountAccepted::default(); + let selected = ordered.then_some(&mut handler as &mut dyn SourceHandler); + let _ = crate::parse_with_source_handler(input, &options, None, selected)?; + if ordered && name == "cheap_callbacks_1000" { + assert_eq!(handler.0, 1000); + } + group.bench_with_input(BenchmarkId::new(name, path), &input, |b, input| { + b.iter(|| { + let mut handler = CountAccepted::default(); + let selected = ordered.then_some(&mut handler as &mut dyn SourceHandler); + let parsed = crate::parse_with_source_handler( + black_box(input), + &options, + None, + selected, + ); + black_box((parsed, handler.0)) + }); + }); + } + } + group.finish(); + Ok(()) +} + #[rstest::rstest] #[case::setext("Title\n=====\nAuthor Name\n:thing: Value\n\nBody.")] #[case::comment("////\nIgnored.\n\n:thing: hidden\n////\n= Title\nAuthor Name\n\nBody.")] @@ -15,6 +101,7 @@ type TestResult = Result<(), Box>; #[case::leading_blanks("\n\n= Title\n\nBody.")] #[case::empty("")] #[case::blank("\n\n")] +#[case::normalized("\u{feff}= Title\r\n\r\nBody.\r\n")] fn source_driver_preserves_prefix_forms(#[case] input: &str) -> TestResult { for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { assert_equivalent(input, mode)?; @@ -46,12 +133,63 @@ fn source_driver_keeps_wrapped_attribute_entries_whole(#[case] input: &str) -> T } Ok(()) } + +#[rstest::rstest] +#[case::prose("Ordinary café prose with a https://example.com[link].\n\nAfter.")] +#[case::colon_description("term:: Description.\nother:: Another item.")] +#[case::semicolon_description("term;; Description.\nother;; Another item.")] +#[case::setext("Heading\n-------\n\nBody.")] +#[case::media("image::example.png[]\n\nAfter.")] +#[case::admonition("NOTE: First line.\nSecond line.\n\nAfter.")] +fn source_driver_prose_filters_preserve_native_forms(#[case] input: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + assert_equivalent(input, mode)?; + } + Ok(()) +} + +#[test] +fn source_driver_pass_through_keeps_committed_attribute_timing() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let mut handler = Configure::default(); + let input = "configure::first[]\n\nValue {enabled}."; + let parsed = + crate::parse_with_source_handler(input, &options(mode)?, None, Some(&mut handler))?; + assert_eq!(handler.events, ["first"]); + assert_eq!(parsed.preprocessed_source(), input); + assert!(serde_json::to_string(parsed.document_storage())?.contains("Value yes.")); + } + Ok(()) +} + +#[test] +fn source_driver_resumes_attribute_driven_comment_styles() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write(directory.path().join("part.adoc"), "Exposed include.")?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = options(mode)? + .into_builder() + .with_safe_mode(SafeMode::Safe) + .with_base_dir(directory.path()) + .build()?; + let input = "= Entry\n:enabled: comment\n\nconfigure::first[]\n\n[{enabled}]\n--\ninclude::part.adoc[]\n--"; + let parsed = crate::parse_with_source_handler( + input, + &options, + None, + Some(&mut Configure::default()), + )?; + assert!(parsed.preprocessed_source().contains("Exposed include.")); + } + Ok(()) +} + impl SourceHandler for () { fn accepted<'a>( &mut self, _: &Block<'a>, - _: &ParserState<'a>, - ) -> Result, DocumentAttributeAssignment<'a>)>, Error> { + _: &DocumentAttributes<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, String> { Ok(Vec::new()) } } @@ -326,17 +464,95 @@ fn source_driver_respects_caller_attribute_locks_for_parser_and_reader() -> Test struct Failed; -impl SourceHandler for Failed { +struct FailedProse; + +impl SourceHandler for FailedProse { fn accepted<'a>( &mut self, block: &Block<'a>, - _: &ParserState<'a>, - ) -> Result, DocumentAttributeAssignment<'a>)>, Error> { - if let Block::Extension(extension) = block { - Err(Error::Extension( - Box::new(extension.invocation.location.clone()), - "stop source processing".into(), + _: &DocumentAttributes<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, String> { + if matches!(block, Block::Paragraph(_)) { + return Err("stop after the committed paragraph".into()); + } + Ok(Vec::new()) + } +} + +#[test] +fn source_driver_buffered_prose_commits_before_later_include_reads() -> TestResult { + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let reads = Arc::new(AtomicUsize::default()); + let provider_reads = Arc::clone(&reads); + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Safe) + .with_base_dir("/virtual") + .with_include_loader(IncludeLoader::custom( + move |_: &crate::IncludeSourceTarget| { + provider_reads.fetch_add(1, Ordering::Relaxed); + Ok(crate::IncludeSource::from_bytes( + b"First paragraph.\n\nSecond paragraph.\n\n".to_vec(), + )) + }, )) + .build()?; + let result = crate::parse_with_source_handler( + "include::part.adoc[]\n\ninclude::later.adoc[]", + &options, + None, + Some(&mut FailedProse), + ); + assert!(matches!(result, Err(Error::Extension(..))), "{result:?}"); + assert_eq!(reads.load(Ordering::Relaxed), 1); + } + Ok(()) +} + +#[rstest::rstest] +#[case::unordered("* Parent\n** Child\n+\n")] +#[case::ordered(". Parent\n.. Child\n+\n")] +#[case::description("* Parent\nterm:: Child\n+\n")] +fn source_driver_fatal_reader_error_escapes_nested_recovery(#[case] prefix: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Safe) + .with_base_dir("/virtual") + .with_include_loader(IncludeLoader::custom(|_: &crate::IncludeSourceTarget| { + Err(crate::IncludeSourceError::new( + crate::IncludeSourceErrorKind::Fatal, + "document store is unavailable", + )) + })) + .build()?; + let input = format!("{prefix}include::part.adoc[]"); + for ordered in [false, true] { + let mut handler = (); + let selected = ordered.then_some(&mut handler as &mut dyn SourceHandler); + let result = crate::parse_with_source_handler(&input, &options, None, selected); + assert!( + matches!(&result, Err(Error::IncludeSource(error)) if error.kind() == crate::IncludeSourceErrorKind::Fatal), + "{mode:?}, ordered={ordered}: {result:?}" + ); + } + } + Ok(()) +} + +impl SourceHandler for Failed { + fn accepted<'a>( + &mut self, + block: &Block<'a>, + _: &DocumentAttributes<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, String> { + if matches!(block, Block::Extension(_)) { + Err("stop source processing".into()) } else { Ok(Vec::new()) } @@ -406,8 +622,8 @@ impl SourceHandler for Configure { fn accepted<'a>( &mut self, block: &Block<'a>, - _: &ParserState<'a>, - ) -> Result, DocumentAttributeAssignment<'a>)>, Error> { + _: &DocumentAttributes<'a>, + ) -> Result, DocumentAttributeAssignment<'a>)>, String> { let Block::Extension(extension) = block else { return Ok(Vec::new()); }; From 92b35cdcf3dc4d88d4b1e839ce1a3842471fa62d Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Fri, 13 Nov 2026 10:00:09 +0100 Subject: [PATCH 08/55] perf(parser): move owned include context into cursors --- acdc-parser/CHANGELOG.md | 3 ++ acdc-parser/src/preprocessor/cursor.rs | 25 +++++----- acdc-parser/src/preprocessor/include.rs | 50 +++++++++---------- .../src/preprocessor/include_budget_tests.rs | 12 ++--- acdc-parser/src/preprocessor/mod.rs | 8 +-- acdc-parser/src/preprocessor/source.rs | 4 +- 6 files changed, 53 insertions(+), 49 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 78cbe2fc1..73778734f 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -150,6 +150,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 to 4096 bytes. A bare caller value applies a zero-byte cap; an explicit unset disables the cap. This limit and include `depth=` accept Ruby digit separators, such as `4_096`. +- Documents with AsciiDoc includes use fewer allocations while preserving source + locations and include policies. + - Nested list IDs specified with `[id=...]` now retain their correct source locations inside compound blocks. diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs index 0ab4b16d7..7df963b2b 100644 --- a/acdc-parser/src/preprocessor/cursor.rs +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -364,9 +364,9 @@ impl<'input> InputCursor<'input> { } pub(super) fn new( - preprocessor: &Preprocessor, + preprocessor: Preprocessor, input: &'input str, - source_origin: Option<&SourceOrigin>, + source_origin: Option, options: &mut Options<'_>, line_origins: Vec, front_matter: Option, @@ -385,20 +385,21 @@ impl<'input> InputCursor<'input> { .document_attributes .set_text("front-matter".into(), value.clone().into()); } - let mut out = PreprocessorState::new(input, source_origin, line_origins); + let mut out = PreprocessorState::new(input, source_origin.as_ref(), line_origins); out.record_leveloffset(options); + let scanner = CommentScanner::new( + crate::grammar::setext::is_enabled(options.compatibility_mode), + preprocessor.include_context.block_context.clone(), + options.compatibility_mode, + ); Self { - preprocessor: preprocessor.clone(), - source_origin: source_origin.cloned(), + preprocessor, + source_origin, arena, lines, line_number, out, - scanner: CommentScanner::new( - crate::grammar::setext::is_enabled(options.compatibility_mode), - preprocessor.include_context.block_context.clone(), - options.compatibility_mode, - ), + scanner, conditionals: Vec::new(), front_matter, include: None, @@ -575,9 +576,9 @@ impl<'input> InputCursor<'input> { .flatten(); let preprocessor = Preprocessor::nested(&self.preprocessor.warnings, input.context); let cursor = Self::new( - &preprocessor, + preprocessor, text, - Some(&input.source_origin), + Some(input.source_origin), options, input.line_origins, front_matter, diff --git a/acdc-parser/src/preprocessor/include.rs b/acdc-parser/src/preprocessor/include.rs index 736c34ace..9a75d53a3 100644 --- a/acdc-parser/src/preprocessor/include.rs +++ b/acdc-parser/src/preprocessor/include.rs @@ -842,9 +842,9 @@ impl<'a> Include<'a> { /// Apply `indent` and check the shared budget before processing nested directives. fn process_selected_content( - &self, + self, selected: reader::Selected, - source_origin: &SourceOrigin, + source_origin: SourceOrigin, resolved_source: &Path, is_asciidoc: bool, ) -> Result { @@ -912,7 +912,6 @@ impl<'a> Include<'a> { input: None, }; if is_asciidoc { - included.input = Some(self.prepare_input(source_origin, line_origins, scoped_options)); let full = match &self.selection { ContentSelection::All => true, ContentSelection::Lines(_) => false, @@ -924,9 +923,10 @@ impl<'a> Include<'a> { { included.included_files.insert(name); } + included.input = Some(self.prepare_input(source_origin, line_origins, scoped_options)); } else { included.source_ranges = - Self::source_ranges_for_lines(&included.content, &line_origins, source_origin); + Self::source_ranges_for_lines(&included.content, &line_origins, &source_origin); } Ok(included) } @@ -955,32 +955,31 @@ impl<'a> Include<'a> { } fn prepare_input( - &self, - source_origin: &SourceOrigin, + self, + source_origin: SourceOrigin, line_origins: Vec, scoped_options: Option>>, ) -> IncludeInput { - let mut context = self.context.clone(); - let scope = scoped_options.as_ref().map(|options| { - let prefix = self.leveloffset_prefix(); + let scope = scoped_options.as_ref().map(|options| IncludeScope { + current: Self::leveloffset_assignment(&options.document_attributes), + previous: Self::leveloffset_assignment(&self.options.document_attributes), + mode: self.options.compatibility_mode, + prefix: self.leveloffset_prefix(), + suffix: format!( + "\n\n{}", + Self::leveloffset_control(&self.options.document_attributes) + ), + }); + let mut context = self.context; + if let (Some(scope), Some(options)) = (&scope, &scoped_options) { let mut scanner = CommentScanner::new( crate::grammar::setext::is_enabled(self.options.compatibility_mode), std::mem::take(&mut context.block_context), self.options.compatibility_mode, ); - scanner.record_expansion(&prefix, &options.document_attributes); + scanner.record_expansion(&scope.prefix, &options.document_attributes); context.block_context = scanner.block_context(); - IncludeScope { - current: Self::leveloffset_assignment(&options.document_attributes), - previous: Self::leveloffset_assignment(&self.options.document_attributes), - mode: self.options.compatibility_mode, - prefix, - suffix: format!( - "\n\n{}", - Self::leveloffset_control(&self.options.document_attributes) - ), - } - }); + } if let Some(depth) = self.depth { let limit = context.depth.saturating_add(1).saturating_add(depth); if limit < context.max_depth { @@ -989,7 +988,7 @@ impl<'a> Include<'a> { } } IncludeInput { - source_origin: source_origin.clone(), + source_origin, line_origins, context, attributes: scoped_options.map(|options| options.document_attributes.into_static()), @@ -1305,7 +1304,7 @@ impl<'a> Include<'a> { } pub(crate) fn process( - &self, + self, attribute_list_as_written: &str, source_provider: &dyn IncludeSourceProvider, ) -> Result { @@ -1314,7 +1313,7 @@ impl<'a> Include<'a> { TargetContentOutcome::Content(content) => content, TargetContentOutcome::Fallback(result) => return Ok(*result), }; - self.process_selected_content(content, &source_origin, &resolved_source, is_asciidoc) + self.process_selected_content(content, source_origin, &resolved_source, is_asciidoc) } fn read_file_target( @@ -1833,10 +1832,11 @@ mod tests { .provider() .ok_or("system include loader must provide a source provider")?; + let warnings = Rc::clone(&include.warnings); let result = include.process("opts=optional", source_provider)?; assert_eq!(result.content, ""); - assert!(include.warnings.borrow().is_empty()); + assert!(warnings.borrow().is_empty()); assert!(logs_contain( "optional include dropped because include file not found" )); diff --git a/acdc-parser/src/preprocessor/include_budget_tests.rs b/acdc-parser/src/preprocessor/include_budget_tests.rs index 0cec7c6a7..7fdfde91a 100644 --- a/acdc-parser/src/preprocessor/include_budget_tests.rs +++ b/acdc-parser/src/preprocessor/include_budget_tests.rs @@ -117,9 +117,9 @@ fn resumable_input_applies_changes_before_later_conditionals_and_includes() -> T )?; let input = "configure::[]\n\nifdef::enabled[]\ninclude::body.adoc[]\nendif::[]"; let mut cursor = cursor::InputCursor::new( - &preprocessor, + preprocessor, input, - Some(&source), + Some(source), &mut options, Vec::new(), None, @@ -162,9 +162,9 @@ fn resumable_input_does_not_open_a_later_include_before_advancing() -> TestResul options.base_dir.as_deref(), )?; let mut cursor = cursor::InputCursor::new( - &preprocessor, + preprocessor, "include::first.adoc[]\ninclude::next.adoc[]", - Some(&source), + Some(source), &mut options, Vec::new(), None, @@ -205,9 +205,9 @@ fn resumable_input_pauses_inside_an_include_and_preserves_nested_source_chains() options.base_dir.as_deref(), )?; let mut cursor = cursor::InputCursor::new( - &preprocessor, + preprocessor, "include::outer.adoc[]\ninclude::after.adoc[]", - Some(&source), + Some(source), &mut options, Vec::new(), None, diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index 58870d8f8..b3fa9372e 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -1423,9 +1423,9 @@ impl Preprocessor { ) -> Result, Error> { let arena = bumpalo::Bump::new(); cursor::InputCursor::new( - self, + self.clone(), normalized.as_ref(), - source_origin, + source_origin.cloned(), options, line_origins, front_matter, @@ -1605,9 +1605,9 @@ mod tests { let arena = bumpalo::Bump::new(); let normalized = Preprocessor::normalize(input); let result = cursor::InputCursor::new( - &preprocessor, + preprocessor.clone(), &normalized, - Some(&origin), + Some(origin.clone()), &mut options, Vec::new(), None, diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs index 5b4e45d94..901cede1b 100644 --- a/acdc-parser/src/preprocessor/source.rs +++ b/acdc-parser/src/preprocessor/source.rs @@ -114,9 +114,9 @@ impl<'a> SourceReader<'a> { }); } let cursor = InputCursor::new( - &preprocessor, + preprocessor, normalized, - Some(&origin), + Some(origin), Rc::make_mut(&mut options), Vec::new(), front_matter, From 0362bcc37772081905ded4f2b6e395fc55887e55 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Fri, 13 Nov 2026 10:01:12 +0100 Subject: [PATCH 09/55] perf(parser): reuse unchanged selected include buffers --- acdc-parser/CHANGELOG.md | 3 +- acdc-parser/src/preprocessor/cursor.rs | 129 ++++++++++++++----- acdc-parser/src/preprocessor/source/tests.rs | 47 +++++++ acdc-parser/tests/include_allocations.rs | 60 +++++++++ 4 files changed, 203 insertions(+), 36 deletions(-) create mode 100644 acdc-parser/tests/include_allocations.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 73778734f..28b3026ac 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -151,7 +151,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 disables the cap. This limit and include `depth=` accept Ruby digit separators, such as `4_096`. - Documents with AsciiDoc includes use fewer allocations while preserving source - locations and include policies. + locations and include policies. Short `lines=` and `tag=` selections also use + less memory during ordinary parsing. - Nested list IDs specified with `[id=...]` now retain their correct source locations inside compound blocks. diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs index 7df963b2b..b281c1dcb 100644 --- a/acdc-parser/src/preprocessor/cursor.rs +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -9,7 +9,7 @@ use super::{ PreprocessorState, SkimmedFrontMatter, SourceLineOrigin, SourceOrigin, attribute, consume_front_matter, has_attribute_continuation, has_attribute_driven_styles, has_include_directive_shape, - include::{IncludeResult, IncludeScope}, + include::{IncludeInput, IncludeResult, IncludeScope}, is_escaped_directive, skim_front_matter, }; @@ -29,6 +29,12 @@ pub(super) struct InputCursor<'input> { bulk_consumed: bool, } +#[derive(Clone, Copy)] +enum ReadMode { + Complete, + Resumable, +} + struct IncludeFrame<'input> { result: IncludeResult, cursor: Box>, @@ -175,7 +181,7 @@ impl<'input> InputCursor<'input> { let Some(line) = self.lines.next() else { return Ok(Advance::End); }; - self.process_line(line, options)?; + self.process_line(line, options, ReadMode::Resumable)?; self.line_number += 1; } let Some(text) = self.emitted_text(start) else { @@ -426,12 +432,17 @@ impl<'input> InputCursor<'input> { let Some(line) = self.lines.next() else { return Ok(false); }; - self.process_line(line, options)?; + self.process_line(line, options, ReadMode::Complete)?; self.line_number += 1; Ok(true) } - fn process_line(&mut self, line: &'input str, options: &mut Options<'_>) -> Result<(), Error> { + fn process_line( + &mut self, + line: &'input str, + options: &mut Options<'_>, + mode: ReadMode, + ) -> Result<(), Error> { if self.conditionals.last().is_none_or(|frame| frame.active) && self.scanner.preserves_comment_line(line) { @@ -482,7 +493,7 @@ impl<'input> InputCursor<'input> { } self.out.push_source_line(line, self.line_number); } else if line.ends_with(']') && !line.starts_with('[') && line.contains("::") { - return self.process_directive_line(line, options); + return self.process_directive_line(line, options, mode); } else { self.out.push_source_line(line, self.line_number); } @@ -494,6 +505,7 @@ impl<'input> InputCursor<'input> { &mut self, line: &'input str, options: &mut Options<'_>, + mode: ReadMode, ) -> Result<(), Error> { if is_escaped_directive(line) { self.out.note_source_line(self.line_number); @@ -501,7 +513,7 @@ impl<'input> InputCursor<'input> { self.scanner .record(&line[1..], &options.document_attributes); } else if has_include_directive_shape(line) { - self.process_include_line(line, options)?; + self.process_include_line(line, options, mode)?; } else { self.out.push_source_line(line, self.line_number); self.scanner.record(line, &options.document_attributes); @@ -513,6 +525,7 @@ impl<'input> InputCursor<'input> { &mut self, line: &'input str, options: &mut Options<'_>, + mode: ReadMode, ) -> Result<(), Error> { let origin = self.out.origin_of_line(self.line_number); let ctx = DirectiveContext { @@ -564,41 +577,87 @@ impl<'input> InputCursor<'input> { return Ok(()); }; if let Some(input) = included.input.take() { - if let Some(attributes) = input.attributes { - options.document_attributes = attributes; - } - let normalized = Preprocessor::normalize(&included.content); - let text = self.arena.alloc_str(&normalized); - let front_matter = options - .document_attributes - .contains_key("skip-front-matter") - .then(|| skim_front_matter(text.lines())) - .flatten(); - let preprocessor = Preprocessor::nested(&self.preprocessor.warnings, input.context); - let cursor = Self::new( - preprocessor, - text, - Some(input.source_origin), - options, - input.line_origins, - front_matter, - self.arena, - ); - self.include = Some(IncludeFrame { - result: included, - cursor: Box::new(cursor), - input_line: self.line_number, - scope: input.scope, - pending_blank: None, - prefix_emitted: false, - emitted_end: self.out.byte_offset, - }); + self.start_include(included, input, options, mode); } else { self.accept_include(included, self.line_number, options); } Ok(()) } + fn start_include( + &mut self, + mut included: IncludeResult, + input: IncludeInput, + options: &mut Options<'_>, + mode: ReadMode, + ) { + if let Some(attributes) = input.attributes { + options.document_attributes = attributes; + } + let normalized = Preprocessor::normalize(&included.content); + let front_matter = options + .document_attributes + .contains_key("skip-front-matter") + .then(|| skim_front_matter(normalized.lines())) + .flatten(); + let preprocessor = Preprocessor::nested(&self.preprocessor.warnings, input.context); + // Complete-input preprocessing can retain the owned selected text when + // the shared scanner proves it unchanged. Ordered readers must keep + // stable cursor storage until the included blocks have committed. + if matches!(mode, ReadMode::Complete) + && input.scope.is_none() + && front_matter.is_none() + && !preprocessor.nested_attributes_must_propagate(&normalized) + && let Some(scanner) = preprocessor.try_pass_through( + &normalized, + crate::grammar::setext::is_enabled(options.compatibility_mode), + options, + ) + { + included.source_ranges = { + let mut out = PreprocessorState::new( + &normalized, + Some(&input.source_origin), + input.line_origins, + ); + for (idx, line) in normalized.lines().enumerate() { + out.note_source_line(idx + 1); + out.byte_offset += line.len() + 1; + } + out.flush_run(); + out.source_ranges + }; + let length = normalized.len(); + if let Cow::Owned(text) = normalized { + included.content = text; + } else { + included.content.truncate(length); + } + included.comment_context = Some(scanner.block_context()); + self.accept_include(included, self.line_number, options); + return; + } + let text = self.arena.alloc_str(&normalized); + let cursor = Self::new( + preprocessor, + text, + Some(input.source_origin), + options, + input.line_origins, + front_matter, + self.arena, + ); + self.include = Some(IncludeFrame { + result: included, + cursor: Box::new(cursor), + input_line: self.line_number, + pending_blank: None, + scope: input.scope, + prefix_emitted: false, + emitted_end: self.out.byte_offset, + }); + } + fn accept_include(&mut self, mut included: IncludeResult, line: usize, options: &Options<'_>) { if let Some(context) = included.comment_context.take() { self.scanner.record_preprocessed(&included.content, context); diff --git a/acdc-parser/src/preprocessor/source/tests.rs b/acdc-parser/src/preprocessor/source/tests.rs index 890496964..c300b605a 100644 --- a/acdc-parser/src/preprocessor/source/tests.rs +++ b/acdc-parser/src/preprocessor/source/tests.rs @@ -139,3 +139,50 @@ fn emitted_nested_include_pauses_before_later_directives() -> TestResult { assert!(text.contains("== Inner")); Ok(()) } + +#[test] +fn selected_include_pass_through_matches_resumable_source_maps() -> TestResult { + let directory = tempfile::tempdir()?; + let file = directory.path().join("part.adoc"); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::System) + .with_base_dir(directory.path()) + .with_attribute("skip-front-matter", true) + .build()?; + for included in [ + "\u{feff}// tag::keep[]\r\n é\t\r\n\r\n 世界\r\n// end::keep[]\r\n", + "first\n\nthird\n\nfifth\n\n", + "---\ntitle: Front matter\n---\n\nBody.\n", + ":kind: comment\n[{kind}]\n--\ninclude::missing.adoc[]\n--\n", + ] { + std::fs::write(&file, included)?; + for directive in [ + "include::part.adoc[]", + "include::part.adoc[lines=1;3;5,indent=2]", + "include::part.adoc[tag=keep,indent=0]", + ] { + let source = format!("before\n\n{directive}\n\nafter"); + let expected = Preprocessor::process(&source, &options, Rc::default())?; + let arena = bumpalo::Bump::new(); + let mut reader = SourceReader::new(&source, None, &options, Rc::default(), &arena)?; + let mut text = String::new(); + while let Some(chunk) = reader.next()? { + assert_eq!(chunk.start, text.len()); + text.push_str(chunk.text); + } + let actual = reader.finish()?; + text.truncate(actual.text.len()); + assert_eq!(text, expected.text, "{included:?} in {source:?}"); + assert_eq!(actual.text, expected.text); + assert_eq!( + actual.source_ranges, expected.source_ranges, + "{included:?} in {source:?}" + ); + } + } + } + Ok(()) +} diff --git a/acdc-parser/tests/include_allocations.rs b/acdc-parser/tests/include_allocations.rs new file mode 100644 index 000000000..2aca8e23c --- /dev/null +++ b/acdc-parser/tests/include_allocations.rs @@ -0,0 +1,60 @@ +//! Allocation budgets for ordinary parsing of unchanged selected includes. +//! Keep one test: the allocator region measures the entire process. + +use std::{alloc::System, fmt::Write as _, hint::black_box, process::Command}; + +use acdc_parser::{CompatibilityMode, IncludeLoader, Options, SafeMode, parse_file}; +use stats_alloc::{INSTRUMENTED_SYSTEM, Region, StatsAlloc}; + +#[global_allocator] +static GLOBAL: &StatsAlloc = &INSTRUMENTED_SYSTEM; + +#[test] +fn unchanged_selected_include_allocation_budgets() -> Result<(), Box> { + if std::env::var("SOURCE_DATE_EPOCH").as_deref() != Ok("0") { + let status = Command::new(std::env::current_exe()?) + .arg("--exact") + .arg("unchanged_selected_include_allocation_budgets") + .arg("--nocapture") + .env("SOURCE_DATE_EPOCH", "0") + .status()?; + assert!(status.success()); + return Ok(()); + } + + let directory = tempfile::tempdir()?; + let path = directory.path().join("main.adoc"); + std::fs::write( + directory.path().join("part.adoc"), + "ignored\n// tag::body[]\nFirst selected line.\nSecond selected line.\n// end::body[]\nignored\n", + )?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::System) + .build()?; + for selection in ["tag=body", "lines=3..4"] { + // Main's include-attribute decoding adds two allocations per include. + // These bounds retain the fixed overhead and match the updated baseline. + for (includes, budget) in [(1, 132), (10, 627), (50, 2_827), (200, 11_077)] { + let mut source = String::from("= Includes\n\n"); + for _ in 0..includes { + writeln!(source, "include::part.adoc[{selection}]\n")?; + } + std::fs::write(&path, source)?; + let _ = black_box(parse_file(&path, &options)?); + let region = Region::new(GLOBAL); + let parsed = parse_file(&path, &options)?; + let stats = region.change(); + assert!( + stats.allocations <= budget, + "{mode:?}, {selection}, {includes} includes: {stats:?}" + ); + assert_eq!(parsed.document().blocks().count(), includes); + let _ = black_box(parsed); + } + } + } + Ok(()) +} From 86596f748c3c82c8723cc22c859be6d43f9a7c31 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Fri, 13 Nov 2026 10:08:32 +0100 Subject: [PATCH 10/55] perf(parser): write accepted block results into coordinator storage --- .../src/grammar/document/coordinator.rs | 28 +++++++++++++------ acdc-parser/src/grammar/document/peg.rs | 15 ++++++---- acdc-parser/src/source_tests.rs | 16 +++++++++++ 3 files changed, 45 insertions(+), 14 deletions(-) diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index 34fa71961..c0c0bfe47 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -126,24 +126,36 @@ impl BlockCursor { } } - #[inline] + #[cfg(test)] pub(super) fn advance<'a>( &mut self, input: &'a str, state: &mut ParserState<'a>, ) -> Result, Error>, RecognitionError> { - let step = document_parser::next_block( + let mut step = BlockStep::end(Vec::new(), self.offset); + Ok(self.advance_into(input, state, &mut step)?.map(|()| step)) + } + + #[inline] + fn advance_into<'a>( + &mut self, + input: &'a str, + state: &mut ParserState<'a>, + step: &mut BlockStep<'a>, + ) -> Result, RecognitionError> { + let result = document_parser::next_block( input, state, self.offset, self.base_offset, self.parent, self.mode, + step, )?; - if let Ok(step) = &step { + if result.is_ok() { self.offset = step.end; } - Ok(step) + Ok(result) } pub(super) fn section(&self, section: &crate::Section<'_>, state: &ParserState<'_>) -> Self { @@ -179,10 +191,10 @@ impl BlockCursor { Ok(source) => source, Err(error) => return Ok(Err(error)), }; - let step = match self.advance(source, state)? { - Ok(step) => step, - Err(error) => return Ok(Err(error)), - }; + let mut step = BlockStep::end(Vec::new(), self.offset); + if let Err(error) = self.advance_into(source, state, &mut step)? { + return Ok(Err(error)); + } let kind = match step.kind { BlockStepKind::End(trailing) => { blocks.extend(trailing); diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 7a85512d3..852d8adab 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -114,21 +114,24 @@ peg::parser! { = resume_at(offset) blocks:blocks(0, None, None) end:position!() eol()* { blocks.map(|blocks| (blocks, end)) } + // Write the result only in the terminal action of an accepted branch. + // This public no_eof rule has no later match that can fail. Handlers run + // in the coordinator after success, outside all PEG actions. #[no_eof] - pub(in crate::grammar::document) rule next_block(offset: usize, base_offset: usize, parent: BlockParent, mode: ConstructionMode) -> Result, Error> - = resume_at(offset) step:( + pub(in crate::grammar::document) rule next_block(offset: usize, base_offset: usize, parent: BlockParent, mode: ConstructionMode, output: &mut BlockStep<'input>) -> Result<(), Error> + = resume_at(offset) result:( !trailing_block_metadata_match() block:( ordered_construction(mode) block:recognized_block(base_offset, parent.level, parent.kind, mode) { block } / recursive_construction(mode) block:block(base_offset, parent.level, parent.kind) { block.map(BlockStepKind::Block) } ) end:position!() - { block.map(|kind| BlockStep { kind, end }) } + { block.map(|kind| { *output = BlockStep { kind, end }; }) } / eol()* &same_or_higher_level_section(base_offset, parent.level) - { Ok(BlockStep::end(Vec::new(), offset)) } + { *output = BlockStep::end(Vec::new(), offset); Ok(()) } / trailing:trailing_block_metadata(base_offset)? end:position!() eol()* ![_] - { trailing.transpose().map(|blocks| BlockStep::end(blocks.unwrap_or_default(), end)) } - ) { step } + { trailing.transpose().map(|blocks| { *output = BlockStep::end(blocks.unwrap_or_default(), end); }) } + ) { result } // Read-only line probes share the actual block recognizers. The source // driver uses them to collect one unit, then constructs that unit once. diff --git a/acdc-parser/src/source_tests.rs b/acdc-parser/src/source_tests.rs index 38afa3e8e..5d353f8cf 100644 --- a/acdc-parser/src/source_tests.rs +++ b/acdc-parser/src/source_tests.rs @@ -21,6 +21,22 @@ impl SourceHandler for CountAccepted { } } +#[rstest::rstest] +#[case::paragraph("[role=note]\nA paragraph.")] +#[case::anchor("[[anchor]]\n.Title\nA paragraph.")] +#[case::listing("[source,rust]\n----\nlet answer = 42;\n----")] +#[case::image(".Caption\n[role=note]\nimage::target.png[]")] +fn source_driver_calls_handler_once_after_block_disambiguation(#[case] input: &str) -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut handler = CountAccepted::default(); + let parsed = crate::parse_with_source_handler(input, &options, None, Some(&mut handler))?; + assert_eq!(parsed.document().blocks().count(), 1); + assert_eq!(handler.0, 1); + } + Ok(()) +} + // Keep the A1 seam private while measuring it in optimized builds. Run this // ignored test alone through nextest with --release and --nocapture. The // output directory and order can be set for paired, alternating runs. From 80a28e0392ae2b898278aaf042aad1e197eb3828 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 14 Nov 2026 08:09:12 +0100 Subject: [PATCH 11/55] refactor(parser): stream committed compound and table content Let the private source coordinator advance through compound bodies and pipe/exclamation AsciiDoc cells at committed block boundaries. Reuse the existing delimiters, table placement, attribute policy, and diagnostics. Retain buffered handling for other table formats. --- acdc-parser/src/blocks/table.rs | 240 ++++++---- acdc-parser/src/extensions/recognition.rs | 7 + acdc-parser/src/grammar/document.rs | 1 + acdc-parser/src/grammar/document/compound.rs | 133 ++++++ .../src/grammar/document/coordinator.rs | 233 ++++++--- acdc-parser/src/grammar/document/delimited.rs | 14 +- acdc-parser/src/grammar/document/input.rs | 24 + .../src/grammar/document/lists/callout.rs | 8 +- .../grammar/document/lists/construction.rs | 11 +- .../src/grammar/document/lists/description.rs | 10 +- acdc-parser/src/grammar/document/peg.rs | 14 +- acdc-parser/src/grammar/document/source.rs | 330 +++++++++++-- acdc-parser/src/grammar/document/table.rs | 206 ++++---- .../src/grammar/document/table/streaming.rs | 444 ++++++++++++++++++ acdc-parser/src/grammar/source.rs | 9 +- acdc-parser/src/grammar/state.rs | 24 + acdc-parser/src/preprocessor/cursor.rs | 18 + acdc-parser/src/preprocessor/source.rs | 6 + acdc-parser/src/source_tests.rs | 4 +- 19 files changed, 1428 insertions(+), 308 deletions(-) create mode 100644 acdc-parser/src/grammar/document/compound.rs create mode 100644 acdc-parser/src/grammar/document/table/streaming.rs diff --git a/acdc-parser/src/blocks/table.rs b/acdc-parser/src/blocks/table.rs index dc229bd8a..64b4cb6d0 100644 --- a/acdc-parser/src/blocks/table.rs +++ b/acdc-parser/src/blocks/table.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use crate::{ColumnStyle, HorizontalAlignment, Table, VerticalAlignment}; pub(crate) const MAX_TABLE_COLUMNS: usize = 100; @@ -54,6 +56,25 @@ fn split_escaped(line: &str, separator: char) -> Vec { parts } +/// Decode escapes through the table lexer before interpreting raw cell syntax. +pub(crate) fn decode_cell_escapes(source: &str, separator: char) -> Cow<'_, str> { + if !source.match_indices('\\').any(|(index, _)| { + source + .get(index + 1..) + .is_some_and(|tail| tail.starts_with(separator)) + }) { + return Cow::Borrowed(source); + } + let mut decoded = String::with_capacity(source.len()); + for (index, part) in split_escaped(source, separator).into_iter().enumerate() { + if index > 0 { + decoded.push(separator); + } + decoded.push_str(&part.content); + } + Cow::Owned(decoded) +} + /// Split a single line into cell parts for line-per-row formats (DSV, TSV, or a /// custom multi-character separator). Single-character separators honor `\` /// escapes; multi-character separators are matched literally. @@ -627,6 +648,32 @@ fn extract_trailing_spec(content: &str, allow_at_start: bool) -> (&str, Option Option<(usize, usize, CellSpecifier)> { + let parts = split_escaped(text, separator); + let first = parts.first()?; + let next = parts.get(1)?; + let (kept, spec) = extract_trailing_spec(&first.content, allow_at_start); + let marker = next.start.checked_sub(separator.len_utf8())?; + let end = marker.checked_sub(first.content.len() - kept.len())?; + Some((end, next.start, spec.unwrap_or_default())) +} + +pub(crate) fn inferred_columns(source: &str, separator: &str) -> usize { + first_line_column_count(source, separator) +} + +pub(crate) fn implicit_header(lines: &[&str], separator: &str) -> bool { + lines.first().is_some_and(|line| !line.trim().is_empty()) + && lines.get(1).is_some_and(|line| line.trim().is_empty()) + && detect_header_after_first_row(lines, 1, separator) +} + /// Scan the table body into a flat stream of cells. /// /// The whole body is split on the separator (respecting `\|` escapes), so @@ -705,35 +752,30 @@ fn first_line_column_count(text: &str, separator: &str) -> usize { } } -fn validate_cell_specifiers(cells: &[ParsedCell]) -> Result<(), TableLimitViolation> { - for cell in cells { - if cell.spec.colspan > MAX_TABLE_COLUMNS { - return Err(TableLimitViolation::new( - "column span", - cell.spec.colspan, - MAX_TABLE_COLUMNS, - cell.start, - cell.end, - )); - } - if cell.spec.rowspan > MAX_TABLE_ROWS { - return Err(TableLimitViolation::new( - "row span", - cell.spec.rowspan, - MAX_TABLE_ROWS, - cell.start, - cell.end, - )); - } - if cell.spec.duplication_count > MAX_TABLE_COLUMNS { - return Err(TableLimitViolation::new( +impl CellSpecifier { + pub(crate) fn validate(self, start: usize, end: usize) -> Result<(), TableLimitViolation> { + for (resource, requested, limit) in [ + ("column span", self.colspan, MAX_TABLE_COLUMNS), + ("row span", self.rowspan, MAX_TABLE_ROWS), + ( "cell duplication", - cell.spec.duplication_count, + self.duplication_count, MAX_TABLE_COLUMNS, - cell.start, - cell.end, - )); + ), + ] { + if requested > limit { + return Err(TableLimitViolation::new( + resource, requested, limit, start, end, + )); + } } + Ok(()) + } +} + +fn validate_cell_specifiers(cells: &[ParsedCell]) -> Result<(), TableLimitViolation> { + for cell in cells { + cell.spec.validate(cell.start, cell.end)?; } Ok(()) } @@ -770,6 +812,88 @@ fn validate_row_widths(rows: &[Vec]) -> Result<(), TableLimitViolati Ok(()) } +/// Column placement shared by complete and cooperative table construction. +pub(crate) struct CellPlacement { + columns: usize, + column: usize, + generated: usize, + active: Vec<(usize, usize, usize)>, + new_spans: Vec<(usize, usize, usize)>, + filled: bool, + rows: usize, +} + +impl CellPlacement { + pub(crate) fn new(columns: usize) -> Self { + Self { + columns: columns.max(1), + column: 0, + generated: 0, + active: Vec::new(), + new_spans: Vec::new(), + filled: false, + rows: 0, + } + } + pub(crate) fn generated(&self) -> usize { + self.generated + } + pub(crate) fn at_row_end(&mut self) -> bool { + while self.column < self.columns { + let Some(&(_, _, width)) = self + .active + .iter() + .find(|(pos, _, width)| self.column >= *pos && self.column < pos + width) + else { + break; + }; + self.column += width; + } + self.filled = self.column >= self.columns; + self.filled + } + pub(crate) fn place(&mut self, spec: CellSpecifier) { + let count = if spec.is_duplication { + spec.duplication_count + } else { + 1 + }; + let occupied = count.max(1) * spec.colspan.max(1); + if spec.rowspan > 1 { + self.new_spans + .push((self.column, spec.rowspan - 1, occupied)); + } + self.column += occupied; + self.generated += count; + self.filled = self.column >= self.columns; + } + pub(crate) fn finish_row( + &mut self, + start: usize, + end: usize, + ) -> Result<(), TableLimitViolation> { + if self.rows == MAX_TABLE_ROWS { + return Err(TableLimitViolation::new( + "row count", + self.rows + 1, + MAX_TABLE_ROWS, + start, + end, + )); + } + self.rows += 1; + self.active.retain_mut(|(_, remaining, _)| { + *remaining -= 1; + *remaining > 0 + }); + self.active.append(&mut self.new_spans); + self.column = 0; + self.generated = 0; + self.filled = false; + Ok(()) + } +} + /// Group a flat cell stream into rows of `ncols` columns. /// /// Placement is colspan-, duplication-, and rowspan-aware: a cell spanning @@ -784,74 +908,32 @@ fn group_cells_into_rows( ncols: usize, dropped: &mut Option<(usize, usize)>, ) -> Result>, TableLimitViolation> { - let ncols = ncols.max(1); let mut rows = Vec::new(); - // Columns occupied by rowspans carried down from earlier rows. - let mut active: Vec<(usize, usize, usize)> = Vec::new(); // (col, remaining_rows, width) + let mut placement = CellPlacement::new(ncols); let mut iter = cells.into_iter(); let mut next = iter.next(); - while next.is_some() { let mut row = Vec::new(); - let mut new_spans: Vec<(usize, usize, usize)> = Vec::new(); - let mut col = 0; - - while col < ncols { - // Skip columns occupied by an active rowspan from a previous row. - if let Some(&(_, _, width)) = active - .iter() - .find(|(pos, _, width)| col >= *pos && col < pos + width) - { - col += width; - continue; - } + while !placement.at_row_end() { let Some(cell) = next.take() else { break; }; next = iter.next(); - - let occupied = if cell.spec.is_duplication { - cell.spec.duplication_count.max(1) * cell.spec.colspan.max(1) - } else { - cell.spec.colspan.max(1) - }; - if cell.spec.rowspan > 1 { - new_spans.push((col, cell.spec.rowspan - 1, occupied)); - } + placement.place(cell.spec); row.push(cell); - col += occupied; } - - if col < ncols { - // Incomplete final row — asciidoctor drops it and warns. Capture - // the span of the dropped cells for the warning location. - if let (Some(first), Some(last)) = (row.first(), row.last()) { - *dropped = Some((first.start, last.end)); - } + let span = row + .first() + .zip(row.last()) + .map(|(first, last)| (first.start, last.end)); + if !placement.filled && next.is_none() { + *dropped = span; break; } - if rows.len() == MAX_TABLE_ROWS { - let (start, end) = row - .first() - .zip(row.last()) - .map_or((0, 0), |(first, last)| (first.start, last.end)); - return Err(TableLimitViolation::new( - "row count", - rows.len() + 1, - MAX_TABLE_ROWS, - start, - end, - )); - } + let (start, end) = span.unwrap_or((0, 0)); + placement.finish_row(start, end)?; rows.push(row); - // Age existing rowspans, then add the ones introduced by this row. - active.retain_mut(|(_, remaining, _)| { - *remaining -= 1; - *remaining > 0 - }); - active.extend(new_spans); } - Ok(rows) } diff --git a/acdc-parser/src/extensions/recognition.rs b/acdc-parser/src/extensions/recognition.rs index 5cac2bc7b..66de79aa3 100644 --- a/acdc-parser/src/extensions/recognition.rs +++ b/acdc-parser/src/extensions/recognition.rs @@ -27,6 +27,13 @@ pub(crate) fn recognize<'a>( format!("unregistered block macro: {name}"), ) })?; + let decode = |source: &'a str| { + state.raw_cell_separator.map_or(source, |separator| { + state.intern_cow(crate::blocks::table::decode_cell_escapes(source, separator)) + }) + }; + let target = decode(target); + let arguments = decode(arguments); let target = state.intern_cow(apply_attribute_substitutions( target, &[Substitution::Attributes], diff --git a/acdc-parser/src/grammar/document.rs b/acdc-parser/src/grammar/document.rs index a0a7d204a..002df1401 100644 --- a/acdc-parser/src/grammar/document.rs +++ b/acdc-parser/src/grammar/document.rs @@ -2,6 +2,7 @@ mod author; mod callouts; +mod compound; mod construction; mod coordinator; mod delimited; diff --git a/acdc-parser/src/grammar/document/compound.rs b/acdc-parser/src/grammar/document/compound.rs new file mode 100644 index 000000000..d0a8456fe --- /dev/null +++ b/acdc-parser/src/grammar/document/compound.rs @@ -0,0 +1,133 @@ +//! Commit compound children before advancing the enclosing source reader. + +use crate::{ + Block, Error, + grammar::{ParserState, state::BlockContext}, +}; + +use super::{ + RecognitionError, + construction::{ConstructionMode, DelimitedConstruction}, + coordinator::{BlockCursor, Execution}, + delimited::resolve_delimited_close, + document_parser, + metadata::assign_block_caption, + source::SourceInput, +}; + +impl BlockCursor { + pub(super) fn construct_streamed_compound<'a>( + &mut self, + input: &mut SourceInput<'a>, + state: &mut ParserState<'a>, + mut construction: DelimitedConstruction<'a>, + output: &mut Vec>, + accepted: &mut Execution< + '_, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, + >, + ) -> Result, RecognitionError> { + let mut params = construction.params; + // The closing delimiter is resolved after the child cursor finishes. + // Build the accepted shell with the existing builder without issuing an + // unterminated-block warning at the temporary end of the input window. + construction.params.close = Some((params.end, params.open_delim)); + let (mut block, _) = match construction.start(state) { + Ok(started) => started, + Err(error) => return Ok(Err(error)), + }; + match accepted.run(&mut block, state, output) { + Ok(true) => {} + Ok(false) => return Ok(Ok(())), + Err(error) => return Ok(Err(error)), + } + let mut child = BlockCursor::new(self.offset, ConstructionMode::Ordered); + child.base_offset = self.base_offset; + let previous_context = std::mem::replace(&mut state.block_context, BlockContext::Compound); + let previous_scope = std::mem::replace( + &mut state.source_scope_offset, + params.content_start + params.offset, + ); + input.push_boundary(params.open_delim); + let mut body = Vec::new(); + let result = child.collect(input, state, &mut body, accepted); + input.pop_boundary(); + state.block_context = previous_context; + state.source_scope_offset = previous_scope; + let mut end = match result? { + Ok(end) => end, + Err(error) => return Ok(Err(error)), + }; + while let Some(line) = + source_tail(state, end).and_then(|tail| tail.split_inclusive('\n').next()) + { + if !line.trim().is_empty() { + break; + } + end += line.len(); + } + let close = source_tail(state, end) + .and_then(|tail| tail.split_inclusive('\n').next()) + .filter(|line| { + document_parser::source_block_close(line, state, params.open_delim, false).is_ok() + }); + params.close = close.map(|_| (end - params.offset, params.open_delim)); + params.end = + end - params.offset + close.map_or(0, |line| line.trim_end_matches('\n').len()); + let close_location = match resolve_delimited_close(state, ¶ms) { + Ok(location) => location, + Err(error) => return Ok(Err(error)), + }; + let Some(source) = retain_body(state, params.content_start + params.offset, end) else { + return Ok(Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "missing committed compound source".into(), + ))); + }; + *block.location_mut() = + state.create_block_location(params.start, params.end, params.offset); + if let Block::DelimitedBlock(delimited) = &mut block { + delimited.close_delimiter_location = close_location; + delimited.source_text = Some(source); + } + let Some(slot) = crate::extensions::compound_body_mut(&mut block) else { + return Ok(Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "compound builder returned no child content slot".into(), + ))); + }; + *slot = body; + child.offset = + end - child.base_offset + close.map_or(0, |line| line.trim_end_matches('\n').len()); + self.offset = child.offset; + self.base_offset = child.base_offset; + assign_block_caption(state, &mut block); + output.push(block); + Ok(Ok(())) + } +} + +pub(super) fn retain_body<'a>( + state: &ParserState<'a>, + start: usize, + end: usize, +) -> Option<&'a str> { + state.source_slice(start..end).or_else(|| { + let origin = state.input_origin.as_ref()?; + let view = origin.index.window(start..end, state.arena)?; + let base = view.origin.as_ref().map_or(0, |origin| origin.base); + view.input.get(start - base..end - base) + }) +} + +fn source_tail<'a>(state: &ParserState<'a>, offset: usize) -> Option<&'a str> { + state + .source_tail(offset) + .filter(|tail| !tail.is_empty()) + .or_else(|| { + state + .input_origin + .as_ref() + .and_then(|origin| origin.index.tail(offset)) + }) +} diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index c0c0bfe47..57f04b473 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -17,7 +17,10 @@ use super::{ lists::ListEntry, metadata::{assign_block_caption, order_block_prefix_events}, sections::expected_child_level, - table::{InitialAttributes, construction::TableConstruction}, + table::{ + InitialAttributes, + construction::{TableConstruction, TableContent}, + }, }; /// A handler failure always escapes native content recovery. Effects that @@ -25,6 +28,7 @@ use super::{ pub(super) struct Execution<'handler, F> { callback: &'handler mut F, failed: bool, + macro_callbacks: usize, } impl<'handler, F> Execution<'handler, F> { @@ -32,22 +36,29 @@ impl<'handler, F> Execution<'handler, F> { Self { callback, failed: false, + macro_callbacks: 0, } } #[inline] pub(super) fn run<'a>( &mut self, - block: &Block<'a>, + block: &mut Block<'a>, state: &mut ParserState<'a>, - ) -> Result<(), Error> + output: &mut Vec>, + ) -> Result where - F: FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, { - let result = (self.callback)(block, state); + self.macro_callbacks += usize::from(matches!(block, Block::Extension(_))); + let result = (self.callback)(block, state, output); self.failed |= result.is_err(); result } + pub(super) const fn macro_callbacks(&self) -> usize { + self.macro_callbacks + } + pub(super) fn failed(&self) -> bool { self.failed } @@ -183,7 +194,7 @@ impl BlockCursor { blocks: &mut Vec>, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result, RecognitionError> { loop { @@ -191,6 +202,10 @@ impl BlockCursor { Ok(source) => source, Err(error) => return Ok(Err(error)), }; + if input.at_boundary(source, self, state) { + *blocks = order_block_prefix_events(std::mem::take(blocks)); + return Ok(Ok(self.base_offset + self.offset)); + } let mut step = BlockStep::end(Vec::new(), self.offset); if let Err(error) = self.advance_into(source, state, &mut step)? { return Ok(Err(error)); @@ -201,11 +216,12 @@ impl BlockCursor { *blocks = order_block_prefix_events(std::mem::take(blocks)); return Ok(Ok(self.base_offset + step.end)); } - BlockStepKind::Block(block) if !matches!(block, Block::Section(_)) => { - if let Err(error) = accepted.run(&block, state) { - return Ok(Err(error)); + BlockStepKind::Block(mut block) if !matches!(block, Block::Section(_)) => { + match accepted.run(&mut block, state, blocks) { + Ok(true) => blocks.push(block), + Ok(false) => {} + Err(error) => return Ok(Err(error)), } - blocks.push(block); continue; } kind @ (BlockStepKind::Block(_) @@ -228,52 +244,62 @@ impl BlockCursor { output: &mut Vec>, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result, RecognitionError> { + let kind = if let Some(source) = input.source_input() { + match kind { + BlockStepKind::Table(construction) if source.streaming_table() => { + return Ok(self.construct_streamed_table( + source, + state, + construction, + output, + accepted, + )); + } + BlockStepKind::Delimited(construction) if source.streaming_compound() => { + return self.construct_streamed_compound( + source, + state, + construction, + output, + accepted, + ); + } + kind @ (BlockStepKind::Block(_) + | BlockStepKind::Delimited(_) + | BlockStepKind::Table(_) + | BlockStepKind::Quote(_) + | BlockStepKind::List(_) + | BlockStepKind::End(_)) => kind, + } + } else { + kind + }; let needs_caption = matches!( &kind, BlockStepKind::Delimited(_) | BlockStepKind::Table(_) | BlockStepKind::Quote(_) ); - let mut table_content = None; - let (mut block, request) = match kind { - BlockStepKind::List(entry) => { - return self.construct_list_into( - input, - state, - &entry, - &crate::grammar::helpers::BlockParsingMetadata::new( - state.options.compatibility_mode, - ), - output, - accepted, - ); - } - BlockStepKind::Block(block) => (block, None), - BlockStepKind::Delimited(construction) => match construction.start(state) { - Ok(started) => started, - Err(error) => return Ok(Err(error)), - }, - BlockStepKind::Quote(construction) => match construction.start(state) { - Ok(started) => started, - Err(error) => return Ok(Err(error)), - }, - BlockStepKind::Table(construction) => match construction.start(state) { - Ok((block, content)) => { - table_content = Some(content); - (block, None) - } - Err(error) => return Ok(Err(error)), - }, - BlockStepKind::End(_) => { - return Ok(Err(Error::Parse( - Box::new(state.create_error_source_location(state.create_location( - self.base_offset + self.offset, - self.base_offset + self.offset, - ))), - "block construction received an end boundary".into(), - ))); - } + if let BlockStepKind::List(entry) = kind { + return self.construct_list_into( + input, + state, + &entry, + &crate::grammar::helpers::BlockParsingMetadata::new( + state.options.compatibility_mode, + ), + output, + accepted, + ); + } + let StartedBlock { + mut block, + request, + table_content, + } = match start_block(kind, state) { + Ok(started) => started, + Err(error) => return Ok(Err(error)), }; let child = if let Block::Section(section) = &block && self.mode == ConstructionMode::Ordered @@ -282,8 +308,10 @@ impl BlockCursor { } else { None }; - if let Err(error) = accepted.run(&block, state) { - return Ok(Err(error)); + match accepted.run(&mut block, state, output) { + Ok(true) => {} + Ok(false) => return Ok(Ok(())), + Err(error) => return Ok(Err(error)), } if let (Block::Section(section), Some(mut child)) = (&mut block, child) { let end = match child.collect(input, state, &mut section.content, accepted)? { @@ -293,20 +321,12 @@ impl BlockCursor { self.offset = child.offset; self.base_offset = child.base_offset; section.location = state.create_block_location(section.location.absolute_start, end, 0); + state.finish_section_warnings(section.heading_location.absolute_start); } - if let Some(request) = request { - let mut parser = CursorContent { accepted }; - let content = match parse_content(state, request, &mut parser) { - Ok(content) => content, - Err(error) => return Ok(Err(error)), - }; - let Some(body) = crate::extensions::compound_body_mut(&mut block) else { - return Ok(Err(Error::Parse( - Box::new(state.create_error_source_location(block.location().clone())), - "compound builder returned no child content slot".into(), - ))); - }; - *body = content; + if let Some(request) = request + && let Err(error) = construct_requested_content(&mut block, state, request, accepted) + { + return Ok(Err(error)); } if needs_caption { if let Some(content) = table_content @@ -322,13 +342,67 @@ impl BlockCursor { } } -struct CursorContent<'h, 'callback, F> { - accepted: &'h mut Execution<'callback, F>, +struct StartedBlock<'a> { + block: Block<'a>, + request: Option>, + table_content: Option>, +} + +fn start_block<'a>( + kind: BlockStepKind<'a>, + state: &mut ParserState<'a>, +) -> Result, Error> { + let mut table_content = None; + let (block, request) = match kind { + BlockStepKind::Block(block) => (block, None), + BlockStepKind::Delimited(construction) => construction.start(state)?, + BlockStepKind::Quote(construction) => construction.start(state)?, + BlockStepKind::Table(construction) => { + let (block, content) = construction.start(state)?; + table_content = Some(content); + (block, None) + } + BlockStepKind::List(_) | BlockStepKind::End(_) => { + return Err(Error::Parse( + Box::new(state.create_error_source_location(state.create_location(0, 0))), + "block construction received an unfinished boundary".into(), + )); + } + }; + Ok(StartedBlock { + block, + request, + table_content, + }) +} + +fn construct_requested_content<'a, F>( + block: &mut Block<'a>, + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + accepted: &mut Execution<'_, F>, +) -> Result<(), Error> +where + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, +{ + let content = parse_content(state, request, &mut CursorContent { accepted })?; + let Some(body) = crate::extensions::compound_body_mut(block) else { + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "compound builder returned no child content slot".into(), + )); + }; + *body = content; + Ok(()) +} + +pub(super) struct CursorContent<'h, 'callback, F> { + pub(super) accepted: &'h mut Execution<'callback, F>, } impl<'a, F> ContentParser<'a> for CursorContent<'_, '_, F> where - F: FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, { fn parse( &mut self, @@ -414,8 +488,7 @@ pub(crate) fn document<'a>( input: &'a str, state: &mut ParserState<'a>, ) -> Result, Error>, RecognitionError> { - // Registry callbacks still run after parsing. A registry alone must not - // change construction or diagnostic order before source handlers are wired. + // Ordinary parsing retains the recursive construction fast path. let prefix = match document_parser::document_prefix(input, state)? { Ok(prefix) => prefix, Err(error) => return Ok(Err(error)), @@ -444,11 +517,15 @@ pub(crate) fn document<'a>( /// Internal accepted-block execution boundary for documents and containers. /// Complete input uses the same ordered builders as the resumable source path. -pub(super) fn document_with<'a>( +pub(super) fn document_with_execution<'a>( input: &'a str, state: &mut ParserState<'a>, mode: ConstructionMode, - accepted: &mut impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + accepted: &mut impl FnMut( + &mut Block<'a>, + &mut ParserState<'a>, + &mut Vec>, + ) -> Result, ) -> Result, Error>, RecognitionError> { let prefix = match document_parser::document_prefix(input, state)? { Ok(prefix) => prefix, @@ -470,3 +547,15 @@ pub(super) fn document_with<'a>( blocks, )) } + +#[cfg(test)] +pub(super) fn document_with<'a>( + input: &'a str, + state: &mut ParserState<'a>, + mode: ConstructionMode, + accepted: &mut impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, +) -> Result, Error>, RecognitionError> { + document_with_execution(input, state, mode, &mut |block, state, _| { + accepted(block, state).map(|()| true) + }) +} diff --git a/acdc-parser/src/grammar/document/delimited.rs b/acdc-parser/src/grammar/document/delimited.rs index a5868f3b8..e90a61079 100644 --- a/acdc-parser/src/grammar/document/delimited.rs +++ b/acdc-parser/src/grammar/document/delimited.rs @@ -35,6 +35,11 @@ pub(super) struct ContentRequest<'a> { } pub(super) trait ContentParser<'a> { + /// Buffered cells have already passed through the table decoder. + fn raw_cell_separator(&self) -> Option { + None + } + fn parse( &mut self, state: &mut ParserState<'a>, @@ -121,7 +126,7 @@ pub(super) fn check_delimiters( /// Validate a closing delimiter and return its location. /// If the block has no closing delimiter, warn at the opening delimiter and /// return `None`. The caller keeps the block through end of input. -fn resolve_delimited_close<'input>( +pub(super) fn resolve_delimited_close<'input>( state: &mut ParserState<'input>, p: &DelimitedParams<'input>, ) -> Result, Error> { @@ -170,6 +175,13 @@ pub(super) enum DelimitedKind { } impl DelimitedKind { + pub(super) fn has_compound_body(self, style: Option<&str>) -> bool { + matches!( + self.with_style(style), + Self::Example | Self::Open | Self::Sidebar | Self::Quote + ) && !matches!(style, Some("comment" | "verse")) + } + pub(super) fn with_style(self, style: Option<&str>) -> Self { match (self, style) { (Self::Open | Self::Literal, Some("source" | "listing")) => Self::Listing, diff --git a/acdc-parser/src/grammar/document/input.rs b/acdc-parser/src/grammar/document/input.rs index 0c2c1d112..d42b84778 100644 --- a/acdc-parser/src/grammar/document/input.rs +++ b/acdc-parser/src/grammar/document/input.rs @@ -16,6 +16,30 @@ pub(super) enum ReadRequest<'a> { } pub(super) trait BlockInput<'a> { + /// Complete text does not expose resumable reader operations. + fn source_input(&mut self) -> Option<&mut super::source::SourceInput<'a>> { + None + } + + fn at_boundary( + &mut self, + source: &'a str, + cursor: &BlockCursor, + state: &mut ParserState<'a>, + ) -> bool { + self.source_input() + .and_then(|source| source.boundary()) + .is_some_and(|delimiter| { + source + .get(cursor.offset..) + .and_then(|tail| tail.split_inclusive('\n').next()) + .is_some_and(|line| { + super::document_parser::source_block_close(line, state, delimiter, false) + .is_ok() + }) + }) + } + /// Source failures cannot be recovered as malformed nested content. fn failed(&self) -> bool { false diff --git a/acdc-parser/src/grammar/document/lists/callout.rs b/acdc-parser/src/grammar/document/lists/callout.rs index e55cf91b4..c31c3d383 100644 --- a/acdc-parser/src/grammar/document/lists/callout.rs +++ b/acdc-parser/src/grammar/document/lists/callout.rs @@ -23,7 +23,7 @@ impl BlockCursor { metadata: &BlockParsingMetadata<'a>, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result, Error>, RecognitionError> { let source = match input.prepare(self, state, ReadRequest::ListHead(ListKind::Callout)) { @@ -66,7 +66,7 @@ impl BlockCursor { head: CalloutItemHead<'a>, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result>, Error>, RecognitionError> { let mut item = match head.finish(state, Ok(Vec::new()), self.offset, self.base_offset) { @@ -74,14 +74,14 @@ impl BlockCursor { Err(error) => return Ok(Err(error)), }; item.2 += self.base_offset; - let shell = build_callout_list( + let mut shell = build_callout_list( state, metadata, state.create_location(start, item.2), Vec::new(), &[], ); - if let Err(error) = accepted.run(&shell, state) { + if let Err(error) = accepted.run(&mut shell, state, &mut Vec::new()) { return Ok(Err(error)); } let mut items = Vec::new(); diff --git a/acdc-parser/src/grammar/document/lists/construction.rs b/acdc-parser/src/grammar/document/lists/construction.rs index 71158796d..3ee3ef6d3 100644 --- a/acdc-parser/src/grammar/document/lists/construction.rs +++ b/acdc-parser/src/grammar/document/lists/construction.rs @@ -27,7 +27,7 @@ impl BlockCursor { output: &mut Vec>, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result, RecognitionError> { let metadata = entry.metadata.as_deref().unwrap_or(parent_metadata); @@ -77,7 +77,7 @@ impl BlockCursor { output: &mut Vec>, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result, RecognitionError> { let (list_kind, start, head) = frame; @@ -105,7 +105,7 @@ impl BlockCursor { }, vec![item], ); - if let Err(error) = accepted.run(&block, state) { + if let Err(error) = accepted.run(&mut block, state, output) { return Ok(Err(error)); } let mut items = Vec::new(); @@ -187,7 +187,7 @@ impl BlockCursor { context: (ListKind<'a>, &'a str, &'a str), accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result>, Error>, RecognitionError> { let (kind, base_marker, marker) = context; @@ -199,6 +199,9 @@ impl BlockCursor { Ok(source) => source, Err(error) => return Ok(Err(error)), }; + if input.at_boundary(source, self, state) { + break; + } let step = document_parser::list_next( source, state, diff --git a/acdc-parser/src/grammar/document/lists/description.rs b/acdc-parser/src/grammar/document/lists/description.rs index e06be8e8d..e905c3d27 100644 --- a/acdc-parser/src/grammar/document/lists/description.rs +++ b/acdc-parser/src/grammar/document/lists/description.rs @@ -30,7 +30,7 @@ impl BlockCursor { metadata: &BlockParsingMetadata<'a>, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result, Error>, RecognitionError> { let source = match input.prepare( @@ -77,7 +77,7 @@ impl BlockCursor { initial: (DescriptionItemHead<'a>, Option>), accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result>, Error>, RecognitionError> { let (mut head, parent_scope) = initial; @@ -97,8 +97,8 @@ impl BlockCursor { end.max(source.term.delimiter_end) + head_base, 0, ); - let shell = build_description_list(metadata, location, Vec::new()); - if let Err(error) = accepted.run(&shell, state) { + let mut shell = build_description_list(metadata, location, Vec::new()); + if let Err(error) = accepted.run(&mut shell, state, &mut Vec::new()) { return Ok(Err(error)); } first = false; @@ -152,7 +152,7 @@ impl BlockCursor { delimiter: &'a str, accepted: &mut Execution< '_, - impl FnMut(&Block<'a>, &mut ParserState<'a>) -> Result<(), Error>, + impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, ) -> Result, Error>, RecognitionError> { let mut children = DescriptionChildren::default(); diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 852d8adab..17fddd104 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -140,8 +140,8 @@ peg::parser! { / document_attribute_match() (eol() / ![_]) { SourceLine::Attribute } / comment_line_prefix() source_line_tail() { SourceLine::Comment } / &atx_heading_match() source_line_tail() { SourceLine::Heading } - / open:block_open() (eol() / ![_]) { SourceLine::Delimited { delimiter: open.1, table: false, comment: matches!(open.0, DelimitedKind::Comment) } } - / delimiter:table_delimiter() (eol() / ![_]) { SourceLine::Delimited { delimiter, table: true, comment: false } } + / open:block_open() (eol() / ![_]) { SourceLine::Delimited { delimiter: open.1, kind: Some(open.0), table: false, comment: matches!(open.0, DelimitedKind::Comment) } } + / delimiter:table_delimiter() (eol() / ![_]) { SourceLine::Delimited { delimiter, kind: None, table: true, comment: false } } / (attribute_or_anchor_line_match() / title_line_match()) { SourceLine::Metadata } / extension_macro_source() (eol() / ![_]) { SourceLine::Macro } / (media_block_ahead_true() / toc_block_ahead()) source_line_tail() { SourceLine::Macro } @@ -1162,13 +1162,19 @@ peg::parser! { let location = state.create_error_source_location( state.create_block_location(section_level_start, section_level_end, offset), ); - state.add_warning(Warning::new( + let start = location.location.absolute_start; + let warning = Warning::new( WarningKind::SectionLevelOutOfSequence { expected: parent_level, got: section_level.1, }, Some(location), - )); + ); + if mode == ConstructionMode::Ordered { + state.defer_section_warning(start, warning); + } else { + state.add_warning(warning); + } } } diff --git a/acdc-parser/src/grammar/document/source.rs b/acdc-parser/src/grammar/document/source.rs index 09149335d..73ba7f3c2 100644 --- a/acdc-parser/src/grammar/document/source.rs +++ b/acdc-parser/src/grammar/document/source.rs @@ -14,23 +14,46 @@ use crate::{ use super::{ construction::ConstructionMode, - coordinator::{BlockCursor, Execution, document_with}, + coordinator::{BlockCursor, Execution, document_with_execution}, + delimited::DelimitedKind, document_parser, input::{BlockInput, ReadRequest}, lists::{ListKind, ListPhase, OrdinaryListKind}, }; -type Assignments<'a> = Vec<(AttributeName<'a>, DocumentAttributeAssignment<'a>)>; -type PendingAssignments = Rc>>; +pub(crate) type Assignments<'a> = Vec<(AttributeName<'a>, DocumentAttributeAssignment<'a>)>; +#[derive(Default)] +struct SourceUpdates<'a> { + assignments: RefCell>, + nested_parent: RefCell>>>, +} + +type PendingAssignments<'a> = Rc>; -/// A1's private execution seam. Public Registry callbacks retain their -/// existing post-acceptance timing until the A2 context contract is introduced. +/// Document-local execution after recognition has committed a block. pub(crate) trait SourceHandler { fn accepted<'a>( &mut self, - block: &Block<'a>, - attributes: &DocumentAttributes<'a>, - ) -> Result, String>; + _block: &Block<'a>, + _attributes: &DocumentAttributes<'a>, + ) -> Result, String> { + Ok(Vec::new()) + } + + fn construct<'a>( + &mut self, + block: &mut Block<'a>, + state: &mut ParserState<'a>, + ) -> Result<(bool, Assignments<'a>), Error> { + self.accepted(block, &state.document_attributes) + .map(|assignments| (true, assignments)) + .map_err(|message| { + Error::Extension( + Box::new(state.create_error_source_location(block.location().clone())), + message, + ) + }) + } } #[derive(Clone, Copy)] @@ -42,6 +65,7 @@ pub(super) enum SourceLine<'a> { Heading, Delimited { delimiter: &'a str, + kind: Option, table: bool, comment: bool, }, @@ -76,20 +100,32 @@ struct SourceStart<'a> { line: &'a str, form: SourceLine<'a>, verbatim: bool, + compound: bool, +} + +struct CellRead<'a> { + separator: char, + delimiter: &'a str, + start: usize, + end: Option, } pub(super) struct SourceInput<'a> { reader: Option>, pub(super) index: Rc>, pub(super) result: Option>, - updates: PendingAssignments, + updates: PendingAssignments<'a>, failed: bool, + stream_open: bool, + boundaries: Vec<&'a str>, + cells: Vec>, + stream_table: bool, } impl<'a> SourceInput<'a> { fn new( reader: SourceReader<'a>, - updates: PendingAssignments, + updates: PendingAssignments<'a>, index: Rc>, ) -> Self { Self { @@ -98,10 +134,64 @@ impl<'a> SourceInput<'a> { result: None, updates, failed: false, + stream_open: false, + boundaries: Vec::new(), + cells: Vec::new(), + stream_table: false, + } + } + + fn available_end(&self) -> usize { + self.cells + .last() + .and_then(|cell| cell.end) + .map_or(self.index.len(), |end| end.min(self.index.len())) + } + + pub(super) fn line( + &mut self, + offset: usize, + state: &mut ParserState<'a>, + ) -> Result, Error> { + if self + .cells + .last() + .and_then(|cell| cell.end) + .is_some_and(|end| offset >= end) + { + return Ok(None); + } + let Some(line) = self.raw_line(offset, state)? else { + return Ok(None); + }; + if let Some(cell) = self.cells.last_mut() { + let boundary = if document_parser::source_block_close(line, state, cell.delimiter, true) + .is_ok() + { + Some(0) + } else { + crate::blocks::table::next_cell_boundary(line, cell.separator, offset != cell.start) + .map(|(end, _, _)| end) + }; + if let Some(end) = boundary { + cell.end = Some(offset + end); + return Ok((end > 0).then(|| &line[..end])); + } } + Ok(Some(line)) } - fn line( + pub(super) fn raw_line( + &mut self, + offset: usize, + state: &mut ParserState<'a>, + ) -> Result, Error> { + let result = self.read_line(offset, state); + self.failed |= result.is_err(); + result + } + + fn read_line( &mut self, offset: usize, state: &mut ParserState<'a>, @@ -119,7 +209,7 @@ impl<'a> SourceInput<'a> { let Some(reader) = self.reader.as_mut() else { return Ok(None); }; - for (name, assignment) in self.updates.borrow_mut().drain(..) { + for (name, assignment) in self.updates.assignments.borrow_mut().drain(..) { let value = match assignment { DocumentAttributeAssignment::Set(value) => RawAttributeValue::Resolved(value), DocumentAttributeAssignment::Unset => RawAttributeValue::Unset, @@ -174,10 +264,38 @@ impl<'a> SourceInput<'a> { request: ReadRequest<'a>, state: &mut ParserState<'a>, ) -> Result { + self.stream_open = false; + self.stream_table = false; let Some(unit) = self.block_start(start, request, state)? else { - return Ok(self.index.len()); + return Ok(self.available_end()); }; let offset = unit.offset + unit.line.len(); + if self.boundaries.last().is_some_and(|delimiter| { + document_parser::source_block_close(unit.line, state, delimiter, false).is_ok() + }) { + return Ok(offset); + } + if let SourceLine::Delimited { + delimiter, table, .. + } = unit.form + && self.index.tail(offset).is_some_and(|tail| { + tail.split_inclusive('\n').any(|line| { + document_parser::source_block_close(line, state, delimiter, table).is_ok() + }) + }) + { + return self.delimited_end(offset, delimiter, table, state); + } + if state.options.extensions.is_some() + && matches!(unit.form, SourceLine::Delimited { table: true, delimiter, .. } if delimiter.starts_with(['|', '!'])) + { + self.stream_table = true; + return Ok(offset); + } + if state.options.extensions.is_some() && unit.compound { + self.stream_open = true; + return Ok(offset); + } if let SourceLine::Delimited { delimiter, table, .. } = unit.form @@ -249,6 +367,7 @@ impl<'a> SourceInput<'a> { delimiter, table, comment: true, + kind: _, } = form { offset = self.delimited_end(offset + line.len(), delimiter, table, state)?; @@ -289,6 +408,7 @@ impl<'a> SourceInput<'a> { line, form, verbatim, + compound: matches!(form, SourceLine::Delimited {kind: Some(kind), ..} if kind.has_compound_body(style.as_deref())), })); } } @@ -344,6 +464,7 @@ impl<'a> SourceInput<'a> { delimiter, table, comment: true, + kind: _, } => { offset = self.delimited_end(offset, delimiter, table, state)?; } @@ -512,7 +633,15 @@ impl<'a> SourceInput<'a> { } pub(super) fn prepare_header(&mut self, state: &mut ParserState<'a>) -> Result<&'a str, Error> { - let mut offset = 0; + self.prepare_header_from(0, state) + } + + pub(super) fn prepare_header_from( + &mut self, + start: usize, + state: &mut ParserState<'a>, + ) -> Result<&'a str, Error> { + let mut offset = start; let mut title = false; let mut header_started = false; while let Some(line) = self.line(offset, state)? { @@ -526,6 +655,7 @@ impl<'a> SourceInput<'a> { delimiter, table, comment: true, + kind: _, } = kind { while let Some(next) = self.line(offset, state)? { @@ -572,9 +702,13 @@ impl<'a> SourceInput<'a> { } let view = self .index - .window(0..offset.min(self.index.len()), state.arena) + .window(start..offset.min(self.available_end()), state.arena) .ok_or_else(|| source_error(state, 0, "missing document prefix window"))?; - let source = view.input; + let base = view.origin.as_ref().map_or(0, |origin| origin.base); + let source = view + .input + .get(start - base..offset.min(self.available_end()) - base) + .ok_or_else(|| source_error(state, start, "missing nested header window"))?; state.set_source_view(view); Ok(source) } @@ -607,7 +741,11 @@ impl<'a> SourceInput<'a> { let start = cursor.base_offset + cursor.offset; let end = self.scan(start, request, state)?; if let Some(origin) = state.input_origin.as_ref().filter(|origin| { - Rc::ptr_eq(&origin.index, &self.index) + !self.stream_open + && !self.stream_table + && self.cells.is_empty() + && self.boundaries.is_empty() + && Rc::ptr_eq(&origin.index, &self.index) && origin.base <= start && end <= origin.base + state.input.len() && origin.base + state.input.len() <= self.index.len() @@ -616,11 +754,42 @@ impl<'a> SourceInput<'a> { cursor.base_offset = origin.base; return Ok(state.input); } - let view = self + let mut view = self .index .window(start..end, state.arena) .ok_or_else(|| source_error(state, start, "missing accepted source window"))?; let base = view.origin.as_ref().map_or(0, |origin| origin.base); + if self.stream_open + || self.stream_table + || !self.cells.is_empty() + || !self.boundaries.is_empty() + { + let mut limit = end; + if let Some(delimiter) = self.boundaries.last() { + let mut offset = start; + for line in view + .input + .get(start - base..end - base) + .unwrap_or_default() + .split_inclusive('\n') + { + if offset != start + && document_parser::source_block_close(line, state, delimiter, false) + .is_ok() + { + limit = offset.saturating_sub(usize::from( + state.source_byte(offset.saturating_sub(1)) == Some(b'\n'), + )); + break; + } + offset += line.len(); + } + } + view.input = view + .input + .get(..limit - base) + .ok_or_else(|| source_error(state, start, "missing compound opening window"))?; + } cursor.offset = start - base; cursor.base_offset = base; let source = view.input; @@ -629,7 +798,60 @@ impl<'a> SourceInput<'a> { } } +impl<'a> SourceInput<'a> { + pub(super) fn streaming_table(&self) -> bool { + self.stream_table + } + + pub(super) fn cell_end(&self) -> Option { + self.cells.last().and_then(|cell| cell.end) + } + pub(super) fn table_header_lookahead(&self) -> Vec<&'a str> { + self.reader + .as_ref() + .map_or_else(Vec::new, SourceReader::table_header_lookahead) + } + pub(super) fn begin_cell(&mut self, separator: char, delimiter: &'a str, start: usize) { + self.cells.push(CellRead { + separator, + delimiter, + start, + end: None, + }); + } + pub(super) fn end_cell(&mut self) { + self.cells.pop(); + } + pub(super) fn reader_attributes( + &mut self, + attributes: &DocumentAttributes<'a>, + nested_parent: Option<&Rc>>, + ) { + self.updates.nested_parent.replace(nested_parent.cloned()); + self.updates.assignments.borrow_mut().clear(); + if let Some(reader) = self.reader.as_mut() { + reader.options_mut().document_attributes = attributes.clone().into_static(); + } + } + + pub(super) fn streaming_compound(&self) -> bool { + self.stream_open + } + pub(super) fn boundary(&self) -> Option<&'a str> { + self.boundaries.last().copied() + } + pub(super) fn push_boundary(&mut self, delimiter: &'a str) { + self.boundaries.push(delimiter); + } + pub(super) fn pop_boundary(&mut self) { + self.boundaries.pop(); + } +} + impl<'a> BlockInput<'a> for SourceInput<'a> { + fn source_input(&mut self) -> Option<&mut SourceInput<'a>> { + Some(self) + } #[inline] fn prepare( &mut self, @@ -637,7 +859,9 @@ impl<'a> BlockInput<'a> for SourceInput<'a> { state: &mut ParserState<'a>, request: ReadRequest<'a>, ) -> Result<&'a str, Error> { - if matches!(request, ReadRequest::Block) + if self.boundaries.is_empty() + && self.cells.is_empty() + && matches!(request, ReadRequest::Block) && let Some(source) = self.buffered_prose(cursor, state) { return Ok(source); @@ -706,18 +930,21 @@ pub(crate) fn document_from_source<'a>( origin: None, }); } - let mut callback = |block: &Block<'a>, state: &mut ParserState<'a>| { - execute_source_handler(handler, block, state, None) - }; - let document = document_with(source, state, ConstructionMode::Ordered, &mut callback) - .map_err(|error| recognition_error(error, state))??; + let mut callback = + |block: &mut Block<'a>, state: &mut ParserState<'a>, output: &mut Vec>| { + execute_source_handler(handler, block, state, None, output) + }; + let document = + document_with_execution(source, state, ConstructionMode::Ordered, &mut callback) + .map_err(|error| recognition_error(error, state))??; *conditionals = result.conditionals; return Ok(document); } let updates = PendingAssignments::default(); - let mut callback = |block: &Block<'a>, state: &mut ParserState<'a>| { - execute_source_handler(handler, block, state, Some(&updates)) - }; + let mut callback = + |block: &mut Block<'a>, state: &mut ParserState<'a>, output: &mut Vec>| { + execute_source_handler(handler, block, state, Some(&updates), output) + }; let index = state .input_origin .as_ref() @@ -770,29 +997,24 @@ pub(crate) fn document_from_source<'a>( #[inline] fn execute_source_handler<'a>( handler: &mut dyn SourceHandler, - block: &Block<'a>, + block: &mut Block<'a>, state: &mut ParserState<'a>, - updates: Option<&PendingAssignments>, -) -> Result<(), Error> { - let assignments = handler - .accepted(block, &state.document_attributes) - .map_err(|message| { - Error::Extension( - Box::new(state.create_error_source_location(block.location().clone())), - message, - ) - })?; + updates: Option<&PendingAssignments<'a>>, + output: &mut Vec>, +) -> Result { + let (keep, assignments) = handler.construct(block, state)?; if !assignments.is_empty() { - apply_assignments(assignments, block, state, updates); + apply_assignments(assignments, block, state, updates, output); } - Ok(()) + Ok(keep) } fn apply_assignments<'a>( assignments: Assignments<'a>, block: &Block<'a>, state: &mut ParserState<'a>, - updates: Option<&PendingAssignments>, + updates: Option<&PendingAssignments<'a>>, + output: &mut Vec>, ) { for (name, assignment) in assignments { let name = state.intern_cow(name); @@ -808,13 +1030,25 @@ fn apply_assignments<'a>( }, false, block.location().clone(), - ) && state.nested_parent_attributes.is_none() - && let Some(updates) = updates - { - updates.borrow_mut().push(( - name.to_owned().into(), - event.assignment().clone().into_static(), - )); + ) { + if let Some(updates) = updates + && state + .nested_parent_attributes + .as_ref() + .is_none_or(|parent| { + updates + .nested_parent + .borrow() + .as_ref() + .is_some_and(|selected| Rc::ptr_eq(parent, selected)) + }) + { + updates.assignments.borrow_mut().push(( + name.to_owned().into(), + event.assignment().clone().into_static(), + )); + } + output.push(Block::DocumentAttribute(event)); } } } diff --git a/acdc-parser/src/grammar/document/table.rs b/acdc-parser/src/grammar/document/table.rs index e61e1c5a3..e0adaac03 100644 --- a/acdc-parser/src/grammar/document/table.rs +++ b/acdc-parser/src/grammar/document/table.rs @@ -1,6 +1,7 @@ //! Table blocks and cell content. pub(super) mod construction; +mod streaming; #[cfg(test)] mod tests; @@ -48,6 +49,113 @@ pub(super) struct TableParseParams<'a> { pub(super) closing: TableClosing<'a>, } +pub(super) struct TableSettings { + pub(super) separator: String, + pub(super) ncols: Option, + pub(super) column_formats: Vec, +} + +pub(super) fn table_settings( + state: &ParserState<'_>, + block_metadata: &BlockParsingMetadata<'_>, + table_location: &Location, + default_separator: &str, + report_warnings: bool, +) -> Result { + let separator = if let Some(AttributeValue::String(sep)) = + block_metadata.metadata.attributes.get("separator") + { + sep.to_string() + } else if let Some(AttributeValue::String(format)) = + block_metadata.metadata.attributes.get("format") + { + match &**format { + "csv" => ",", + "dsv" => ":", + "tsv" => "\t", + unknown_format => { + if report_warnings { + state.add_warning(Warning::new( + WarningKind::TableUnknownFormat { + format: unknown_format.to_string(), + }, + Some(state.create_error_source_location(table_location.clone())), + )); + } + default_separator + } + } + .to_string() + } else { + default_separator.to_string() + }; + + let (ncols, column_formats) = if let Some(AttributeValue::String(cols)) = + block_metadata.metadata.attributes.get("cols") + { + let cols = if cols.contains(' ') { + Cow::Owned(cols.replace(' ', "")) + } else { + Cow::Borrowed(cols.as_ref()) + }; + let mut specs = Vec::new(); + let count_only = !cols.is_empty() + && cols.bytes().all(|byte| byte.is_ascii_digit()) + && (cols.len() == 1 || !cols.starts_with('0')); + if count_only { + let count = cols.parse::().unwrap_or(MAX_TABLE_COLUMNS + 1); + if count > MAX_TABLE_COLUMNS { + return Err(table_limit_error( + state, + table_location.clone(), + "column count", + count, + MAX_TABLE_COLUMNS, + )); + } + specs.resize(count, ColumnFormat::default()); + } else { + for input in cols.split(if cols.contains(',') { ',' } else { ';' }) { + let Some((multiplier, spec, width_error)) = parse_column_spec(input) else { + continue; + }; + if report_warnings && let Some(width) = width_error { + state.add_warning(Warning::new( + WarningKind::ContentRecovery { + message: format!( + "table column width `{width}` exceeds the maximum of {}; using proportional width 1", + u32::MAX, + ).into(), + }, + Some(state.create_error_source_location(table_location.clone())), + )); + } + let column_count = specs.len().saturating_add(multiplier); + if column_count > MAX_TABLE_COLUMNS { + return Err(table_limit_error( + state, + table_location.clone(), + "column count", + column_count, + MAX_TABLE_COLUMNS, + )); + } + specs.extend(std::iter::repeat_n(spec, multiplier)); + } + } + + ((!specs.is_empty()).then_some(specs.len()), specs) + } else { + (None, Vec::new()) + }; + + Ok(TableSettings { + separator, + ncols, + column_formats, + }) +} + fn table_limit_error( state: &ParserState<'_>, location: Location, @@ -237,90 +345,17 @@ fn parse_table_with_cells<'input>( } }; - let separator = if let Some(AttributeValue::String(sep)) = - block_metadata.metadata.attributes.get("separator") - { - sep.to_string() - } else if let Some(AttributeValue::String(format)) = - block_metadata.metadata.attributes.get("format") - { - match &**format { - "csv" => ",", - "dsv" => ":", - "tsv" => "\t", - unknown_format => { - state.add_warning(Warning::new( - WarningKind::TableUnknownFormat { - format: unknown_format.to_string(), - }, - Some(state.create_error_source_location(table_location.clone())), - )); - default_separator - } - } - .to_string() - } else { - default_separator.to_string() - }; - - let (ncols, column_formats) = if let Some(AttributeValue::String(cols)) = - block_metadata.metadata.attributes.get("cols") - { - let cols = if cols.contains(' ') { - Cow::Owned(cols.replace(' ', "")) - } else { - Cow::Borrowed(cols.as_ref()) - }; - let mut specs = Vec::new(); - let count_only = !cols.is_empty() - && cols.bytes().all(|byte| byte.is_ascii_digit()) - && (cols.len() == 1 || !cols.starts_with('0')); - if count_only { - let count = cols.parse::().unwrap_or(MAX_TABLE_COLUMNS + 1); - if count > MAX_TABLE_COLUMNS { - return Err(table_limit_error( - state, - table_location.clone(), - "column count", - count, - MAX_TABLE_COLUMNS, - )); - } - specs.resize(count, ColumnFormat::default()); - } else { - for input in cols.split(if cols.contains(',') { ',' } else { ';' }) { - let Some((multiplier, spec, width_error)) = parse_column_spec(input) else { - continue; - }; - if let Some(width) = width_error { - state.add_warning(Warning::new( - WarningKind::ContentRecovery { - message: format!( - "table column width `{width}` exceeds the maximum of {}; using proportional width 1", - u32::MAX, - ).into(), - }, - Some(state.create_error_source_location(table_location.clone())), - )); - } - let column_count = specs.len().saturating_add(multiplier); - if column_count > MAX_TABLE_COLUMNS { - return Err(table_limit_error( - state, - table_location.clone(), - "column count", - column_count, - MAX_TABLE_COLUMNS, - )); - } - specs.extend(std::iter::repeat_n(spec, multiplier)); - } - } - - ((!specs.is_empty()).then_some(specs.len()), specs) - } else { - (None, Vec::new()) - }; + let TableSettings { + separator, + ncols, + column_formats, + } = table_settings( + state, + block_metadata, + &table_location, + default_separator, + true, + )?; let mut has_header = block_metadata.metadata.options.contains(&"header"); @@ -755,8 +790,11 @@ fn parse_table_cell_with_parser<'a>( &mut state.document_attributes, )); + let outer_separator = + std::mem::replace(&mut state.raw_cell_separator, parser.raw_cell_separator()); let result = parser.nested_document(state, content, cell_start_offset, &mut initial_attributes); + state.raw_cell_separator = outer_separator; if result.is_err() { state.footnote_tracker.borrow_mut().discard_definitions(); diff --git a/acdc-parser/src/grammar/document/table/streaming.rs b/acdc-parser/src/grammar/document/table/streaming.rs new file mode 100644 index 000000000..d2e03832a --- /dev/null +++ b/acdc-parser/src/grammar/document/table/streaming.rs @@ -0,0 +1,444 @@ +//! Read `AsciiDoc` cell bodies cooperatively, retaining the shared table layout. + +use std::collections::HashMap; + +use crate::{ + Block, ColumnStyle, Error, SourceLocation, TableCell, Warning, + blocks::table::{ + CellPlacement, CellSpecifier, implicit_header, inferred_columns, next_cell_boundary, + }, + grammar::ParserState, +}; + +use super::super::{ + RecognitionError, + compound::retain_body, + construction::ConstructionMode, + coordinator::{BlockCursor, Execution}, + delimited::{ContentParser, ContentRequest}, + document_parser, + source::SourceInput, +}; +use super::{ + CellParser, InitialAttributes, PreparedTableCellParagraph, TableClosing, TableSettings, + construction::TableConstruction, parse_table_cell_with_parser, parse_table_with_cells, + table_settings, +}; + +struct CellReader<'i, 'h, 'callback, 'a, F> { + input: &'i mut SourceInput<'a>, + accepted: &'h mut Execution<'callback, F>, + start: usize, + end: usize, + separator: char, +} + +impl<'a, F> ContentParser<'a> for CellReader<'_, '_, '_, 'a, F> +where + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, +{ + fn raw_cell_separator(&self) -> Option { + Some(self.separator) + } + + fn parse( + &mut self, + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + ) -> Result>, Error> { + super::super::coordinator::CursorContent { + accepted: self.accepted, + } + .parse(state, request) + } + + fn nested_document( + &mut self, + state: &mut ParserState<'a>, + _source: &'a str, + _offset: usize, + initial: &mut InitialAttributes<'a>, + ) -> Result>, Error>, RecognitionError> { + self.input.reader_attributes( + &state.document_attributes, + state.nested_parent_attributes.as_ref(), + ); + let source = match self.input.prepare_header_from(self.start, state) { + Ok(source) => source, + Err(error) => return Ok(Err(error)), + }; + let leading = source.len() - source.trim_start().len(); + let start = self.start + leading; + let prefix = match document_parser::nested_document_prefix( + source.trim_start(), + state, + start, + initial, + )? { + Ok(prefix) => prefix, + Err(error) => return Ok(Err(error)), + }; + let mut cursor = BlockCursor::new(prefix.body_offset, ConstructionMode::Ordered); + cursor.base_offset = start; + let mut blocks = prefix.blocks; + let result = cursor.collect(self.input, state, &mut blocks, self.accepted)?; + match result { + Ok(end) => { + self.end = self.input.cell_end().unwrap_or(end); + Ok(Ok(blocks)) + } + Err(error) => Ok(Err(error)), + } + } +} + +struct CommittedCell<'a> { + cell: TableCell<'a>, + warnings: Vec, + macro_callbacks: usize, + used: bool, + location: SourceLocation, +} + +struct CompletedCells<'p, P> { + cells: HashMap>, + parser: P, +} + +impl<'a, P: ContentParser<'a>> CellParser<'a> for CompletedCells<'a, P> { + fn parse( + &mut self, + source: &'a str, + state: &mut ParserState<'a>, + offset: usize, + spec: &CellSpecifier, + prepared: &mut Option>>, + ) -> Result, Error> { + if spec.style == Some(ColumnStyle::AsciiDoc) + && let Some(committed) = self.cells.get_mut(&offset) + && !committed.used + { + committed.used = true; + for warning in std::mem::take(&mut committed.warnings) { + state.add_warning(warning); + } + let mut cell = committed.cell.clone(); + cell.colspan = spec.colspan; + cell.rowspan = spec.rowspan; + cell.halign = spec.halign; + cell.valign = spec.valign; + return Ok(cell); + } + parse_table_cell_with_parser(source, state, offset, spec, prepared, &mut self.parser) + } +} + +struct TableReader<'a> { + delimiter: &'a str, + separator: char, + settings: TableSettings, + placement: CellPlacement, + header: bool, + cells: HashMap>, +} + +impl<'a> TableReader<'a> { + fn style(&self, mut spec: CellSpecifier) -> CellSpecifier { + if self.header { + spec.style = None; + } else if spec.style.is_none() + && let Some(column) = self.settings.column_formats.get(self.placement.generated()) + && column.style != ColumnStyle::Default + { + spec.style = Some(column.style); + } + if spec.is_duplication && spec.duplication_count == 0 { + spec.style = None; + } + spec + } + + fn cell( + &mut self, + input: &mut SourceInput<'a>, + state: &mut ParserState<'a>, + start: usize, + spec: CellSpecifier, + accepted: &mut Execution<'_, F>, + ) -> Result + where + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, + { + let before = accepted.macro_callbacks(); + input.begin_cell(self.separator, self.delimiter, start); + let mut warnings = Vec::new(); + let result = if spec.style == Some(ColumnStyle::AsciiDoc) { + // Replay grammar diagnostics when the final layout consumes this + // cell. Reader diagnostics keep their original shared collector. + let outer_warnings = std::mem::take(&mut state.warnings); + let outer_warnings_start = std::mem::replace(&mut state.warnings_start, 0); + let mut reader = CellReader { + input, + accepted, + start, + end: start, + separator: self.separator, + }; + let result = + parse_table_cell_with_parser("", state, start, &spec, &mut None, &mut reader) + .map(|cell| (reader.end, Some(cell))); + warnings = state.warnings.borrow_mut().split_off(0); + state.warnings = outer_warnings; + state.warnings_start = outer_warnings_start; + result + } else { + let mut end = start; + loop { + match input.line(end, state) { + Ok(Some(line)) => end += line.len(), + Ok(None) => break Ok((input.cell_end().unwrap_or(end), None)), + Err(error) => break Err(error), + } + } + }; + input.end_cell(); + input.reader_attributes( + &state.document_attributes, + state.nested_parent_attributes.as_ref(), + ); + let (end, cell) = match result { + Ok(parsed) => parsed, + Err(error) => { + for warning in warnings { + state.add_warning(warning); + } + return Err(error); + } + }; + if let Some(cell) = cell { + let text = retain_body(state, start, end).ok_or_else(|| { + Error::Extension( + Box::new( + state.create_error_source_location(state.create_location(start, start)), + ), + "missing committed table cell source".into(), + ) + })?; + let key = start + text.len() - text.trim_start().len(); + self.cells.insert( + key, + CommittedCell { + cell, + warnings, + macro_callbacks: accepted.macro_callbacks() - before, + used: false, + location: state.create_error_source_location(state.create_location(key, key)), + }, + ); + } + Ok(end) + } + + fn collect( + &mut self, + input: &mut SourceInput<'a>, + state: &mut ParserState<'a>, + mut offset: usize, + accepted: &mut Execution<'_, F>, + ) -> Result<(usize, Option<&'a str>), Error> + where + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, + { + while let Some(line) = input.raw_line(offset, state)? { + if document_parser::source_block_close(line, state, self.delimiter, true).is_ok() { + return Ok((offset, Some(line.trim_end_matches('\n')))); + } + if let Some((_, content_start, spec)) = next_cell_boundary(line, self.separator, true) { + spec.validate(offset, offset + content_start) + .map_err(|violation| { + super::table_limit_error( + state, + state.create_location(violation.start, violation.end), + violation.resource, + violation.requested, + violation.limit, + ) + })?; + while self.placement.at_row_end() { + self.placement + .finish_row(offset, offset + content_start) + .map_err(|violation| { + super::table_limit_error( + state, + state.create_location(violation.start, violation.end), + violation.resource, + violation.requested, + violation.limit, + ) + })?; + self.header = false; + } + let style = self.style(spec); + self.placement.place(spec); + offset = self.cell(input, state, offset + content_start, style, accepted)?; + } else { + offset += line.len(); + } + } + Ok((offset, None)) + } +} + +impl BlockCursor { + pub(in crate::grammar::document) fn construct_streamed_table<'a, F>( + &mut self, + input: &mut SourceInput<'a>, + state: &mut ParserState<'a>, + construction: TableConstruction<'a>, + output: &mut Vec>, + accepted: &mut Execution<'_, F>, + ) -> Result<(), Error> + where + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, + { + let TableConstruction { + metadata, + mut params, + } = construction; + let location = state.create_block_location(params.start, params.end, params.offset); + // The final builder reports diagnostics using the completed table span. + let settings = + table_settings(state, &metadata, &location, params.default_separator, false)?; + if !matches!(settings.separator.as_str(), "|" | "!") { + return self.construct_buffered_table( + input, + state, + TableConstruction { metadata, params }, + output, + accepted, + ); + } + let start = params.content_start + params.offset; + let first = match input.raw_line(start, state) { + Ok(Some(line)) => line, + Ok(None) => "", + Err(error) => return Err(error), + }; + let mut lines = vec![first.trim_end_matches('\n')]; + lines.extend(input.table_header_lookahead()); + let columns = settings + .ncols + .unwrap_or_else(|| inferred_columns(first, &settings.separator)); + let header = !metadata.metadata.options.contains(&"noheader") + && (metadata.metadata.options.contains(&"header") + || implicit_header(&lines, &settings.separator)); + let separator = settings.separator.chars().next().unwrap_or('|'); + let mut reader = TableReader { + delimiter: params.open_delim, + separator, + settings, + placement: CellPlacement::new(columns), + header, + cells: HashMap::new(), + }; + let (end, close) = reader.collect(input, state, start, accepted)?; + params.end = end - params.offset + close.map_or(0, str::len); + params.content_end = end.saturating_sub(usize::from(close.is_some())) - params.offset; + params.content = + retain_body(state, start, params.content_end + params.offset).ok_or_else(|| { + Error::Extension( + Box::new(state.create_error_source_location(location)), + "missing committed table source".into(), + ) + })?; + params.closing = close.map_or(TableClosing::Unterminated, |close_delim| { + TableClosing::Terminated { + close_delim, + close_start: end - params.offset, + } + }); + let mut parser = CompletedCells { + cells: reader.cells, + parser: super::super::coordinator::CursorContent { accepted }, + }; + let mut block = parse_table_with_cells(¶ms, state, &metadata, &mut parser)?; + if let Some(discarded) = parser + .cells + .values() + .filter(|cell| !cell.used && cell.macro_callbacks > 0) + .min_by_key(|cell| cell.location.location.absolute_start) + { + return Err(Error::Extension( + Box::new(discarded.location.clone()), + "table layout discarded a cell after its block macro executed".into(), + )); + } + match accepted.run(&mut block, state, output) { + Ok(true) => { + super::super::metadata::assign_block_caption(state, &mut block); + output.push(block); + } + Ok(false) => {} + Err(error) => return Err(error), + } + self.offset = params.end; + self.base_offset = params.offset; + Ok(()) + } +} + +impl BlockCursor { + fn construct_buffered_table<'a, F>( + &mut self, + input: &mut SourceInput<'a>, + state: &mut ParserState<'a>, + mut construction: TableConstruction<'a>, + output: &mut Vec>, + accepted: &mut Execution<'_, F>, + ) -> Result<(), Error> + where + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, + { + let params = &mut construction.params; + let start = params.content_start + params.offset; + let mut end = start; + let mut close = None; + while let Some(line) = input.raw_line(end, state)? { + if document_parser::source_block_close(line, state, params.open_delim, true).is_ok() { + close = Some(line.trim_end_matches('\n')); + break; + } + end += line.len(); + } + params.end = end - params.offset + close.map_or(0, str::len); + params.content_end = end.saturating_sub(usize::from(close.is_some())) - params.offset; + params.content = + retain_body(state, start, params.content_end + params.offset).ok_or_else(|| { + Error::Extension( + Box::new( + state.create_error_source_location(state.create_location(start, start)), + ), + "missing buffered table source".into(), + ) + })?; + params.closing = close.map_or(TableClosing::Unterminated, |close_delim| { + TableClosing::Terminated { + close_delim, + close_start: end - params.offset, + } + }); + self.offset = params.end; + self.base_offset = params.offset; + let (mut block, content) = construction.start(state)?; + if accepted.run(&mut block, state, output)? { + content.finish( + &mut block, + state, + &mut super::super::coordinator::CursorContent { accepted }, + )?; + super::super::metadata::assign_block_caption(state, &mut block); + output.push(block); + } + Ok(()) + } +} diff --git a/acdc-parser/src/grammar/source.rs b/acdc-parser/src/grammar/source.rs index d27640006..c7e34801b 100644 --- a/acdc-parser/src/grammar/source.rs +++ b/acdc-parser/src/grammar/source.rs @@ -90,11 +90,10 @@ impl<'a> SourceIndex<'a> { fn remember_window(&self, start: usize, text: &'a str) { let mut windows = self.windows.borrow_mut(); if let Some(last) = windows.last() { - debug_assert!( - start >= last.start, - "source windows advance in source order" - ); - if start + text.len() <= last.start + last.text.len() { + // Completed containers can retain their whole body after their + // children have advanced the cursor. Keep only forward windows in + // the lookup cache; the container owns this retained borrow. + if start < last.start || start + text.len() <= last.start + last.text.len() { return; } } diff --git a/acdc-parser/src/grammar/state.rs b/acdc-parser/src/grammar/state.rs index 4e617f16b..63f581bb7 100644 --- a/acdc-parser/src/grammar/state.rs +++ b/acdc-parser/src/grammar/state.rs @@ -160,6 +160,9 @@ pub(crate) struct ParserState<'a> { /// Inline owners share this buffer, map their newly collected diagnostics, /// then reinsert them in their parent's coordinates. pub(crate) warnings: Rc>, + /// Raw cooperative cells retain table escapes until syntax interpretation. + pub(crate) raw_cell_separator: Option, + deferred_section_warnings: Vec<(usize, Warning)>, // Earlier warnings may use a different substring's coordinates. pub(super) warnings_start: usize, /// When true, inline parsing uses a reduced rule set that only matches formatting @@ -400,6 +403,21 @@ impl<'a> FootnoteTracker<'a> { } impl<'a> ParserState<'a> { + pub(super) fn defer_section_warning(&mut self, start: usize, warning: Warning) { + self.deferred_section_warnings.push((start, warning)); + } + + pub(super) fn finish_section_warnings(&mut self, start: usize) { + while let Some(index) = self + .deferred_section_warnings + .iter() + .position(|(heading, _)| *heading == start) + { + let (_, warning) = self.deferred_section_warnings.swap_remove(index); + self.add_warning(warning); + } + } + /// Finalize a footnote only after its locations are document-absolute. pub(crate) fn finalize_footnote(&self, footnote: &mut Footnote<'a>) { if self.scope == ParserScope::Document @@ -846,6 +864,8 @@ impl<'a> ParserState<'a> { source_ranges: Vec::new(), included_files: HashSet::new(), warnings: Rc::default(), + raw_cell_separator: None, + deferred_section_warnings: Vec::new(), warnings_start: 0, quotes_only: false, attribute_passthroughs: Rc::default(), @@ -906,6 +926,8 @@ impl<'a> ParserState<'a> { source_ranges: Vec::new(), included_files: HashSet::new(), warnings: Rc::default(), + raw_cell_separator: None, + deferred_section_warnings: Vec::new(), warnings_start: 0, quotes_only: true, attribute_passthroughs: Rc::default(), @@ -969,6 +991,8 @@ impl<'a> ParserState<'a> { included_files: HashSet::new(), // Each inline owner maps only the diagnostics appended in its scope. warnings: Rc::clone(&parent.warnings), + raw_cell_separator: None, + deferred_section_warnings: Vec::new(), warnings_start: parent.warnings.borrow().len(), quotes_only: parent.quotes_only, attribute_passthroughs: Rc::clone(&parent.attribute_passthroughs), diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs index b281c1dcb..c41aeb9a5 100644 --- a/acdc-parser/src/preprocessor/cursor.rs +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -152,6 +152,24 @@ impl Emission<'_> { } impl<'input> InputCursor<'input> { + pub(super) fn table_header_lookahead(&self) -> Vec<&'input str> { + if let Some(include) = &self.include { + include.cursor.table_header_lookahead() + } else { + let mut remaining = self.lines.clone(); + let Some(first) = remaining.next() else { + return Vec::new(); + }; + let mut lines = vec![first]; + if first.trim().is_empty() + && let Some(next) = remaining.find(|line| !line.trim().is_empty()) + { + lines.push(next); + } + lines + } + } + pub(super) fn can_finish_without_reading(&mut self) -> bool { self.lines.peek().is_none() && self diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs index 901cede1b..da3cc007a 100644 --- a/acdc-parser/src/preprocessor/source.rs +++ b/acdc-parser/src/preprocessor/source.rs @@ -131,6 +131,12 @@ impl<'a> SourceReader<'a> { }) } + pub(crate) fn table_header_lookahead(&self) -> Vec<&'a str> { + self.cursor + .as_ref() + .map_or_else(Vec::new, InputCursor::table_header_lookahead) + } + pub(crate) fn options_mut(&mut self) -> &mut Options<'static> { Rc::make_mut(&mut self.options) } diff --git a/acdc-parser/src/source_tests.rs b/acdc-parser/src/source_tests.rs index 5d353f8cf..487c35ac8 100644 --- a/acdc-parser/src/source_tests.rs +++ b/acdc-parser/src/source_tests.rs @@ -440,9 +440,9 @@ fn source_driver_preserves_buffered_body_and_cell_attribute_scope( .conditionals() .map(crate::ConditionalEvaluation::is_active) .collect::>(), - [false, propagates] + [true, propagates] ); - assert!(!parsed.preprocessed_source().contains("Early.")); + assert!(parsed.preprocessed_source().contains("Early.")); assert_eq!(parsed.preprocessed_source().contains("Later."), propagates); } Ok(()) From 0a001708684abe8dc97d826b5fcc565a97b0157c Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 14 Nov 2026 08:11:21 +0100 Subject: [PATCH 12/55] feat(parser): run registered macros in source order Run block macros as their blocks commit so callbacks can affect later conditionals and includes. Keep mutable handlers and deferred requests local to each document, with original source and attribute snapshots. Cover compound bodies and AsciiDoc cells with regressions and fixtures. Document buffered CSV/TSV behavior and effects that survive later errors. Refs SC-536 --- acdc-parser/CHANGELOG.md | 13 +- acdc-parser/README.adoc | 20 +- acdc-parser/README.md | 20 +- acdc-parser/benches/parser_bench.rs | 6 +- .../tests/extensions/nested_source_order.adoc | 20 + .../tests/extensions/nested_source_order.json | 252 ++++++++++++ .../tests/extensions/session_order.adoc | 17 + .../tests/extensions/session_order.json | 249 ++++++++++++ .../includes/extensions/session_order.adoc | 7 + acdc-parser/src/extensions/block_macro.rs | 50 ++- acdc-parser/src/extensions/finalization.rs | 9 - acdc-parser/src/extensions/mod.rs | 46 ++- acdc-parser/src/extensions/recognition.rs | 3 +- acdc-parser/src/extensions/registry.rs | 21 +- acdc-parser/src/extensions/session.rs | 205 +++------- acdc-parser/src/extensions/tests/mod.rs | 379 +++++++++++++++++- acdc-parser/src/extensions/tests/support.rs | 42 +- acdc-parser/src/grammar/attributes.rs | 4 + acdc-parser/src/grammar/document.rs | 2 +- .../grammar/document/construction/tests.rs | 1 + acdc-parser/src/grammar/mod.rs | 3 +- acdc-parser/src/lib.rs | 37 +- acdc-parser/src/source_tests.rs | 32 +- acdc-parser/tests/extensions.rs | 71 +++- acdc-parser/tests/support/fixtures.rs | 16 +- .../html/tests/typed_document_entrypoints.rs | 6 +- 26 files changed, 1304 insertions(+), 227 deletions(-) create mode 100644 acdc-parser/fixtures/tests/extensions/nested_source_order.adoc create mode 100644 acdc-parser/fixtures/tests/extensions/nested_source_order.json create mode 100644 acdc-parser/fixtures/tests/extensions/session_order.adoc create mode 100644 acdc-parser/fixtures/tests/extensions/session_order.json create mode 100644 acdc-parser/fixtures/tests/includes/extensions/session_order.adoc diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 28b3026ac..06d6926bc 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -201,9 +201,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Edits repair references, TOC and scoped footnotes while preserving surviving section and caption numbers. Call `ExtensionParseResult::finish()` before conversion or checked ASG export; - unresolved requests return a located error. Callbacks run after parsing and - cannot change later includes or conditionals, unlike source-changing - Asciidoctor extensions. + unresolved requests return a located error. Block-macro callbacks now run + once as their blocks commit. `MacroExecutionContext::set_attribute` and + `unset_attribute` affect later conditionals, includes, and substitutions under + normal document assignment policy. Callback effects already performed remain + if a later block fails. Quoted empty positional arguments override defaults; + omitted slots retain their positions. Nested source ordering supports compound + bodies and pipe/exclamation AsciiDoc cells, including cell-local attributes; + Asciidoctor 2.0.26 buffers those bodies before invoking their macros. Other + table formats retain buffered preprocessing. Discarding a table cell after + its callback executed is a located error rather than silent recovery. - Faster parsing of paragraphs, deeply nested blocks, mixed ASCII and Unicode text, formatting, inline passthroughs, and duplicated ordinary table cells diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index a7da280fa..d4624e23e 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2056,10 +2056,22 @@ to preserve their isolation. The fixture runner's case names are unchanged. == Registered extensions Applications can register block macros and ordered tree processors with -`extensions::Registry`. Each parse creates fresh processor instances. Callbacks -run once after the document is accepted and cannot change later includes, -conditionals, or parsing. This differs from source-changing Asciidoctor extensions. -Both compatibility modes support registrations. +`extensions::Registry`. Each parse creates fresh processor instances. Block-macro +callbacks run once when their block commits. `MacroExecutionContext::set_attribute` +and `unset_attribute` request changes before subsequent conditionals and includes, +under normal document assignment policy. The invocation retains the original +source location and a read-only attribute snapshot. Both compatibility modes +support registrations. Factories are shared; handlers may use document-local, +non-`Send` state. Completed callback effects remain if later parsing fails. + +Nested source ordering supports compound bodies and pipe/exclamation-delimited +AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered +preprocessing. Unlike Asciidoctor 2.0.26, callbacks in supported nested bodies can +affect later directives in the same body. Cell attributes follow the normal +inheritance policy and stay local. Table-cell duplication repeats handlers over +the selected source and gives each deferred request a distinct identity. +A table layout that discards a cell after its callback ran returns a located +extension error, since those effects cannot be rolled back. Use `query()` to inspect typed block, content, attribute, and caption views. Document-local `TargetId` handles survive insertions and placeholder replacement; diff --git a/acdc-parser/README.md b/acdc-parser/README.md index f3a4dc479..6816fc553 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1700,10 +1700,22 @@ to preserve their isolation. The fixture runner's case names are unchanged. ## Registered extensions Applications can register block macros and ordered tree processors with -`extensions::Registry`. Each parse creates fresh processor instances. Callbacks -run once after the document is accepted and cannot change later includes, -conditionals, or parsing. This differs from source-changing Asciidoctor extensions. -Both compatibility modes support registrations. +`extensions::Registry`. Each parse creates fresh processor instances. Block-macro +callbacks run once when their block commits. `MacroExecutionContext::set_attribute` +and `unset_attribute` request changes before subsequent conditionals and includes, +under normal document assignment policy. The invocation retains the original +source location and a read-only attribute snapshot. Both compatibility modes +support registrations. Factories are shared; handlers may use document-local, +non-`Send` state. Completed callback effects remain if later parsing fails. + +Nested source ordering supports compound bodies and pipe/exclamation-delimited +AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered +preprocessing. Unlike Asciidoctor 2.0.26, callbacks in supported nested bodies can +affect later directives in the same body. Cell attributes follow the normal +inheritance policy and stay local. Table-cell duplication repeats handlers over +the selected source and gives each deferred request a distinct identity. +A table layout that discards a cell after its callback ran returns a located +extension error, since those effects cannot be rolled back. Use `query()` to inspect typed block, content, attribute, and caption views. Document-local `TargetId` handles survive insertions and placeholder replacement; diff --git a/acdc-parser/benches/parser_bench.rs b/acdc-parser/benches/parser_bench.rs index 2e93d2286..cfd746f4a 100644 --- a/acdc-parser/benches/parser_bench.rs +++ b/acdc-parser/benches/parser_bench.rs @@ -208,7 +208,11 @@ fn diagnostic_collection_benchmark(c: &mut Criterion) { struct CheapMacro; impl BlockMacroProcessor for CheapMacro { - fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result { + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { black_box(invocation); Ok(BlockMacroOutput::None) } diff --git a/acdc-parser/fixtures/tests/extensions/nested_source_order.adoc b/acdc-parser/fixtures/tests/extensions/nested_source_order.adoc new file mode 100644 index 000000000..a754d5c6e --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/nested_source_order.adoc @@ -0,0 +1,20 @@ +:mode: outer + +==== +configure::mode[compound] + +ifdef::mode[] +record::{mode}[] +endif::[] +==== + +[cols=a] +|=== +|configure::mode[cell] + +ifdef::mode[] +include::../includes/extensions/session_order.adoc[] +endif::[] +|=== + +record::{mode}[] diff --git a/acdc-parser/fixtures/tests/extensions/nested_source_order.json b/acdc-parser/fixtures/tests/extensions/nested_source_order.json new file mode 100644 index 000000000..b535acca3 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/nested_source_order.json @@ -0,0 +1,252 @@ +{ + "name": "document", + "type": "block", + "attributes": { + "mode": "outer" + }, + "blocks": [ + { + "name": "example", + "type": "block", + "form": "delimited", + "delimiter": "====", + "blocks": [ + { + "name": "mode", + "type": "attribute", + "value": "compound", + "location": [ + { + "line": 4, + "col": 1 + }, + { + "line": 4, + "col": 25 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"fallback\"},\"call\":1,\"mode\":\"compound\",\"positional\":[],\"target\":\"compound\"}", + "location": [ + { + "line": 7, + "col": 1 + }, + { + "line": 7, + "col": 16 + } + ] + } + ], + "location": [ + { + "line": 7, + "col": 1 + }, + { + "line": 7, + "col": 16 + } + ] + } + ], + "location": [ + { + "line": 3, + "col": 1 + }, + { + "line": 9, + "col": 4 + } + ] + }, + { + "name": "table", + "type": "block", + "form": "delimited", + "delimiter": "|===", + "metadata": { + "attributes": { + "cols": "a" + } + }, + "content": { + "header": null, + "footer": null, + "rows": [ + { + "columns": [ + { + "footnote_scope": true, + "content": [ + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"fallback\"},\"call\":2,\"mode\":\"compound\",\"positional\":[],\"target\":\"compound\"}", + "location": [ + { + "line": 1, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 1, + "col": 16, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 1, + "col": 16, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"a,b\",\"second\":\"\"},\"call\":3,\"mode\":\"compound\",\"positional\":[\"a,b\"],\"target\":\"compound\"}", + "location": [ + { + "line": 6, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 6, + "col": 31, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + } + ], + "location": [ + { + "line": 6, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 6, + "col": 31, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + } + ], + "style": "asciidoc" + } + ] + } + ], + "columns": [ + { + "style": "asciidoc" + } + ], + "location": [ + { + "line": 12, + "col": 1 + }, + { + "line": 18, + "col": 4 + } + ] + }, + "location": [ + { + "line": 11, + "col": 1 + }, + { + "line": 18, + "col": 4 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"fallback\"},\"call\":4,\"mode\":\"compound\",\"positional\":[],\"target\":\"compound\"}", + "location": [ + { + "line": 20, + "col": 1 + }, + { + "line": 20, + "col": 16 + } + ] + } + ], + "location": [ + { + "line": 20, + "col": 1 + }, + { + "line": 20, + "col": 16 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 20, + "col": 16 + } + ] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/extensions/session_order.adoc b/acdc-parser/fixtures/tests/extensions/session_order.adoc new file mode 100644 index 000000000..7ac5e24f1 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/session_order.adoc @@ -0,0 +1,17 @@ +:mode: before + +record::{mode}[one,,three,first="",second="quoted, value"] + +configure::mode[after] + +ifdef::mode[] +include::../includes/extensions/session_order.adoc[] +endif::[] + +configure::mode[unset=true] + +ifndef::mode[] +record::unset["",,last] +endif::[] + +unknown::ordinary[] diff --git a/acdc-parser/fixtures/tests/extensions/session_order.json b/acdc-parser/fixtures/tests/extensions/session_order.json new file mode 100644 index 000000000..988675a96 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/session_order.json @@ -0,0 +1,249 @@ +{ + "name": "document", + "type": "block", + "attributes": { + "mode": "before" + }, + "blocks": [ + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"\",\"second\":\"quoted, value\",\"third\":\"three\"},\"call\":1,\"mode\":\"before\",\"positional\":[\"one\",null,\"three\"],\"target\":\"before\"}", + "location": [ + { + "line": 3, + "col": 1 + }, + { + "line": 3, + "col": 58 + } + ] + } + ], + "location": [ + { + "line": 3, + "col": 1 + }, + { + "line": 3, + "col": 58 + } + ] + }, + { + "name": "mode", + "type": "attribute", + "value": "after", + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 5, + "col": 22 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"fallback\"},\"call\":2,\"mode\":\"after\",\"positional\":[],\"target\":\"after\"}", + "location": [ + { + "line": 1, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 1, + "col": 16, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 1, + "col": 16, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + }, + { + "name": "mode", + "type": "attribute", + "value": "included", + "location": [ + { + "line": 3, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 3, + "col": 25, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"a,b\",\"second\":\"\"},\"call\":3,\"mode\":\"included\",\"positional\":[\"a,b\"],\"target\":\"included\"}", + "location": [ + { + "line": 6, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 6, + "col": 31, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + } + ], + "location": [ + { + "line": 6, + "col": 1, + "file": [ + "../includes/extensions/session_order.adoc" + ] + }, + { + "line": 6, + "col": 31, + "file": [ + "../includes/extensions/session_order.adoc" + ] + } + ] + }, + { + "name": "mode", + "type": "attribute", + "value": false, + "location": [ + { + "line": 11, + "col": 1 + }, + { + "line": 11, + "col": 27 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "{\"attributes\":{\"first\":\"\",\"third\":\"last\"},\"call\":4,\"mode\":null,\"positional\":[\"\",null,\"last\"],\"target\":\"unset\"}", + "location": [ + { + "line": 14, + "col": 1 + }, + { + "line": 14, + "col": 23 + } + ] + } + ], + "location": [ + { + "line": 14, + "col": 1 + }, + { + "line": 14, + "col": 23 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "unknown::ordinary[]", + "location": [ + { + "line": 17, + "col": 1 + }, + { + "line": 17, + "col": 19 + } + ] + } + ], + "location": [ + { + "line": 17, + "col": 1 + }, + { + "line": 17, + "col": 19 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 17, + "col": 19 + } + ] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/includes/extensions/session_order.adoc b/acdc-parser/fixtures/tests/includes/extensions/session_order.adoc new file mode 100644 index 000000000..2665695e1 --- /dev/null +++ b/acdc-parser/fixtures/tests/includes/extensions/session_order.adoc @@ -0,0 +1,7 @@ +record::{mode}[] + +configure::mode[included] + +ifdef::mode[] +record::{mode}["a,b",second=""] +endif::[] diff --git a/acdc-parser/src/extensions/block_macro.rs b/acdc-parser/src/extensions/block_macro.rs index b497236df..98ae43692 100644 --- a/acdc-parser/src/extensions/block_macro.rs +++ b/acdc-parser/src/extensions/block_macro.rs @@ -1,6 +1,9 @@ use std::{borrow::Cow, fmt, sync::Arc}; -use crate::{DocumentAttributes, ElementAttributes, SourceLocation}; +use crate::{ + DocumentAttributeAssignment, DocumentAttributeValue, DocumentAttributes, ElementAttributes, + SourceLocation, +}; /// The parser scope in which a block macro can be recognized. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -113,7 +116,50 @@ pub trait BlockMacroProcessor { /// /// # Errors /// Return a message describing why this invocation cannot be processed. - fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result; + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + context: &mut MacroExecutionContext, + ) -> Result; +} + +impl BlockMacroProcessor for F +where + F: FnMut(&MacroInvocation<'_>, &mut MacroExecutionContext) -> Result, +{ + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + context: &mut MacroExecutionContext, + ) -> Result { + self(invocation, context) + } +} + +/// Attribute changes requested by one committed callback. +/// +/// The host applies these changes in order after a successful callback, using +/// normal document assignment policy, before advancing to subsequent source. +/// Values are already resolved; literal attribute references are not expanded again. +#[derive(Debug, Default)] +pub struct MacroExecutionContext { + pub(crate) assignments: Vec<(Cow<'static, str>, DocumentAttributeAssignment<'static>)>, +} + +impl MacroExecutionContext { + pub fn set_attribute( + &mut self, + name: impl Into>, + value: impl Into>, + ) { + self.assignments + .push((name.into(), DocumentAttributeAssignment::Set(value.into()))); + } + + pub fn unset_attribute(&mut self, name: impl Into>) { + self.assignments + .push((name.into(), DocumentAttributeAssignment::Unset)); + } } /// Content produced by a registered block macro. diff --git a/acdc-parser/src/extensions/finalization.rs b/acdc-parser/src/extensions/finalization.rs index b49353085..d8e7c8e55 100644 --- a/acdc-parser/src/extensions/finalization.rs +++ b/acdc-parser/src/extensions/finalization.rs @@ -118,12 +118,3 @@ fn failure(document: &crate::Document<'_>, error: impl std::fmt::Display) -> Err error.to_string(), ) } - -pub(crate) fn repair_macros(document: &mut crate::Document<'_>) -> Result<(), Error> { - document - .rebuild_footnotes() - .map_err(|error| failure(document, error))?; - document - .rebuild_references_and_toc() - .map_err(|error| failure(document, error)) -} diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 2e1571c76..15a7668c2 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -7,7 +7,7 @@ //! //! struct Greeting; //! impl BlockMacroProcessor for Greeting { -//! fn process(&mut self, call: &MacroInvocation<'_>) -> Result { +//! fn process(&mut self, call: &MacroInvocation<'_>, _: &mut acdc_parser::extensions::MacroExecutionContext) -> Result { //! Ok(BlockMacroOutput::Paragraph(format!("Hello, {}!", call.target))) //! } //! } @@ -21,14 +21,43 @@ //! # Ok::<(), Box>(()) //! ``` //! -//! On success, each accepted macro runs once, in document order, after the document is accepted. -//! Its attribute snapshot reflects the macro's position. The host repairs catalogs -//! after the callbacks finish. -//! Callbacks cannot affect conditionals, includes, or later parsing. Deferred -//! blocks retain their arguments and a session-local identity; they are not +//! Each accepted macro runs once at its committed block boundary, in source order. +//! Its attribute snapshot reflects the macro's position. The callback's mutable +//! [`MacroExecutionContext`] queues attribute sets and unsets. The host applies +//! accepted changes as body attribute events before advancing the source reader. +//! Caller locks, intrinsic restrictions, and nested-document policy still apply. +//! Callback errors stop parsing; effects from earlier callbacks are not undone. +//! Deferred blocks retain their arguments and a session-local identity; they are not //! renderable content. `ExtensionParseResult::finish()` rejects unresolved requests //! and returns an ordinary `ParseResult` for conversion. //! +//! Source ordering also applies inside compound bodies and pipe/exclamation +//! `AsciiDoc` cells. Other table formats retain buffered preprocessing. Nested +//! attributes follow the normal inheritance policy and remain local to the cell. +//! A table cannot silently discard a cell after its callback executed; that +//! layout failure is a located extension error. Preprocessing selects authored +//! cell content once; duplicate cells run their own handlers over that selection. +//! +//! ``` +//! use acdc_parser::{Options, extensions::{ +//! BlockMacro, BlockMacroOutput, MacroExecutionContext, MacroInvocation, Registry, +//! }}; +//! +//! let mut builder = Registry::builder(); +//! builder.register(BlockMacro::new("configure", || { +//! |call: &MacroInvocation<'_>, context: &mut MacroExecutionContext| { +//! context.set_attribute("audience", call.target.to_string()); +//! Ok(BlockMacroOutput::None) +//! } +//! }))?; +//! let parsed = builder.build().parse( +//! "configure::expert[]\n\nifdef::audience[]\nVisible to {audience}.\nendif::[]", +//! &Options::default(), +//! )?.finish()?; +//! assert!(parsed.conditionals().next().unwrap().is_active()); +//! # Ok::<(), Box>(()) +//! ``` +//! //! Query parsed blocks by semantic context and let the host assign link targets: //! //! ``` @@ -61,7 +90,7 @@ //! //! struct Request; //! impl BlockMacroProcessor for Request { -//! fn process(&mut self, _: &MacroInvocation<'_>) -> Result { +//! fn process(&mut self, _: &MacroInvocation<'_>, _: &mut acdc_parser::extensions::MacroExecutionContext) -> Result { //! Ok(BlockMacroOutput::Deferred) //! } //! } @@ -105,7 +134,8 @@ pub(crate) use traversal::{TablePart, compound_body_mut, ordinary_list_items_mut mod tree_processor; pub use block_macro::{ - BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroContext, MacroInvocation, MacroTarget, + BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroContext, MacroExecutionContext, + MacroInvocation, MacroTarget, }; pub use builder::BlockBuilder; pub use deferred::{DeferredBlock, ExtensionBlock, PlaceholderId}; diff --git a/acdc-parser/src/extensions/recognition.rs b/acdc-parser/src/extensions/recognition.rs index 66de79aa3..95aed44a3 100644 --- a/acdc-parser/src/extensions/recognition.rs +++ b/acdc-parser/src/extensions/recognition.rs @@ -58,6 +58,7 @@ pub(crate) fn recognize<'a>( if argument.name.is_some() && argument.is_unset() { continue; } + let empty_slot = argument.is_empty_slot(); let value = state.intern_str(&argument.value); if let Some(name) = argument.name { attributes.set( @@ -66,7 +67,7 @@ pub(crate) fn recognize<'a>( ); } else { positional.resize(slot, None); - positional.push((!value.is_empty()).then_some(value)); + positional.push((!empty_slot).then_some(value)); } } for (name, value) in descriptor.positional.iter().zip(&positional) { diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 23e231ba2..92a6f800f 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -138,10 +138,11 @@ impl Registry { /// Parse with fresh processors and retain this document's deferred requests. /// - /// Macro processors run after the complete document is accepted. The host - /// repairs captions and catalogs, then tree processors run once in - /// registration order, with catalog repair after each edit. Callbacks cannot - /// change source processing. + /// Macro processors run once at committed block boundaries, before the + /// reader advances to later conditionals and includes. Attribute changes + /// follow normal document assignment policy. Tree processors then run once + /// in registration order, with catalog repair after each edit. Effects from + /// completed callbacks are not rolled back if a later block fails. /// An empty registry uses the ordinary parser path. /// /// # Errors @@ -199,6 +200,18 @@ impl Registry { .map(|descriptor| (index, descriptor)) } + /// A conservative dispatch filter, not a syntax recognizer. Includes can + /// introduce registered names that are absent from the entry source. + pub(crate) fn may_execute(&self, source: &str) -> bool { + source.match_indices("::").any(|(end, _)| { + let name = source[..end] + .rsplit(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-') + .next() + .unwrap_or_default(); + name == "include" || self.0.names.contains_key(name) + }) + } + pub(crate) fn session(&self) -> Session { Session::new( self.0 diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index c42a44af0..4eb249905 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -1,9 +1,6 @@ use std::{cell::OnceCell, fmt}; -use crate::{ - Block, DelimitedBlockType, Document, Error, InlineNode, Paragraph, ParseResult, Plain, - grammar::ParserState, -}; +use crate::{Block, Error, InlineNode, Paragraph, ParseResult, Plain, grammar::ParserState}; use super::{ BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, PlaceholderId, TargetId, @@ -106,157 +103,75 @@ impl Session { self.identity.get_or_init(DocumentIdentity::default) } - pub(crate) fn process<'a>( + fn block<'a>( &mut self, - document: &mut Document<'a>, + block: &mut Block<'a>, state: &ParserState<'a>, + context: &mut super::MacroExecutionContext, ) -> Result { - self.blocks(&mut document.blocks, state)?; - Ok(self.processed_blocks) - } - - fn blocks<'a>( - &mut self, - blocks: &mut Vec>, - state: &ParserState<'a>, - ) -> Result<(), Error> { - let mut result = Ok(()); - blocks.retain_mut(|block| { - if result.is_err() { - return true; - } - match self.block(block, state) { - Ok(keep) => keep, - Err(error) => { - result = Err(error); - true - } - } - }); - result - } - - fn block<'a>(&mut self, block: &mut Block<'a>, state: &ParserState<'a>) -> Result { - match block { - Block::Extension(extension) => { - self.processed_blocks = true; - let output = self - .processors - .get_mut(extension.processor) - .ok_or_else(|| { - Error::Extension( - Box::new(extension.invocation.location.clone()), - "processor is absent from the document session".into(), - ) - })? - .process(&extension.invocation) - .map_err(|message| { - Error::Extension(Box::new(extension.invocation.location.clone()), message) - })?; - match output { - BlockMacroOutput::Paragraph(text) => { - let mut paragraph = Paragraph::new( - vec![InlineNode::PlainText(Plain { - content: state.intern_str(&text), - location: extension.location.clone(), - escaped: true, - })], - extension.location.clone(), - ); - paragraph.metadata = std::mem::take(&mut extension.metadata); - paragraph.title = std::mem::take(&mut extension.title); - if let Some(kind) = crate::CaptionKind::for_style(paragraph.metadata.style) - { - paragraph.metadata.caption = Some(crate::Caption::resolve( - ¶graph.metadata, - &extension.invocation.document_attributes, - kind, - )); - } - *block = Block::Paragraph(paragraph); + if let Block::Extension(extension) = block { + self.processed_blocks = true; + let output = self + .processors + .get_mut(extension.processor) + .ok_or_else(|| { + Error::Extension( + Box::new(extension.invocation.location.clone()), + "processor is absent from the document session".into(), + ) + })? + .process(&extension.invocation, context) + .map_err(|message| { + Error::Extension(Box::new(extension.invocation.location.clone()), message) + })?; + match output { + BlockMacroOutput::Paragraph(text) => { + let mut paragraph = Paragraph::new( + vec![InlineNode::PlainText(Plain { + content: state.intern_str(&text), + location: extension.location.clone(), + escaped: true, + })], + extension.location.clone(), + ); + paragraph.metadata = std::mem::take(&mut extension.metadata); + paragraph.title = std::mem::take(&mut extension.title); + if let Some(kind) = crate::CaptionKind::for_style(paragraph.metadata.style) { + paragraph.metadata.caption = Some(crate::Caption::resolve( + ¶graph.metadata, + &extension.invocation.document_attributes, + kind, + )); } - BlockMacroOutput::None => return Ok(false), - BlockMacroOutput::Deferred => { - let placeholder = PlaceholderId(self.deferred.len()); - extension.placeholder = Some(placeholder); - self.deferred.push(DeferredBlock { - placeholder, - invocation: extension.invocation.to_owned_invocation(), - target: TargetId { - document: self.identity().clone(), - slot: placeholder.0, - }, - }); - } - } - } - Block::Section(section) => self.blocks(&mut section.content, state)?, - Block::Admonition(admonition) => self.blocks(&mut admonition.blocks, state)?, - Block::UnorderedList(list) => { - for item in &mut list.items { - self.blocks(&mut item.blocks, state)?; + *block = Block::Paragraph(paragraph); } - } - Block::OrderedList(list) => { - for item in &mut list.items { - self.blocks(&mut item.blocks, state)?; - } - } - Block::CalloutList(list) => { - for item in &mut list.items { - self.blocks(&mut item.blocks, state)?; + BlockMacroOutput::None => return Ok(false), + BlockMacroOutput::Deferred => { + let placeholder = PlaceholderId(self.deferred.len()); + extension.placeholder = Some(placeholder); + self.deferred.push(DeferredBlock { + placeholder, + invocation: extension.invocation.to_owned_invocation(), + target: TargetId { + document: self.identity().clone(), + slot: placeholder.0, + }, + }); } } - Block::DescriptionList(list) => { - for item in &mut list.items { - if let Some(definition) = &mut item.definition { - self.blocks(&mut definition.blocks, state)?; - } - } - } - Block::DelimitedBlock(delimited) => self.delimited(&mut delimited.inner, state)?, - Block::TableOfContents(_) - | Block::DiscreteHeading(_) - | Block::DocumentAttribute(_) - | Block::ThematicBreak(_) - | Block::PageBreak(_) - | Block::Paragraph(_) - | Block::Image(_) - | Block::Audio(_) - | Block::Video(_) - | Block::Comment(_) => {} } Ok(true) } - fn delimited<'a>( +} + +impl crate::grammar::SourceHandler for Session { + fn construct<'a>( &mut self, - inner: &mut DelimitedBlockType<'a>, - state: &ParserState<'a>, - ) -> Result<(), Error> { - match inner { - DelimitedBlockType::DelimitedExample(blocks) - | DelimitedBlockType::DelimitedOpen(blocks) - | DelimitedBlockType::DelimitedSidebar(blocks) - | DelimitedBlockType::DelimitedQuote(blocks) => self.blocks(blocks, state)?, - DelimitedBlockType::DelimitedTable(table) => { - for row in table - .header - .iter_mut() - .chain(&mut table.rows) - .chain(&mut table.footer) - { - for column in &mut row.columns { - self.blocks(&mut column.content, state)?; - } - } - } - DelimitedBlockType::DelimitedComment(_) - | DelimitedBlockType::DelimitedListing(_) - | DelimitedBlockType::DelimitedLiteral(_) - | DelimitedBlockType::DelimitedPass(_) - | DelimitedBlockType::DelimitedVerse(_) - | DelimitedBlockType::DelimitedStem(_) => {} - } - Ok(()) + block: &mut Block<'a>, + state: &mut ParserState<'a>, + ) -> Result<(bool, crate::grammar::SourceAssignments<'a>), Error> { + let mut context = super::MacroExecutionContext::default(); + let keep = self.block(block, state, &mut context)?; + Ok((keep, context.assignments)) } } diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index 551fe4525..c5015b94e 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -36,7 +36,11 @@ struct Counter { } impl BlockMacroProcessor for Counter { - fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result { + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { self.total.fetch_add(1, Ordering::Relaxed); self.calls.set(self.calls.get() + 1); match invocation.target.as_ref() { @@ -109,7 +113,7 @@ fn extensions_fresh_local_processors_live_with_their_result() -> TestResult { } #[test] -fn extensions_no_callbacks_for_rejected_document() -> TestResult { +fn extensions_committed_callbacks_survive_later_recognition_errors() -> TestResult { let total = Arc::new(AtomicUsize::new(0)); let drops = Arc::new(AtomicUsize::new(0)); let mut builder = Registry::builder(); @@ -119,7 +123,7 @@ fn extensions_no_callbacks_for_rejected_document() -> TestResult { .parse("count::one[]\n\ncount::[]", &Options::default()) .expect_err("missing target"); assert!(matches!(error, Error::Extension(..))); - assert_eq!(total.load(Ordering::Relaxed), 0); + assert_eq!(total.load(Ordering::Relaxed), 1); assert_eq!(drops.load(Ordering::Relaxed), 1); Ok(()) } @@ -226,7 +230,11 @@ fn extensions_registry_rejects_ambiguous_names_and_replaces_explicitly() -> Test struct Never; impl BlockMacroProcessor for Never { - fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + fn process( + &mut self, + _: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { panic!("unexpected processor invocation") } } @@ -237,6 +245,9 @@ fn extensions_empty_or_unused_registry_preserves_document_and_warnings() -> Test for input in [ include_str!("../../../fixtures/tests/xref_nested_sections.adoc"), "= Document\n\n== Parent\n\n==== Skipped\n\n[subs=unknown]\nText", + "= Document\n\n== Parent\n\n==== Skipped\n\n[subs=unknown]\nText\n\nifdef::missing[]\nrecord::inactive[]\nendif::[]", + "[format=unknown]\n|===\n|Cell\n\nifdef::missing[]\nrecord::inactive[]\nendif::[]\n|===", + "[format=unknown,cols=a]\n|===\n|[subs=unknown]\nText\n\nifdef::missing[]\nrecord::inactive[]\nendif::[]\n|===", ] { let ordinary = acdc_parser::parse(input, &options)?; for registry in [Registry::default(), support::registry()] { @@ -408,3 +419,363 @@ fn extensions_output_captions_use_source_position_attributes() -> TestResult { ); Ok(()) } + +#[test] +fn extensions_callback_attributes_precede_conditionals_and_nested_includes() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write( + directory.path().join("outer.adoc"), + "configure::enabled[yes]\nifdef::enabled[]\ninclude::{enabled}.adoc[]\nendif::[]\nconfigure::enabled[unset=true]\nifndef::enabled[]\nrecord::after[]\nendif::[]", + )?; + std::fs::write( + directory.path().join("yes.adoc"), + "record::{enabled}[]\n\ndefer::included[]", + )?; + let root = directory.path().join("root.adoc"); + let input = "include::outer.adoc[]\n\nifdef::enabled[]\nrecord::inactive[]\nendif::[]\nunknown::ordinary[]"; + std::fs::write(&root, input)?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Unsafe) + .with_base_dir(directory.path()) + .build()?; + for parsed in [ + support::registry().parse(input, &options)?, + support::registry().parse_file(&root, &options)?, + ] { + let document = serde_json::to_string(parsed.parsed.document_storage())?; + assert!(document.contains("yes"), "{document}"); + assert!(document.contains("after"), "{document}"); + assert!(!document.contains("inactive"), "{document}"); + assert!(document.contains("unknown::ordinary[]"), "{document}"); + let request = &parsed.deferred_blocks()[0]; + assert_eq!( + request.invocation.document_attributes.text("enabled"), + Some("yes") + ); + assert_eq!(request.invocation.location.location.start.line, 3); + assert!( + request + .invocation + .location + .file + .as_ref() + .is_some_and(|path| path.ends_with("yes.adoc")) + ); + assert_eq!(parsed.deferred_blocks().len(), 1); + assert_eq!( + parsed + .parsed + .conditionals() + .map(crate::ConditionalEvaluation::is_active) + .collect::>(), + [true, true, false] + ); + } + } + Ok(()) +} + +#[test] +fn extensions_callback_assignments_obey_locks_and_preserve_body_events() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_attribute("locked", "caller") + .with_default_attribute("soft", "caller") + .build()?; + let parsed = support::registry().parse("configure::locked[ignored]\nconfigure::soft[accepted]\nconfigure::empty[\"\"]\nrecord::{locked}[{soft},,\"\"]\nconfigure::soft[unset=true]\nifndef::soft[]\nrecord::unset[]\nendif::[]", &options)?; + let document = parsed.parsed.document_storage(); + let events: Vec<_> = document + .blocks + .iter() + .filter_map(|block| { + if let Block::DocumentAttribute(event) = block { + Some(event.name.as_ref()) + } else { + None + } + }) + .collect(); + assert_eq!(events, ["soft", "empty", "soft"]); + let paragraphs: Vec<_> = document + .blocks + .iter() + .filter(|block| matches!(block, Block::Paragraph(_))) + .map(paragraph_text) + .collect(); + let record: serde_json::Value = serde_json::from_str(¶graphs[0])?; + assert_eq!(record["target"], "caller"); + assert_eq!( + record["positional"], + serde_json::json!(["accepted", null, ""]) + ); + assert_eq!(record["attributes"]["third"], ""); + assert!(paragraphs[1].contains("unset")); + } + Ok(()) +} + +#[test] +fn extensions_parallel_documents_use_independent_non_send_handlers() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let registry = builder.build(); + std::thread::scope(|scope| { + let handles: Vec<_> = (0..4) + .map(|_| { + let registry = registry.clone(); + scope.spawn(move || { + let result = registry + .parse("count::one[]\n\ncount::two[]", &Options::default()) + .expect("parse"); + assert_eq!( + paragraph_text(&result.parsed.document_storage().blocks[0]), + "1" + ); + assert_eq!( + paragraph_text(&result.parsed.document_storage().blocks[1]), + "2" + ); + }) + }) + .collect(); + for handle in handles { + handle.join().expect("worker"); + } + }); + assert_eq!(total.load(Ordering::Relaxed), 8); + assert_eq!(drops.load(Ordering::Relaxed), 4); + Ok(()) +} + +#[test] +fn extensions_macro_errors_escape_attachment_recovery_without_later_reads() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + for (prefix, suffix) in [ + ("", ""), + ("* Item\n+\n", ""), + ("Term::\n+\n", ""), + ("====\n", "====\n"), + ("[cols=a]\n|===\na|\n", "|===\n"), + ] { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let source = format!( + "{prefix}count::fail[]\n\ninclude::missing.adoc[]\ncount::later[]\n{suffix}" + ); + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let error = builder + .build() + .parse(&source, &options) + .expect_err("callback error"); + assert!( + matches!(error, Error::Extension(_, ref message) if message == "deliberate failure"), + "{error:?}" + ); + assert_eq!(total.load(Ordering::Relaxed), 1, "{prefix}"); + } + } + Ok(()) +} + +#[test] +fn extensions_compound_callbacks_precede_following_conditionals() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let parsed = support::registry().parse("====\nconfigure::enabled[yes]\n\nifdef::enabled[]\nrecord::selected[]\nendif::[]\n====", &options)?; + let document = serde_json::to_string(parsed.parsed.document_storage())?; + assert!(document.contains("selected"), "{document}"); + } + Ok(()) +} + +#[test] +fn extensions_table_callbacks_precede_cell_directives_and_keep_local_attributes() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write( + directory.path().join("cell.adoc"), + "record::{local}[]\n\ndefer::inside[]", + )?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_base_dir(directory.path()) + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let source = "[cols=2*a]\n|===\na|configure::local[cell]\n\nifdef::local[]\ninclude::{local}.adoc[]\nendif::[]\na|\nifndef::local[]\nrecord::sibling[]\nendif::[]\n|===\n\nifndef::local[]\nrecord::outer[]\nendif::[]"; + let result = support::registry().parse(source, &options)?; + let requests = result.deferred_blocks(); + assert_eq!(requests.len(), 1); + assert_eq!( + requests[0].invocation.document_attributes.text("local"), + Some("cell") + ); + assert!( + requests[0] + .invocation + .location + .file + .as_ref() + .is_some_and(|path| path.ends_with("cell.adoc")) + ); + assert_eq!(requests[0].invocation.location.location.start.line, 3); + let document = serde_json::to_string(result.parsed.document_storage())?; + assert!(document.contains("sibling"), "{document}"); + assert!(document.contains("outer"), "{document}"); + assert_eq!( + result + .parsed + .conditionals() + .map(crate::ConditionalEvaluation::is_active) + .collect::>(), + [true, true, true] + ); + } + Ok(()) +} + +#[test] +fn extensions_buffered_cells_do_not_change_outer_reader_attributes() -> TestResult { + let directory = tempfile::tempdir()?; + let table = "[cols=a]\n|===\n|configure::local[cell]\n|==="; + std::fs::write(directory.path().join("table.adoc"), table)?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Unsafe) + .with_base_dir(directory.path()) + .build()?; + for prefix in [table, "include::table.adoc[]"] { + let source = format!( + "{prefix}\n\nifdef::local[]\nrecord::leaked[]\nendif::[]\nifndef::local[]\nrecord::outer[]\nendif::[]" + ); + let result = support::registry().parse(&source, &options)?; + let document = serde_json::to_string(result.parsed.document_storage())?; + assert!(!document.contains("leaked"), "{document}"); + assert!(document.contains("outer"), "{document}"); + } + } + Ok(()) +} + +#[test] +fn extensions_streaming_table_limits_fail_before_callbacks() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let source = "[cols=a]\n|===\n18446744073709551615*a|count::one[]\nifdef::never[]\nignored\nendif::[]\n|==="; + let error = builder + .build() + .parse(source, &Options::default()) + .expect_err("oversized table specifier"); + assert!(matches!(error, Error::Parse(..)), "{error:?}"); + assert_eq!(total.load(Ordering::Relaxed), 0); + Ok(()) +} + +#[test] +fn extensions_streamed_incomplete_rows_fail_after_committed_callbacks() -> TestResult { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let error = builder + .build() + .parse( + "[cols=2*a]\n|===\na|count::one[]\nifdef::never[]\nignored\nendif::[]\n|===", + &Options::default(), + ) + .expect_err("committed row cannot disappear through recovery"); + assert!( + matches!(error, Error::Extension(_, ref message) if message.contains("discarded a cell")), + "{error:?}" + ); + assert_eq!(total.load(Ordering::Relaxed), 1); + Ok(()) +} + +#[test] +fn extensions_duplicated_streamed_cells_keep_distinct_deferred_requests() -> TestResult { + let result = support::registry().parse( + "[cols=2*a]\n|===\n2*a|defer::pending[]\nifdef::never[]\nignored\nendif::[]\n|===", + &Options::default(), + )?; + let requests = result.deferred_blocks(); + assert_eq!(requests.len(), 2); + assert_ne!(requests[0].placeholder, requests[1].placeholder); + assert_ne!(requests[0].target(), requests[1].target()); + for request in requests { + assert!(result.query().get(request.target()).is_some()); + } + Ok(()) +} + +#[test] +fn extensions_table_formats_preserve_callback_order() -> TestResult { + for source in [ + "[format=csv,cols=2*a]\n|===\ncount::one[],count::two[]\nifdef::never[]\nignored\nendif::[]\n|===", + "[cols=a,options=noheader]\n|===\n|count::one[]\n\n|count::two[]\nifdef::never[]\nignored\nendif::[]\n|===", + ] { + let total = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let mut builder = Registry::builder(); + builder.register(counter_macro(&total, &drops))?; + let result = builder.build().parse(source, &Options::default())?; + assert_eq!(total.load(Ordering::Relaxed), 2); + let serialized = serde_json::to_string(result.parsed.document_storage())?; + assert!( + serialized + .find("\"value\":\"1\"") + .ok_or("first callback output")? + < serialized + .find("\"value\":\"2\"") + .ok_or("second callback output")? + ); + } + Ok(()) +} + +#[test] +fn extensions_streamed_table_include_errors_escape_list_recovery() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).with_safe_mode(SafeMode::Unsafe) + .with_include_loader(crate::IncludeLoader::custom(|_: &crate::IncludeSourceTarget| -> Result { + Err(crate::IncludeSourceError::new(crate::IncludeSourceErrorKind::Fatal, "deliberate source failure")) + })).build()?; + let error = support::registry().parse("* Item\n+\n[cols=a]\n|===\n|configure::enabled[yes]\n\nifdef::enabled[]\ninclude::failure.adoc[]\nendif::[]\n|===\n\nrecord::later[]", &options).expect_err("fatal include error"); + assert!( + error.to_string().contains("deliberate source failure"), + "{error:?}" + ); + } + Ok(()) +} + +#[test] +fn extensions_streamed_cell_arguments_use_table_escape_rules() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = support::registry().parse("[cols=a]\n|===\n|record::target[first=\"a\\|b\"]\n\nifdef::never[]\nignored\nendif::[]\n|===", &options)?; + let document = result.parsed.document_storage(); + let Block::DelimitedBlock(table) = &document.blocks[0] else { + panic!("table") + }; + let crate::DelimitedBlockType::DelimitedTable(table) = &table.inner else { + panic!("table") + }; + let output: serde_json::Value = + serde_json::from_str(¶graph_text(&table.rows[0].columns[0].content[0]))?; + assert_eq!(output["attributes"]["first"], "a|b", "{mode:?}"); + } + Ok(()) +} diff --git a/acdc-parser/src/extensions/tests/support.rs b/acdc-parser/src/extensions/tests/support.rs index 84fcbdffc..f684a6867 100644 --- a/acdc-parser/src/extensions/tests/support.rs +++ b/acdc-parser/src/extensions/tests/support.rs @@ -11,7 +11,11 @@ struct Record { } impl BlockMacroProcessor for Record { - fn process(&mut self, invocation: &MacroInvocation<'_>) -> Result { + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { self.calls += 1; let text = serde_json::json!({ "call": self.calls, @@ -27,7 +31,11 @@ impl BlockMacroProcessor for Record { pub(super) struct Defer; impl BlockMacroProcessor for Defer { - fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + fn process( + &mut self, + _: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { Ok(BlockMacroOutput::Deferred) } } @@ -46,5 +54,35 @@ pub(super) fn registry() -> Registry { builder .register(BlockMacro::new("defer", || Defer)) .expect("valid fixture macro"); + builder + .register(BlockMacro::new("configure", || configure).with_positional_attributes(["value"])) + .expect("valid fixture macro"); builder.build() } + +pub(super) fn configure( + invocation: &MacroInvocation<'_>, + context: &mut acdc_parser::extensions::MacroExecutionContext, +) -> Result { + if invocation.target.is_empty() { + return Err("configure requires an attribute name".into()); + } + let name = invocation.target.to_string(); + if invocation.attributes.get("unset").is_some() { + context.unset_attribute(name); + } else { + let value = invocation + .attributes + .get("value") + .and_then(|value| { + if let acdc_parser::AttributeValue::String(text) = value { + Some(text.as_ref()) + } else { + None + } + }) + .unwrap_or(""); + context.set_attribute(name, value.to_owned()); + } + Ok(BlockMacroOutput::None) +} diff --git a/acdc-parser/src/grammar/attributes.rs b/acdc-parser/src/grammar/attributes.rs index d571910c1..9f3b3690b 100644 --- a/acdc-parser/src/grammar/attributes.rs +++ b/acdc-parser/src/grammar/attributes.rs @@ -116,6 +116,10 @@ pub(crate) struct ScannedAttribute { } impl ScannedAttribute { + pub(crate) fn is_empty_slot(&self) -> bool { + self.quote == AttributeQuote::Unquoted && self.value.is_empty() + } + pub(crate) fn is_unset(&self) -> bool { self.quote == AttributeQuote::Unquoted && self.value == "None" } diff --git a/acdc-parser/src/grammar/document.rs b/acdc-parser/src/grammar/document.rs index 002df1401..1086d60df 100644 --- a/acdc-parser/src/grammar/document.rs +++ b/acdc-parser/src/grammar/document.rs @@ -25,7 +25,7 @@ mod verbatim; pub(crate) use coordinator::document; pub(crate) use peg::document_parser; -pub(crate) use source::{SourceHandler, document_from_source}; +pub(crate) use source::{Assignments as SourceAssignments, SourceHandler, document_from_source}; type RecognitionError = ::peg::error::ParseError<::peg::str::LineCol>; diff --git a/acdc-parser/src/grammar/document/construction/tests.rs b/acdc-parser/src/grammar/document/construction/tests.rs index 571367b2a..e9bf75bdb 100644 --- a/acdc-parser/src/grammar/document/construction/tests.rs +++ b/acdc-parser/src/grammar/document/construction/tests.rs @@ -230,6 +230,7 @@ impl crate::extensions::BlockMacroProcessor for UnusedProcessor { fn process( &mut self, _: &crate::extensions::MacroInvocation<'_>, + _: &mut crate::extensions::MacroExecutionContext, ) -> Result { Err("internal boundary tests do not execute public processors".into()) } diff --git a/acdc-parser/src/grammar/mod.rs b/acdc-parser/src/grammar/mod.rs index c7675f11e..81577f970 100644 --- a/acdc-parser/src/grammar/mod.rs +++ b/acdc-parser/src/grammar/mod.rs @@ -31,7 +31,8 @@ pub(crate) use attributes::{ BlockAttributeMode, block_attribute_line, block_attribute_style, style_overrides_block_form, }; pub(crate) use document::{ - SourceHandler, document as parse_document, document_from_source, document_parser, + SourceAssignments, SourceHandler, document as parse_document, document_from_source, + document_parser, }; pub(crate) use inline_preprocessor::{ InlinePreprocessorParserState, ProcessedContent, inline_preprocessing, diff --git a/acdc-parser/src/lib.rs b/acdc-parser/src/lib.rs index aa022f1f4..bdad8f3a6 100644 --- a/acdc-parser/src/lib.rs +++ b/acdc-parser/src/lib.rs @@ -384,7 +384,7 @@ pub fn parse_from_reader( let _span = tracing::info_span!("preprocess").entered(); Preprocessor::process_reader(reader, &options, Rc::clone(&warnings_handle))? }; - parse_input(result, options, None, warnings_handle, None) + parse_input(result, options, None, warnings_handle) } /// Parse `AsciiDoc` content from a string. @@ -450,13 +450,21 @@ fn parse_with_source_handler( .prepare_for_parse(document_attribute::InputKind::String); let warnings_handle: Rc> = Rc::default(); if let Some(handler) = handler { - return parse_ordered_source(input, options, None, warnings_handle, session, handler); + return parse_ordered_source(input, options, None, warnings_handle, handler); + } + if let Some(session) = session + && options + .extensions + .as_ref() + .is_some_and(|registry| registry.may_execute(input)) + { + return parse_ordered_source(input, options, None, warnings_handle, session); } let result = { let _span = tracing::info_span!("preprocess").entered(); Preprocessor::process(input, &options, Rc::clone(&warnings_handle))? }; - parse_input(result, options, None, warnings_handle, session) + parse_input(result, options, None, warnings_handle) } /// Parse `AsciiDoc` content from a file. @@ -503,11 +511,19 @@ fn parse_file_with_session( let path = file_path.to_path_buf(); let raw = preprocessor::read_and_decode_file(file_path, None)?; let warnings_handle: Rc> = Rc::default(); + if let Some(session) = session + && options + .extensions + .as_ref() + .is_some_and(|registry| registry.may_execute(&raw)) + { + return parse_ordered_source(&raw, options, Some(path), warnings_handle, session); + } let result = { let _span = tracing::info_span!("preprocess").entered(); Preprocessor::process_with_file(&raw, file_path, &options, Rc::clone(&warnings_handle))? }; - parse_input(result, options, Some(path), warnings_handle, session) + parse_input(result, options, Some(path), warnings_handle) } /// Helper to convert a PEG parse error to our `SourceLocation` type, @@ -544,7 +560,6 @@ fn parse_input( mut options: Options<'_>, file_path: Option, warnings_handle: Rc>, - session: Option<&mut extensions::Session>, ) -> Result { if let Some(front_matter) = result.front_matter { options @@ -593,7 +608,7 @@ fn parse_input( state.add_warning(Warning::new(WarningKind::DeprecatedToc2Attribute, None)); } let result = match grammar::parse_document(&owner.source, &mut state) { - Ok(Ok(doc)) => finish_parsed_document(doc, &mut state, session, &owner.source), + Ok(Ok(doc)) => finish_parsed_document(doc, &mut state, &owner.source), Ok(Err(e)) => Err(e), Err(error) => { tracing::error!("error parsing document content"); @@ -611,16 +626,9 @@ fn parse_input( fn finish_parsed_document<'a>( mut doc: Document<'a>, state: &mut grammar::ParserState<'a>, - session: Option<&mut extensions::Session>, source: &'a str, ) -> Result, Error> { grammar::reference_text::finish_document(state, &mut doc)?; - if let Some(session) = session - && session.process(&mut doc, state)? - { - doc.renumber_captions(); - extensions::finalization::repair_macros(&mut doc)?; - } grammar::remap_document_to_source(&mut doc, &state.source_ranges, source, &state.line_map); Ok(doc) } @@ -630,7 +638,6 @@ fn parse_ordered_source( options: Options<'_>, file_path: Option, warnings_handle: Rc>, - session: Option<&mut extensions::Session>, handler: &mut dyn grammar::SourceHandler, ) -> Result { let owner = @@ -668,7 +675,7 @@ fn parse_ordered_source( ) .and_then(|document| { *source_files = parsed::SourceFiles::new(file_path, &state.source_ranges); - finish_parsed_document(document, &mut state, session, owner.preprocessed_source()) + finish_parsed_document(document, &mut state, owner.preprocessed_source()) }); state.emit_warnings(); result diff --git a/acdc-parser/src/source_tests.rs b/acdc-parser/src/source_tests.rs index 487c35ac8..20f3481d1 100644 --- a/acdc-parser/src/source_tests.rs +++ b/acdc-parser/src/source_tests.rs @@ -238,15 +238,9 @@ fn source_driver_preserves_selected_include_origins_and_nested_base_directory() &prepared, std::rc::Rc::clone(&warnings), )?; - let expected = crate::parse_input(preprocessed, prepared.clone(), None, warnings, None)?; - let actual = crate::parse_ordered_source( - input, - prepared, - None, - std::rc::Rc::default(), - None, - &mut (), - )?; + let expected = crate::parse_input(preprocessed, prepared.clone(), None, warnings)?; + let actual = + crate::parse_ordered_source(input, prepared, None, std::rc::Rc::default(), &mut ())?; assert_eq!(actual.preprocessed_source(), expected.preprocessed_source()); assert_eq!(actual.document_storage(), expected.document_storage()); assert_eq!(actual.warnings(), expected.warnings()); @@ -305,15 +299,9 @@ pub(crate) fn assert_equivalent(input: &str, mode: CompatibilityMode) -> TestRes &prepared, std::rc::Rc::clone(&warnings), )?; - let expected = crate::parse_input(preprocessed, prepared.clone(), None, warnings, None)?; - let actual = crate::parse_ordered_source( - &input, - prepared, - None, - std::rc::Rc::default(), - None, - &mut (), - )?; + let expected = crate::parse_input(preprocessed, prepared.clone(), None, warnings)?; + let actual = + crate::parse_ordered_source(&input, prepared, None, std::rc::Rc::default(), &mut ())?; assert_eq!( actual.preprocessed_source(), expected.preprocessed_source(), @@ -624,8 +612,12 @@ fn source_driver_handler_failure_prevents_later_include_reads( struct Never; impl BlockMacroProcessor for Never { - fn process(&mut self, _: &MacroInvocation<'_>) -> Result { - Err("public callbacks must retain their post-acceptance boundary".into()) + fn process( + &mut self, + _: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { + Err("registry processors must not run through the private observer seam".into()) } } diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index 988d89e21..e0ed73168 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -11,7 +11,11 @@ type TestResult = Result<(), Box>; struct Defer; impl BlockMacroProcessor for Defer { - fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + fn process( + &mut self, + _: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { Ok(BlockMacroOutput::Deferred) } } @@ -219,3 +223,68 @@ fn extensions_removal_preserves_cell_footnote_owners_and_prepared_numbers() -> T } Ok(()) } + +#[test] +fn extensions_preserve_main_recovery_and_header_semantics() -> TestResult { + let marker = ".".repeat(256); + let sources = [ + ":toc:\n\n= Title\n\nBody.".to_owned(), + "Before.\n\n|===\n|Cell\n|====\n\nLater cell.\n|===\n\nAfter.".to_owned(), + "Before.\n\n|===\n|Cell\n|====\n\nLater cell.".to_owned(), + "Before.\n\n[cols=4294967296a]\n|===\n|Cell\n|===\n\nAfter.".to_owned(), + format!("Before.\n\n.Kept title\n[id=overflow]\n{marker} Literal item.\n\nAfter."), + "Before.\n\nifeval::[1 = 1]\nHidden.\nendif::[]\n\nAfter.".to_owned(), + ]; + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("unused", || Defer))?; + let registry = builder.build(); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for source in &sources { + // Force the registered-name reader path without executing a callback. + let source = format!("{source}\n\n\\unused::[]"); + let native = acdc_parser::parse(&source, &options)?; + let extended = registry.parse(&source, &options)?.finish()?; + assert_eq!( + serde_json::to_value(extended.document())?, + serde_json::to_value(native.document())?, + "{mode:?}: {source}" + ); + assert_eq!(extended.warnings(), native.warnings(), "{mode:?}: {source}"); + } + } + Ok(()) +} + +#[test] +fn extensions_preserve_scoped_include_assignments_and_origins() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write( + directory.path().join("outer.adoc"), + "== Outer\n\ninclude::inner.adoc[leveloffset=+1]\n\nOuter after.", + )?; + std::fs::write( + directory.path().join("inner.adoc"), + "== Inner\n\nInner body.", + )?; + let source = "= Title\n:leveloffset: +1\n\ninclude::outer.adoc[leveloffset=+1]\n\n== After\n\nFinal body."; + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("unused", || Defer))?; + let registry = builder.build(); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_base_dir(directory.path()) + .with_safe_mode(acdc_parser::SafeMode::Unsafe) + .with_compatibility_mode(mode) + .build()?; + let native = acdc_parser::parse(source, &options)?; + let extended = registry.parse(source, &options)?.finish()?; + assert_eq!( + serde_json::to_value(extended.document())?, + serde_json::to_value(native.document())?, + "{mode:?}" + ); + assert_eq!(extended.warnings(), native.warnings(), "{mode:?}"); + } + Ok(()) +} diff --git a/acdc-parser/tests/support/fixtures.rs b/acdc-parser/tests/support/fixtures.rs index a61c7318b..fdd816331 100644 --- a/acdc-parser/tests/support/fixtures.rs +++ b/acdc-parser/tests/support/fixtures.rs @@ -8,6 +8,9 @@ use std::{ use acdc_parser::{CompatibilityMode, Options, SafeMode, Warning, parse_file}; use serde_json::{Value, json}; +#[path = "../../src/extensions/tests/support.rs"] +mod extensions; + pub(crate) type Error = Box; /// Selects an expectation filename, not a production parser policy. @@ -205,7 +208,18 @@ impl Case { .with_compatibility_mode(mode) .with_safe_mode(SafeMode::Unsafe) .build()?; - match parse_file(&self.source, &options) { + let parsed = if self + .source + .parent() + .is_some_and(|parent| parent.ends_with("extensions")) + { + extensions::registry() + .parse_file(&self.source, &options) + .and_then(acdc_parser::extensions::ExtensionParseResult::finish) + } else { + parse_file(&self.source, &options) + }; + match parsed { Ok(parsed) => Ok(Observation { kind: OutcomeKind::Json, output: serde_json::to_string_pretty(&parsed.document())?, diff --git a/converters/html/tests/typed_document_entrypoints.rs b/converters/html/tests/typed_document_entrypoints.rs index 0b7bba31e..9165d56b3 100644 --- a/converters/html/tests/typed_document_entrypoints.rs +++ b/converters/html/tests/typed_document_entrypoints.rs @@ -59,7 +59,11 @@ fn parsed_and_constructed_documents_share_conversion_entrypoints() struct ListRequest; impl BlockMacroProcessor for ListRequest { - fn process(&mut self, _: &MacroInvocation<'_>) -> Result { + fn process( + &mut self, + _: &MacroInvocation<'_>, + _: &mut acdc_parser::extensions::MacroExecutionContext, + ) -> Result { Ok(BlockMacroOutput::Deferred) } } From 3f5c51ab9d82a3d569063ce0f02c63e79cdb4e32 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 14 Nov 2026 20:45:28 +0100 Subject: [PATCH 13/55] feat(parser): retain title source context for extension queries Preserve raw title input, substitutions, source locations, and source-position attributes before inline interpretation. Expose them through BlockView::title_source() and retain the context across placeholder replacement without changing native serialization. Refs SC-537. --- acdc-parser/CHANGELOG.md | 6 + acdc-parser/README.adoc | 13 + acdc-parser/README.md | 13 + .../schemas/asg/support-inventory.json | 8 +- acdc-parser/src/extensions/mod.rs | 7 + acdc-parser/src/extensions/query.rs | 23 ++ acdc-parser/src/extensions/registry.rs | 15 +- acdc-parser/src/extensions/tests/mod.rs | 2 + .../src/extensions/tests/title_sources.rs | 266 ++++++++++++++++++ acdc-parser/src/extensions/title.rs | 39 +++ acdc-parser/src/grammar/document/metadata.rs | 59 +++- acdc-parser/src/grammar/document/peg.rs | 17 +- acdc-parser/src/grammar/inline_processing.rs | 5 +- acdc-parser/src/model/substitution.rs | 19 ++ acdc-parser/src/model/title.rs | 43 ++- 15 files changed, 508 insertions(+), 27 deletions(-) create mode 100644 acdc-parser/src/extensions/tests/title_sources.rs create mode 100644 acdc-parser/src/extensions/title.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 06d6926bc..21631886d 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -200,6 +200,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Empty registries and unused registrations preserve ordinary diagnostic order. Edits repair references, TOC and scoped footnotes while preserving surviving section and caption numbers. + Extension queries also expose raw title source, inline substitutions, original + locations, and source-position document attributes through + `BlockView::title_source()`, including attribute titles and titles that expand + to empty content. Query again after edits or ID assignment; surviving target + handles retain their identities, and removed handles remain invalid even when + another block reuses their output ID. Call `ExtensionParseResult::finish()` before conversion or checked ASG export; unresolved requests return a located error. Block-macro callbacks now run once as their blocks commit. `MacroExecutionContext::set_attribute` and diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index d4624e23e..27b0960b5 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2074,11 +2074,24 @@ A table layout that discards a cell after its callback ran returns a located extension error, since those effects cannot be rolled back. Use `query()` to inspect typed block, content, attribute, and caption views. +Traversal visits parents before children, including list attachments, compound +blocks, and AsciiDoc cell documents. `containing_section()` returns the nearest +section in the same document scope; a cell starts a new scope. +`BlockView::title_source()` exposes raw title input after document preprocessing, +inline substitution order, original location, and attributes captured before +title interpretation. It preserves titles that expand to empty content and the +quote-dependent policy of attribute titles. `caption()` reads the host's resolved +prefix and ordinal. Ordinary parser entry points retain no extension title snapshots. +Queries and borrowed title views end before an edit or ID assignment; query again +afterward to observe the repaired tree. Copied handle selections remain snapshots. Document-local `TargetId` handles survive insertions and placeholder replacement; removed handles cannot bind to another block. The scoped `DocumentEditor` builds literal paragraphs and lists, assigns IDs, replaces requests, and removes sections. Edits repair catalogs and scoped footnotes while preserving surviving section and caption numbers. Generated text is literal and is not reparsed. +ID assignment preserves authored IDs, avoids registered targets and unresolved +reference names, and reuses assigned IDs. Identical conversions produce the same +IDs regardless of request order; IDs need not remain stable across document edits. Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used for conversion or serialization. It rejects unresolved deferred requests at their diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 6816fc553..03792f7e4 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1718,11 +1718,24 @@ A table layout that discards a cell after its callback ran returns a located extension error, since those effects cannot be rolled back. Use `query()` to inspect typed block, content, attribute, and caption views. +Traversal visits parents before children, including list attachments, compound +blocks, and AsciiDoc cell documents. `containing_section()` returns the nearest +section in the same document scope; a cell starts a new scope. +`BlockView::title_source()` exposes raw title input after document preprocessing, +inline substitution order, original location, and attributes captured before +title interpretation. It preserves titles that expand to empty content and the +quote-dependent policy of attribute titles. `caption()` reads the host's resolved +prefix and ordinal. Ordinary parser entry points retain no extension title snapshots. +Queries and borrowed title views end before an edit or ID assignment; query again +afterward to observe the repaired tree. Copied handle selections remain snapshots. Document-local `TargetId` handles survive insertions and placeholder replacement; removed handles cannot bind to another block. The scoped `DocumentEditor` builds literal paragraphs and lists, assigns IDs, replaces requests, and removes sections. Edits repair catalogs and scoped footnotes while preserving surviving section and caption numbers. Generated text is literal and is not reparsed. +ID assignment preserves authored IDs, avoids registered targets and unresolved +reference names, and reuses assigned IDs. Identical conversions produce the same +IDs regardless of request order; IDs need not remain stable across document edits. Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used for conversion or serialization. It rejects unresolved deferred requests at their diff --git a/acdc-parser/schemas/asg/support-inventory.json b/acdc-parser/schemas/asg/support-inventory.json index c4122bb88..dbf951a6f 100644 --- a/acdc-parser/schemas/asg/support-inventory.json +++ b/acdc-parser/schemas/asg/support-inventory.json @@ -5683,7 +5683,8 @@ "shape": { "kind": "struct", "fields": [ - "0" + "content", + "source" ], "variants": {} }, @@ -5692,9 +5693,12 @@ "upstream": "#/$defs/inlines" }, "properties": { - "0": { + "content": { "policy": "no-direct-field-mapping-is-established-for", "upstream": "#/$defs/inlines" + }, + "source": { + "policy": "source-state" } }, "strict_export_group": "core" diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 15a7668c2..a4bae00db 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -77,6 +77,11 @@ //! Titles and captions carry their parsed source-position values. Assigning an ID //! preserves existing IDs and updates the reference catalog; it does not change //! block order or rerun processors. Deferred requests expose the same target handles. +//! [`BlockView::title_source`] retains raw title input, its inline substitution +//! order, original location, and document attributes before title interpretation. +//! This includes titles that expand to empty content, attribute titles, sections, +//! and discrete headings. Constructed titles have no authored source snapshot. +//! Ordinary parser entry points do not retain these extension snapshots. //! //! Tree processors run after block macros and can replace pending requests with //! ordinary content. Builders accept literal text; markup and substitutions are @@ -129,6 +134,7 @@ mod recognition; mod registry; mod session; mod target; +mod title; mod traversal; pub(crate) use traversal::{TablePart, compound_body_mut, ordinary_list_items_mut, table_cell_mut}; mod tree_processor; @@ -144,6 +150,7 @@ pub use query::{BlockContext, BlockView, DocumentQuery}; pub use registry::{RegistrationError, Registry, RegistryBuilder}; pub use session::ExtensionParseResult; pub use target::{TargetError, TargetId}; +pub use title::TitleSource; pub use tree_processor::{TreeProcessor, TreeProcessorRegistration}; pub(crate) use recognition::recognize; diff --git a/acdc-parser/src/extensions/query.rs b/acdc-parser/src/extensions/query.rs index 052980aca..83afe87a0 100644 --- a/acdc-parser/src/extensions/query.rs +++ b/acdc-parser/src/extensions/query.rs @@ -340,6 +340,22 @@ impl TargetIndex { /// Traversal includes list attachments, compound blocks, and `AsciiDoc` table-cell documents. /// List items and table cells are containers, rather than separate block targets. /// The document header is outside this block query. +/// +/// Queries and their borrowed views end before any mutable operation. Query again +/// after an edit or ID assignment to observe repaired semantics; only target +/// handles carry identity across that boundary. A copied selection of handles is +/// a snapshot and is never selected again automatically. +/// +/// ```compile_fail,E0502 +/// use acdc_parser::{Error, extensions::{BlockBuilder, DocumentEditor, TargetId}}; +/// fn edit(editor: &mut DocumentEditor<'_>, target: &TargetId) -> Result<(), Error> { +/// let query = editor.query(); +/// let old = query.get(target).unwrap(); +/// editor.insert_before(target, BlockBuilder::paragraph("New"))?; +/// println!("{:?}", old.context()); +/// Ok(()) +/// } +/// ``` pub struct DocumentQuery<'doc> { pub(super) parsed: &'doc ParseResult, pub(super) index: &'doc TargetIndex, @@ -414,6 +430,13 @@ impl<'doc> BlockView<'doc> { self.block().title() } + /// Raw title input, substitutions, source location, and document attributes. + /// Constructed titles without authored input return `None`. + #[must_use] + pub fn title_source(&self) -> Option<&'doc super::TitleSource<'doc>> { + self.block.title()?.source() + } + #[must_use] pub fn attributes(&self) -> Option> { self.block().attributes() diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 92a6f800f..2f1fea734 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -173,13 +173,14 @@ impl Registry { parse: impl FnOnce(&Options<'_>, Option<&mut Session>) -> Result, ) -> Result { let mut session = self.session(); - let parsed = if self.0.macros.is_empty() { - parse(options, None)? - } else { - let mut options = options.clone(); - options.extensions = Some(self.clone()); - parse(&options, Some(&mut session))? - }; + let mut options = options.clone(); + // Retain query input even when there are no registered macros. The + // ordinary recognizers and inactive source-reader path remain shared. + options.extensions = Some(self.clone()); + let parsed = parse( + &options, + (!self.0.macros.is_empty()).then_some(&mut session), + )?; let mut result = ExtensionParseResult::new(parsed, session); if result.session.processed_blocks { result.repair_after_edit()?; diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index c5015b94e..51b674942 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -24,6 +24,8 @@ mod support; #[path = "queries.rs"] mod queries; +mod title_sources; + #[path = "tree_processors.rs"] mod tree_processors; diff --git a/acdc-parser/src/extensions/tests/title_sources.rs b/acdc-parser/src/extensions/tests/title_sources.rs new file mode 100644 index 000000000..d54f1531d --- /dev/null +++ b/acdc-parser/src/extensions/tests/title_sources.rs @@ -0,0 +1,266 @@ +use acdc_parser::{ + CompatibilityMode, DocumentAttributeValue, Options, SafeMode, Substitution, + extensions::{BlockBuilder, BlockContext, BlockView, DocumentEditor, Registry}, +}; + +use super::{TestResult, support}; + +#[test] +fn extensions_title_sources_retain_input_and_pre_substitution_attributes() -> TestResult { + let source = "= Document\n:label: Early\n:empty:\n\n== Section *{label}*\n\n.{counter:sequence} *{label}*\n[subs=none]\nimage::one.svg[]\n\n:label: Late\n\n[title='{label} *attribute*']\nParagraph.\n\n.{empty}\nimage::empty.svg[]\n\n[discrete]\n=== Discrete {label}"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for registry in [Registry::default(), support::registry()] { + let parsed = registry.parse(source, &options)?; + let query = parsed.query(); + let titles = query + .blocks() + .filter_map(|view| view.title_source()) + .collect::>(); + assert_eq!( + titles + .iter() + .map(|title| title.raw_source()) + .collect::>(), + [ + "Section *{label}*", + "{counter:sequence} *{label}*", + "{label} *attribute*", + "{empty}", + "Discrete {label}", + ] + ); + for (title, expected) in titles + .iter() + .zip(["Early", "Early", "Late", "Late", "Late"]) + { + assert_eq!( + title + .attributes() + .get("label") + .and_then(DocumentAttributeValue::as_str), + Some(expected) + ); + assert_ne!(title.substitutions(), []); + let location = &title.source_location().location; + let end = location.absolute_start + title.raw_source().len(); + assert_eq!( + source.get(location.absolute_start..end), + Some(title.raw_source()) + ); + } + // Capturing the source must precede the title's counter side effect. + assert!( + titles + .get(1) + .ok_or("image title")? + .attributes() + .get("sequence") + .is_none() + ); + let first = query.select(BlockContext::Image).next().ok_or("image")?; + let title = first.title().ok_or("parsed title")?; + assert!( + title + .inlines() + .any(|inline| matches!(inline.kind(), crate::ast::InlineKind::Bold(_))) + ); + assert!( + first + .title_source() + .ok_or("source")? + .substitutions() + .contains(&Substitution::Quotes) + ); + let empty = query + .select(BlockContext::Image) + .nth(1) + .ok_or("empty image")?; + assert!(empty.title().is_some_and(crate::ast::ContentRef::is_empty)); + assert_eq!( + empty + .title_source() + .map(crate::extensions::TitleSource::raw_source), + Some("{empty}") + ); + } + } + Ok(()) +} + +#[test] +fn extensions_title_sources_follow_committed_macros_includes_and_cell_scopes() -> TestResult { + let directory = tempfile::tempdir()?; + let included = directory.path().join("title.adoc"); + std::fs::write(&included, ".Included *{label}*\nimage::included.svg[]\n")?; + let source = "= Document\n:label: Header\n\nconfigure::label[Outer]\n\ninclude::title.adoc[]\n\n[cols=a]\n|===\n|configure::cell-label[Cell]\n\n.Cell {cell-label}\nimage::cell.svg[]\n|===\n\n.Outside {label}\nimage::outside.svg[]"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Unsafe) + .with_base_dir(directory.path()) + .build()?; + let parsed = support::registry().parse(source, &options)?; + let query = parsed.query(); + let images = query.select(BlockContext::Image).collect::>(); + assert_eq!(images.len(), 3); + for image in &images { + assert_eq!( + image + .title_source() + .ok_or("title source")? + .attributes() + .get("label") + .and_then(DocumentAttributeValue::as_str), + Some("Outer") + ); + } + assert_eq!( + images + .get(1) + .and_then(BlockView::title_source) + .ok_or("cell")? + .attributes() + .get("cell-label") + .and_then(DocumentAttributeValue::as_str), + Some("Cell") + ); + assert!( + !images + .get(2) + .and_then(BlockView::title_source) + .ok_or("outside")? + .attributes() + .contains("cell-label") + ); + let title = images + .first() + .and_then(BlockView::title_source) + .ok_or("included title")?; + assert_eq!(title.raw_source(), "Included *{label}*"); + assert_eq!(title.source_location().file.as_ref(), Some(&included)); + assert_eq!(title.source_location().location.start.line, 1); + } + Ok(()) +} + +#[test] +fn extensions_attribute_title_sources_record_their_own_substitution_policy() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let parsed = Registry::default().parse( + "= Document\n:label: Early\n\n[title=\"{label} *double*\"]\nParagraph.\n\n[title='{label} *single*']\nParagraph.\n\n[title=]\nParagraph.", + &options, + )?; + let query = parsed.query(); + let sources = query + .blocks() + .filter_map(|view| view.title_source()) + .collect::>(); + assert_eq!(sources.len(), 3); + assert_eq!( + sources.first().ok_or("double")?.raw_source(), + "{label} *double*" + ); + let double = sources.first().ok_or("double")?.substitutions(); + if mode == CompatibilityMode::Draft { + assert_eq!(double, [Substitution::SpecialChars]); + } else { + assert!(double.contains(&Substitution::Quotes)); + } + let single = sources.get(1).ok_or("single")?.substitutions(); + assert!(single.contains(&Substitution::Quotes)); + assert_eq!( + single.contains(&Substitution::Attributes), + mode == CompatibilityMode::Asciidoctor + ); + assert_eq!(sources.get(2).ok_or("empty")?.raw_source(), ""); + } + Ok(()) +} + +#[test] +fn extensions_setext_titles_retain_source_and_ordinary_parsing_stays_equivalent() -> TestResult { + let source = + "= Document\n:label: Early\n\nSection {label}\n---------------\n\n.A title\nParagraph."; + let native = acdc_parser::parse(source, &Options::default())?; + let extended = Registry::default().parse(source, &Options::default())?; + let query = extended.query(); + let heading = query + .select(BlockContext::Section) + .next() + .ok_or("heading")?; + assert_eq!( + heading + .title_source() + .map(crate::extensions::TitleSource::raw_source), + Some("Section {label}") + ); + assert_eq!( + native.document_storage(), + extended.parsed.document_storage() + ); + assert!( + native + .document_storage() + .blocks + .iter() + .filter_map(crate::Block::title) + .all(|title| title.source().is_none()) + ); + Ok(()) +} + +#[test] +fn extensions_title_sources_survive_placeholder_replacement_and_preserve_caption_context() +-> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let source = "= Document\n:label: Early\n:example-caption: Before\n\n.Pending {label}\n[example]\ndefer::[]\n\n.Original {label}\n====\n:example-caption: Inside\n\nBody.\n====\n\n:label: Late"; + let mut result = support::registry().parse(source, &options)?; + let target = result + .deferred_blocks() + .first() + .ok_or("request")? + .target() + .clone(); + let id = result.ensure_id(&target)?.to_owned(); + let mut editor = DocumentEditor::new(&mut result); + editor.replace_placeholder(&target, BlockBuilder::paragraph("Replaced"))?; + let query = editor.query(); + let replacement = query.get(&target).ok_or("replacement")?; + assert_eq!(replacement.context(), BlockContext::Example); + assert_eq!(replacement.output_id(), Some(id.as_str())); + let retained = replacement.title_source().ok_or("retained")?; + assert_eq!(retained.raw_source(), "Pending {label}"); + assert_eq!( + retained + .attributes() + .get("label") + .and_then(DocumentAttributeValue::as_str), + Some("Early") + ); + assert_eq!(retained.source_location().location.start.line, 5); + let original = query + .select(BlockContext::Example) + .nth(1) + .ok_or("original")?; + assert_eq!( + original + .title_source() + .ok_or("source")? + .attributes() + .get("example-caption") + .and_then(DocumentAttributeValue::as_str), + Some("Before") + ); + assert!(matches!( + original.caption(), + Some(crate::ast::CaptionRef::Numbered { + label: "Inside", + .. + }) + )); + } + Ok(()) +} diff --git a/acdc-parser/src/extensions/title.rs b/acdc-parser/src/extensions/title.rs new file mode 100644 index 000000000..b5f1fe876 --- /dev/null +++ b/acdc-parser/src/extensions/title.rs @@ -0,0 +1,39 @@ +use crate::{DocumentAttributes, SourceLocation, Substitution, ast::DocumentAttributesRef}; + +/// Title input retained by an extension parse before inline substitutions. +/// +/// Source is after document preprocessing and excludes the title marker or +/// attribute quotes. The attribute snapshot and substitution order describe the +/// title itself, independently of the block body's `subs=` setting. For attribute +/// titles, attribute-list expansion and dequoting precede these inline stages. +#[derive(Clone, Debug)] +pub struct TitleSource<'doc> { + pub(crate) source: &'doc str, + pub(crate) substitutions: Vec, + pub(crate) attributes: DocumentAttributes<'doc>, + pub(crate) location: SourceLocation, +} + +impl<'doc> TitleSource<'doc> { + #[must_use] + pub const fn raw_source(&self) -> &'doc str { + self.source + } + + /// The stages applied to the title, in execution order. + #[must_use] + pub fn substitutions(&self) -> &[Substitution] { + &self.substitutions + } + + /// Document attributes in effect when this title was interpreted. + #[must_use] + pub fn attributes(&self) -> DocumentAttributesRef<'_> { + DocumentAttributesRef::from(&self.attributes) + } + + #[must_use] + pub const fn source_location(&self) -> &SourceLocation { + &self.location + } +} diff --git a/acdc-parser/src/grammar/document/metadata.rs b/acdc-parser/src/grammar/document/metadata.rs index 3d4bafd85..8e1c8c257 100644 --- a/acdc-parser/src/grammar/document/metadata.rs +++ b/acdc-parser/src/grammar/document/metadata.rs @@ -27,7 +27,7 @@ use crate::{ substitution::{SubstitutionPlan, parse_subs_attribute}, }, }; -use std::{borrow::Cow, collections::BTreeMap, rc::Rc}; +use std::{borrow::Cow, collections::BTreeMap, rc::Rc, sync::Arc}; use super::delimited::{DelimitedKind, DelimitedParams, build_delimited_block}; @@ -172,6 +172,7 @@ pub(super) fn resolve_title<'a>( source: TitleSource<'a>, offset: usize, ) -> Result, Error> { + let retained = retain_metadata_title(state, &source, offset); let inlines = match source { TitleSource::Dot { source, start, end } => { process_inlines( @@ -192,7 +193,61 @@ pub(super) fn resolve_title<'a>( } TitleSource::Attribute(source) => process_attribute_inlines(state, &source)?, }; - Ok(Title::new(inlines)) + Ok(Title::new(inlines).with_source(retained)) +} + +fn retain_metadata_title<'a>( + state: &ParserState<'a>, + source: &TitleSource<'a>, + offset: usize, +) -> Option>> { + state.options.extensions.as_ref()?; + let (raw, location, substitutions, attributes) = match source { + TitleSource::Dot { source, start, end } => ( + *source, + state.create_block_location(*start, *end, offset), + SubstitutionPlan::for_mode(state.options.compatibility_mode), + state.document_attributes.as_ref(), + ), + TitleSource::Attribute(source) => { + let substitutions = if state.options.compatibility_mode == CompatibilityMode::Draft + && source.quote != AttributeQuote::Single + { + SubstitutionPlan::only(&Substitution::SpecialChars) + } else { + SubstitutionPlan::for_attribute(state.options.compatibility_mode) + }; + ( + state + .source_slice(source.source_range.clone()) + .unwrap_or(source.text), + state.create_block_location(source.source_range.start, source.source_range.end, 0), + substitutions, + source.attributes.as_ref(), + ) + } + }; + Some(Arc::new(crate::extensions::TitleSource { + source: raw, + substitutions: substitutions.stages(), + attributes: attributes.clone(), + location: state.create_error_source_location(location), + })) +} + +pub(super) fn retain_heading_title<'a>( + state: &ParserState<'a>, + source: &'a str, + location: impl FnOnce() -> Location, + substitutions: SubstitutionPlan, +) -> Option>> { + state.options.extensions.as_ref()?; + Some(Arc::new(crate::extensions::TitleSource { + source, + substitutions: substitutions.stages(), + attributes: state.document_attributes.as_ref().clone(), + location: state.create_error_source_location(location()), + })) } fn literal_attribute_inlines<'a>( diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 17fddd104..a04f62fac 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -44,8 +44,8 @@ use crate::{ finish_block_parsing_metadata, media_attributes_ahead, merge_macro_metadata, metadata_comment, metadata_marks_discrete_heading, order_block_prefix_events, parse_block_attribute_list, push_metadata_anchor, resolve_block_content_attributes, - resolve_title, route_block_positions, route_media_attributes, select_heading_style, - thematic_break_anchors, + resolve_title, retain_heading_title, route_block_positions, route_media_attributes, + select_heading_style, thematic_break_anchors, }, paragraph::{ParagraphParams, build_paragraph, paragraph_text_end}, quotes::{QuoteAttribution, QuoteParams, QuoteSource, build_quote}, @@ -1267,10 +1267,11 @@ peg::parser! { title_start:position!() title:setext_title_text() title_end:position!() eol() setext_level:setext_section_level(title.trim().chars().count(), parent_section_level) section_header:({ + let location = state.create_block_location(title_start, title_end, offset); + let retained = retain_heading_title(state, title, || location.clone(), block_metadata.substitutions); let (processed_title, natural_title) = process_inlines(state, &block_metadata, title_start, title_end, offset, title)?; - let title = Title::new(processed_title); - let location = state.create_block_location(title_start, title_end, offset); + let title = Title::new(processed_title).with_source(retained); Ok::, Error>(register_section_header( state, &block_metadata, @@ -1513,6 +1514,12 @@ peg::parser! { = title:$([^'\n']*) { tracing::debug!(title_start = span_start, title_end = span_end, "Found section title"); + let retained = retain_heading_title( + state, + title, + || state.create_block_location(span_start, span_end, offset), + block_metadata.substitutions, + ); let (content, natural_title) = process_inlines( state, block_metadata, @@ -1521,7 +1528,7 @@ peg::parser! { offset, title, )?; - Ok((Title::new(content), natural_title)) + Ok((Title::new(content).with_source(retained), natural_title)) } rule section_content(mode: ConstructionMode, offset: usize, parent_section_level: Option, direct_parent_section_kind: Option) -> Result>, Error> diff --git a/acdc-parser/src/grammar/inline_processing.rs b/acdc-parser/src/grammar/inline_processing.rs index 6055f77b1..a80b1d133 100644 --- a/acdc-parser/src/grammar/inline_processing.rs +++ b/acdc-parser/src/grammar/inline_processing.rs @@ -30,10 +30,7 @@ pub(super) fn process_attribute_inlines<'a>( state: &mut ParserState<'a>, source: &ResolvedContentAttribute<'a>, ) -> Result>, Error> { - let mut substitutions = SubstitutionPlan::default(); - if state.options.compatibility_mode == crate::CompatibilityMode::Draft { - substitutions = substitutions.without(&Substitution::Attributes); - } + let substitutions = SubstitutionPlan::for_attribute(state.options.compatibility_mode); process_attribute_inlines_with_substitutions( state, source, diff --git a/acdc-parser/src/model/substitution.rs b/acdc-parser/src/model/substitution.rs index 011821048..d7d952085 100644 --- a/acdc-parser/src/model/substitution.rs +++ b/acdc-parser/src/model/substitution.rs @@ -101,6 +101,15 @@ impl SubstitutionPlan { Self::from_substitutions(Self::defaults(mode)) } + pub(crate) fn for_attribute(mode: CompatibilityMode) -> Self { + let plan = Self::default(); + if mode == CompatibilityMode::Draft { + plan.without(&Substitution::Attributes) + } else { + plan + } + } + pub(crate) fn for_block_spec(spec: &SubstitutionSpec, mode: CompatibilityMode) -> Self { // Parser defaults include callout discovery for verbatim blocks. Resolve once: // filling missing stages afterwards would restore removed group members. @@ -153,6 +162,16 @@ impl SubstitutionPlan { }); stages } + + pub(crate) fn stages(self) -> Vec { + let mut stages: Vec<_> = DEFAULT_PARSER_SUBSTITUTIONS + .iter() + .filter(|stage| self.enabled(stage)) + .cloned() + .collect(); + stages.sort_by_key(|stage| substitution_stage_index(stage).and_then(|i| self.ranks.get(i))); + stages + } } impl Default for SubstitutionPlan { diff --git a/acdc-parser/src/model/title.rs b/acdc-parser/src/model/title.rs index ad160dbec..b1f0f7630 100644 --- a/acdc-parser/src/model/title.rs +++ b/acdc-parser/src/model/title.rs @@ -1,4 +1,5 @@ use serde::{Serialize, Serializer}; +use std::sync::Arc; use super::{ContentAttribute, InlineNode}; @@ -9,6 +10,7 @@ use super::{ContentAttribute, InlineNode}; /// and [`Self::is_empty`] to inspect its text. Read its nodes through [`Self::content`]. /// /// Serialization emits the inline array. A containing block omits an absent title. +/// Retained extension source context does not participate in equality or serialization. /// /// ```compile_fail,E0308 /// use acdc_parser::{InlineNode, Title}; @@ -27,9 +29,18 @@ use super::{ContentAttribute, InlineNode}; /// let title = Title::default(); /// for _ in &title {} /// ``` -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default)] #[non_exhaustive] -pub struct Title<'a>(Option>); +pub struct Title<'a> { + content: Option>, + source: Option>>, +} + +impl PartialEq for Title<'_> { + fn eq(&self, other: &Self) -> bool { + self.content == other.content + } +} /// A secondary document title. pub type Subtitle<'a> = Title<'a>; @@ -38,13 +49,28 @@ impl<'a> Title<'a> { /// Construct a present title, including an explicitly empty title. #[must_use] pub fn new(inlines: Vec>) -> Self { - Self(Some(ContentAttribute::new(inlines))) + Self { + content: Some(ContentAttribute::new(inlines)), + source: None, + } + } + + pub(crate) fn with_source( + mut self, + source: Option>>, + ) -> Self { + self.source = source; + self + } + + pub(crate) fn source(&self) -> Option<&crate::extensions::TitleSource<'a>> { + self.source.as_deref() } /// Whether a title was supplied, independently of its text length. #[must_use] pub fn is_present(&self) -> bool { - self.0.is_some() + self.content.is_some() } /// Whether the title contains no inline nodes, including an absent title. @@ -62,15 +88,18 @@ impl<'a> Title<'a> { /// Consume the title, returning its inline nodes or an empty vector if absent. #[must_use] pub fn into_inlines(self) -> Vec> { - self.0.map_or_else(Vec::new, ContentAttribute::into_inlines) + self.content + .map_or_else(Vec::new, ContentAttribute::into_inlines) } pub(crate) fn as_inlines(&self) -> &[InlineNode<'a>] { - self.0.as_ref().map_or(&[], ContentAttribute::as_inlines) + self.content + .as_ref() + .map_or(&[], ContentAttribute::as_inlines) } pub(crate) fn inlines_mut(&mut self) -> &mut [InlineNode<'a>] { - self.0 + self.content .as_mut() .map_or(&mut [], |content| content.inlines_mut().as_mut_slice()) } From ac80f91984ed3098f7f41139fd7736814bb15254 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 14 Nov 2026 20:47:07 +0100 Subject: [PATCH 14/55] test(parser): verify semantic query and target identity contracts Exercise generic query and ID consumers through paired fixtures. Cover depth-first traversal in supported containers, query observations after edits, foreign and removed handles, real ID collisions, and request-order determinism in both compatibility modes. Refs SC-537. --- .../tests/extensions/semantic_queries.adoc | 36 + ...antic_queries.asciidoctor.diagnostics.json | 4 + .../semantic_queries.asciidoctor.json | 642 ++++++++++++++++++ .../semantic_queries.draft.diagnostics.json | 4 + .../extensions/semantic_queries.draft.json | 642 ++++++++++++++++++ acdc-parser/src/extensions/tests/queries.rs | 153 ++++- acdc-parser/src/extensions/tests/support.rs | 60 +- 7 files changed, 1535 insertions(+), 6 deletions(-) create mode 100644 acdc-parser/fixtures/tests/extensions/semantic_queries.adoc create mode 100644 acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.diagnostics.json create mode 100644 acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.json create mode 100644 acdc-parser/fixtures/tests/extensions/semantic_queries.draft.diagnostics.json create mode 100644 acdc-parser/fixtures/tests/extensions/semantic_queries.draft.json diff --git a/acdc-parser/fixtures/tests/extensions/semantic_queries.adoc b/acdc-parser/fixtures/tests/extensions/semantic_queries.adoc new file mode 100644 index 000000000..621444b1e --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/semantic_queries.adoc @@ -0,0 +1,36 @@ += Semantic queries +:label: Early +:figure-caption: Picture + +query::[] + +.[[_acdc_2]]Authored collision {label} +image::first.svg[] + +[#authored] +== Outer {label} + +.Compound {label} +[example] +-- +* Item ++ +.Attached {label} +image::attached.svg[] +-- + +[discrete] +=== Discrete {label} + +[cols=a] +|=== +|== Cell {label} + +.Cell figure {label} +image::cell.svg[] +|=== + +configure::label[Late] + +[title='{label} attribute'] +Paragraph. diff --git a/acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.diagnostics.json b/acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.diagnostics.json new file mode 100644 index 000000000..849eafd43 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.diagnostics.json @@ -0,0 +1,4 @@ +{ + "recovery": null, + "warnings": [] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.json b/acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.json new file mode 100644 index 000000000..e63160e46 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/semantic_queries.asciidoctor.json @@ -0,0 +1,642 @@ +{ + "name": "document", + "type": "block", + "header": { + "title": [ + { + "name": "text", + "type": "string", + "value": "Semantic queries", + "location": [ + { + "line": 1, + "col": 3 + }, + { + "line": 1, + "col": 18 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 3, + "col": 24 + } + ] + }, + "attributes": { + "figure-caption": "Picture", + "label": "Early" + }, + "blocks": [ + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "[{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(1) }\",\"context\":\"Image\",\"id\":\"_acdc_2_2\",\"label\":\"Early\",\"raw_title\":\"[[_acdc_2]]Authored collision {label}\",\"section\":null,\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":7},{\"caption\":null,\"context\":\"Section\",\"id\":\"authored\",\"label\":\"Early\",\"raw_title\":\"Outer {label}\",\"section\":null,\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":11},{\"caption\":\"Numbered { kind: Example, label: \\\"Example\\\", number: Some(1) }\",\"context\":\"Example\",\"id\":\"_acdc_4\",\"label\":\"Early\",\"raw_title\":\"Compound {label}\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":13},{\"caption\":null,\"context\":\"UnorderedList\",\"id\":\"_acdc_5\",\"label\":null,\"raw_title\":null,\"section\":\"authored\",\"substitutions\":null,\"title_line\":null},{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(2) }\",\"context\":\"Image\",\"id\":\"_acdc_6\",\"label\":\"Early\",\"raw_title\":\"Attached {label}\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":18},{\"caption\":null,\"context\":\"DiscreteHeading\",\"id\":\"_acdc_7\",\"label\":\"Early\",\"raw_title\":\"Discrete {label}\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":23},{\"caption\":\"Numbered { kind: Table, label: \\\"Table\\\", number: None }\",\"context\":\"Table\",\"id\":\"_acdc_8\",\"label\":null,\"raw_title\":null,\"section\":\"authored\",\"substitutions\":null,\"title_line\":null},{\"caption\":null,\"context\":\"Section\",\"id\":\"_cell_early\",\"label\":\"Early\",\"raw_title\":\"Cell {label}\",\"section\":null,\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":27},{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(3) }\",\"context\":\"Image\",\"id\":\"_acdc_10\",\"label\":\"Early\",\"raw_title\":\"Cell figure {label}\",\"section\":\"_cell_early\",\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":29},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":\"authored\",\"substitutions\":null,\"title_line\":null},{\"caption\":null,\"context\":\"Paragraph\",\"id\":\"_acdc_12\",\"label\":\"Late\",\"raw_title\":\"{label} attribute\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":35}]", + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 5, + "col": 9 + } + ] + } + ], + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 5, + "col": 9 + } + ] + }, + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "id": { + "id": "_acdc_2_2", + "location": [ + { + "line": 7, + "col": 1 + }, + { + "line": 8, + "col": 18 + } + ] + } + }, + "title": [ + { + "name": "anchor", + "type": "inline", + "id": "_acdc_2", + "location": [ + { + "line": 7, + "col": 2 + }, + { + "line": 7, + "col": 12 + } + ] + }, + { + "name": "text", + "type": "string", + "value": "Authored collision Early", + "location": [ + { + "line": 7, + "col": 13 + }, + { + "line": 7, + "col": 38 + } + ] + } + ], + "source": { + "type": "path", + "value": "first.svg" + }, + "location": [ + { + "line": 7, + "col": 1 + }, + { + "line": 8, + "col": 18 + } + ] + }, + { + "name": "section", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Outer Early", + "location": [ + { + "line": 11, + "col": 4 + }, + { + "line": 11, + "col": 16 + } + ] + } + ], + "level": 1, + "metadata": { + "anchors": [ + { + "id": "authored", + "location": [ + { + "line": 10, + "col": 1 + }, + { + "line": 10, + "col": 12 + } + ] + } + ] + }, + "blocks": [ + { + "name": "example", + "type": "block", + "form": "delimited", + "delimiter": "--", + "metadata": { + "style": "example", + "id": { + "id": "_acdc_4", + "location": [ + { + "line": 13, + "col": 1 + }, + { + "line": 20, + "col": 2 + } + ] + } + }, + "blocks": [ + { + "name": "list", + "type": "block", + "variant": "unordered", + "marker": "*", + "metadata": { + "id": { + "id": "_acdc_5", + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + }, + "items": [ + { + "name": "listItem", + "type": "block", + "marker": "*", + "principal": [ + { + "name": "text", + "type": "string", + "value": "Item", + "location": [ + { + "line": 16, + "col": 3 + }, + { + "line": 16, + "col": 6 + } + ] + } + ], + "blocks": [ + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "id": { + "id": "_acdc_6", + "location": [ + { + "line": 18, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Attached Early", + "location": [ + { + "line": 18, + "col": 2 + }, + { + "line": 18, + "col": 17 + } + ] + } + ], + "source": { + "type": "path", + "value": "attached.svg" + }, + "location": [ + { + "line": 18, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + ], + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + ], + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + ], + "title": [ + { + "name": "text", + "type": "string", + "value": "Compound Early", + "location": [ + { + "line": 13, + "col": 2 + }, + { + "line": 13, + "col": 17 + } + ] + } + ], + "location": [ + { + "line": 13, + "col": 1 + }, + { + "line": 20, + "col": 2 + } + ] + }, + { + "name": "heading", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Discrete Early", + "location": [ + { + "line": 23, + "col": 5 + }, + { + "line": 23, + "col": 20 + } + ] + } + ], + "level": 2, + "metadata": { + "style": "discrete", + "id": { + "id": "_acdc_7", + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 23, + "col": 20 + } + ] + } + }, + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 23, + "col": 20 + } + ] + }, + { + "name": "table", + "type": "block", + "form": "delimited", + "delimiter": "|===", + "metadata": { + "attributes": { + "cols": "a" + }, + "id": { + "id": "_acdc_8", + "location": [ + { + "line": 25, + "col": 1 + }, + { + "line": 31, + "col": 4 + } + ] + } + }, + "content": { + "header": null, + "footer": null, + "rows": [ + { + "columns": [ + { + "footnote_scope": true, + "content": [ + { + "name": "section", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Cell Early", + "location": [ + { + "line": 27, + "col": 5 + }, + { + "line": 27, + "col": 16 + } + ] + } + ], + "level": 1, + "blocks": [ + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "id": { + "id": "_acdc_10", + "location": [ + { + "line": 29, + "col": 1 + }, + { + "line": 30, + "col": 17 + } + ] + } + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Cell figure Early", + "location": [ + { + "line": 29, + "col": 2 + }, + { + "line": 29, + "col": 20 + } + ] + } + ], + "source": { + "type": "path", + "value": "cell.svg" + }, + "location": [ + { + "line": 29, + "col": 1 + }, + { + "line": 30, + "col": 17 + } + ] + } + ], + "location": [ + { + "line": 27, + "col": 2 + }, + { + "line": 30, + "col": 17 + } + ] + } + ], + "style": "asciidoc" + } + ] + } + ], + "columns": [ + { + "style": "asciidoc" + } + ], + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 31, + "col": 4 + } + ] + }, + "location": [ + { + "line": 25, + "col": 1 + }, + { + "line": 31, + "col": 4 + } + ] + }, + { + "name": "label", + "type": "attribute", + "value": "Late", + "location": [ + { + "line": 33, + "col": 1 + }, + { + "line": 33, + "col": 22 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Late attribute", + "location": [ + { + "line": 35, + "col": 9 + }, + { + "line": 35, + "col": 25 + } + ] + } + ], + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Paragraph.", + "location": [ + { + "line": 36, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + ], + "metadata": { + "id": { + "id": "_acdc_12", + "location": [ + { + "line": 35, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + }, + "location": [ + { + "line": 35, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + ], + "location": [ + { + "line": 10, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/extensions/semantic_queries.draft.diagnostics.json b/acdc-parser/fixtures/tests/extensions/semantic_queries.draft.diagnostics.json new file mode 100644 index 000000000..849eafd43 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/semantic_queries.draft.diagnostics.json @@ -0,0 +1,4 @@ +{ + "recovery": null, + "warnings": [] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/extensions/semantic_queries.draft.json b/acdc-parser/fixtures/tests/extensions/semantic_queries.draft.json new file mode 100644 index 000000000..97ba5e5c3 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/semantic_queries.draft.json @@ -0,0 +1,642 @@ +{ + "name": "document", + "type": "block", + "header": { + "title": [ + { + "name": "text", + "type": "string", + "value": "Semantic queries", + "location": [ + { + "line": 1, + "col": 3 + }, + { + "line": 1, + "col": 18 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 3, + "col": 24 + } + ] + }, + "attributes": { + "figure-caption": "Picture", + "label": "Early" + }, + "blocks": [ + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "[{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(1) }\",\"context\":\"Image\",\"id\":\"_acdc_2_2\",\"label\":\"Early\",\"raw_title\":\"[[_acdc_2]]Authored collision {label}\",\"section\":null,\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":7},{\"caption\":null,\"context\":\"Section\",\"id\":\"authored\",\"label\":\"Early\",\"raw_title\":\"Outer {label}\",\"section\":null,\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":11},{\"caption\":\"Numbered { kind: Example, label: \\\"Example\\\", number: Some(1) }\",\"context\":\"Example\",\"id\":\"_acdc_4\",\"label\":\"Early\",\"raw_title\":\"Compound {label}\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":13},{\"caption\":null,\"context\":\"UnorderedList\",\"id\":\"_acdc_5\",\"label\":null,\"raw_title\":null,\"section\":\"authored\",\"substitutions\":null,\"title_line\":null},{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(2) }\",\"context\":\"Image\",\"id\":\"_acdc_6\",\"label\":\"Early\",\"raw_title\":\"Attached {label}\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":18},{\"caption\":null,\"context\":\"DiscreteHeading\",\"id\":\"_acdc_7\",\"label\":\"Early\",\"raw_title\":\"Discrete {label}\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":23},{\"caption\":\"Numbered { kind: Table, label: \\\"Table\\\", number: None }\",\"context\":\"Table\",\"id\":\"_acdc_8\",\"label\":null,\"raw_title\":null,\"section\":\"authored\",\"substitutions\":null,\"title_line\":null},{\"caption\":null,\"context\":\"Section\",\"id\":\"_cell_early\",\"label\":\"Early\",\"raw_title\":\"Cell {label}\",\"section\":null,\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":27},{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(3) }\",\"context\":\"Image\",\"id\":\"_acdc_10\",\"label\":\"Early\",\"raw_title\":\"Cell figure {label}\",\"section\":\"_cell_early\",\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":29},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":\"authored\",\"substitutions\":null,\"title_line\":null},{\"caption\":null,\"context\":\"Paragraph\",\"id\":\"_acdc_12\",\"label\":\"Late\",\"raw_title\":\"{label} attribute\",\"section\":\"authored\",\"substitutions\":[\"special_chars\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":35}]", + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 5, + "col": 9 + } + ] + } + ], + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 5, + "col": 9 + } + ] + }, + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "id": { + "id": "_acdc_2_2", + "location": [ + { + "line": 7, + "col": 1 + }, + { + "line": 8, + "col": 18 + } + ] + } + }, + "title": [ + { + "name": "anchor", + "type": "inline", + "id": "_acdc_2", + "location": [ + { + "line": 7, + "col": 2 + }, + { + "line": 7, + "col": 12 + } + ] + }, + { + "name": "text", + "type": "string", + "value": "Authored collision Early", + "location": [ + { + "line": 7, + "col": 13 + }, + { + "line": 7, + "col": 38 + } + ] + } + ], + "source": { + "type": "path", + "value": "first.svg" + }, + "location": [ + { + "line": 7, + "col": 1 + }, + { + "line": 8, + "col": 18 + } + ] + }, + { + "name": "section", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Outer Early", + "location": [ + { + "line": 11, + "col": 4 + }, + { + "line": 11, + "col": 16 + } + ] + } + ], + "level": 1, + "metadata": { + "anchors": [ + { + "id": "authored", + "location": [ + { + "line": 10, + "col": 1 + }, + { + "line": 10, + "col": 12 + } + ] + } + ] + }, + "blocks": [ + { + "name": "example", + "type": "block", + "form": "delimited", + "delimiter": "--", + "metadata": { + "style": "example", + "id": { + "id": "_acdc_4", + "location": [ + { + "line": 13, + "col": 1 + }, + { + "line": 20, + "col": 2 + } + ] + } + }, + "blocks": [ + { + "name": "list", + "type": "block", + "variant": "unordered", + "marker": "*", + "metadata": { + "id": { + "id": "_acdc_5", + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + }, + "items": [ + { + "name": "listItem", + "type": "block", + "marker": "*", + "principal": [ + { + "name": "text", + "type": "string", + "value": "Item", + "location": [ + { + "line": 16, + "col": 3 + }, + { + "line": 16, + "col": 6 + } + ] + } + ], + "blocks": [ + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "id": { + "id": "_acdc_6", + "location": [ + { + "line": 18, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Attached Early", + "location": [ + { + "line": 18, + "col": 2 + }, + { + "line": 18, + "col": 17 + } + ] + } + ], + "source": { + "type": "path", + "value": "attached.svg" + }, + "location": [ + { + "line": 18, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + ], + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + ], + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 19, + "col": 21 + } + ] + } + ], + "title": [ + { + "name": "text", + "type": "string", + "value": "Compound Early", + "location": [ + { + "line": 13, + "col": 2 + }, + { + "line": 13, + "col": 17 + } + ] + } + ], + "location": [ + { + "line": 13, + "col": 1 + }, + { + "line": 20, + "col": 2 + } + ] + }, + { + "name": "heading", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Discrete Early", + "location": [ + { + "line": 23, + "col": 5 + }, + { + "line": 23, + "col": 20 + } + ] + } + ], + "level": 2, + "metadata": { + "style": "discrete", + "id": { + "id": "_acdc_7", + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 23, + "col": 20 + } + ] + } + }, + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 23, + "col": 20 + } + ] + }, + { + "name": "table", + "type": "block", + "form": "delimited", + "delimiter": "|===", + "metadata": { + "attributes": { + "cols": "a" + }, + "id": { + "id": "_acdc_8", + "location": [ + { + "line": 25, + "col": 1 + }, + { + "line": 31, + "col": 4 + } + ] + } + }, + "content": { + "header": null, + "footer": null, + "rows": [ + { + "columns": [ + { + "footnote_scope": true, + "content": [ + { + "name": "section", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Cell Early", + "location": [ + { + "line": 27, + "col": 5 + }, + { + "line": 27, + "col": 16 + } + ] + } + ], + "level": 1, + "blocks": [ + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "id": { + "id": "_acdc_10", + "location": [ + { + "line": 29, + "col": 1 + }, + { + "line": 30, + "col": 17 + } + ] + } + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Cell figure Early", + "location": [ + { + "line": 29, + "col": 2 + }, + { + "line": 29, + "col": 20 + } + ] + } + ], + "source": { + "type": "path", + "value": "cell.svg" + }, + "location": [ + { + "line": 29, + "col": 1 + }, + { + "line": 30, + "col": 17 + } + ] + } + ], + "location": [ + { + "line": 27, + "col": 2 + }, + { + "line": 30, + "col": 17 + } + ] + } + ], + "style": "asciidoc" + } + ] + } + ], + "columns": [ + { + "style": "asciidoc" + } + ], + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 31, + "col": 4 + } + ] + }, + "location": [ + { + "line": 25, + "col": 1 + }, + { + "line": 31, + "col": 4 + } + ] + }, + { + "name": "label", + "type": "attribute", + "value": "Late", + "location": [ + { + "line": 33, + "col": 1 + }, + { + "line": 33, + "col": 22 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "title": [ + { + "name": "text", + "type": "string", + "value": "Late attribute", + "location": [ + { + "line": 35, + "col": 9 + }, + { + "line": 35, + "col": 25 + } + ] + } + ], + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Paragraph.", + "location": [ + { + "line": 36, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + ], + "metadata": { + "id": { + "id": "_acdc_12", + "location": [ + { + "line": 35, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + }, + "location": [ + { + "line": 35, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + ], + "location": [ + { + "line": 10, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 36, + "col": 10 + } + ] +} \ No newline at end of file diff --git a/acdc-parser/src/extensions/tests/queries.rs b/acdc-parser/src/extensions/tests/queries.rs index ab85d1941..9866bbce2 100644 --- a/acdc-parser/src/extensions/tests/queries.rs +++ b/acdc-parser/src/extensions/tests/queries.rs @@ -10,14 +10,151 @@ use std::{ }; use acdc_parser::{ - Block, InlineNode, Options, SafeMode, WarningKind, - extensions::{BlockContext, Registry, TargetError}, + Block, CompatibilityMode, InlineNode, Options, SafeMode, WarningKind, + extensions::{BlockBuilder, BlockContext, DocumentEditor, Registry, TargetError}, }; use super::support; type TestResult = Result<(), Box>; +#[test] +fn extensions_queries_visit_every_container_in_depth_first_order() -> TestResult { + use BlockContext::{ + Admonition, CalloutList, DescriptionList, Example, Image, Listing, Open, OrderedList, + Quote, Section, Sidebar, Table, UnorderedList, + }; + let cases: &[(&str, &[BlockContext])] = &[ + ("--\nimage::one.svg[]\n--", &[Open, Image]), + ("====\nimage::one.svg[]\n====", &[Example, Image]), + ("****\nimage::one.svg[]\n****", &[Sidebar, Image]), + ("____\nimage::one.svg[]\n____", &[Quote, Image]), + ("[NOTE]\n====\nimage::one.svg[]\n====", &[Admonition, Image]), + ( + "* One\n** Nested\n+\nimage::one.svg[]\n\n* Two\n+\nimage::two.svg[]", + &[UnorderedList, UnorderedList, Image, Image], + ), + ( + ". One\n.. Nested\n+\nimage::one.svg[]\n\n. Two\n+\nimage::two.svg[]", + &[OrderedList, OrderedList, Image, Image], + ), + ( + "Term:: Definition\n+\nimage::one.svg[]\n\nOther:: Definition\n+\nimage::two.svg[]", + &[DescriptionList, Image, Image], + ), + ( + "----\nCode <1>\n----\n<1> Explanation\n+\nimage::one.svg[]", + &[Listing, CalloutList, Image], + ), + ( + "[cols=a,options=\"header,footer\"]\n|===\n|Header\n\n|image::one.svg[]\n\n|image::two.svg[]\n|===", + &[Table, Image, Image], + ), + ]; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (body, expected) in cases { + let source = format!("= Document\n\n== Outer\n\n{body}"); + let result = Registry::default().parse(&source, &options)?; + let query = result.query(); + let observed = query + .blocks() + .map(|view| view.context()) + .collect::>(); + let expected = std::iter::once(Section) + .chain(expected.iter().copied()) + .collect::>(); + assert_eq!(observed, expected, "{mode:?}: {body}"); + let outer = query.select(Section).next().ok_or("outer")?; + for view in query.blocks().skip(1) { + assert_eq!( + view.containing_section(), + (view.context() != Image || !body.contains("|===")).then_some(outer.target()), + "{mode:?}: {body}" + ); + } + } + } + Ok(()) +} + +#[test] +fn extensions_queries_observe_edits_and_reject_foreign_or_removed_handles() -> TestResult { + let source = + "[#gone]\n== Gone\n\n.Pending title\ndefer::[]\n\n[#stay]\n== Stay\n\nSurviving paragraph."; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let registry = support::registry(); + let mut result = registry.parse(source, &options)?; + let foreign = registry.parse(source, &options)?; + let handles = result + .query() + .blocks() + .map(|view| view.target().clone()) + .collect::>(); + let reused_id = result + .ensure_id(handles.get(1).ok_or("pending")?)? + .to_owned(); + let mut editor = DocumentEditor::new(&mut result); + for target in foreign.query().blocks().map(|view| view.target().clone()) { + assert!(editor.query().get(&target).is_none()); + assert!(editor.ensure_id(&target).is_err()); + assert!( + editor + .insert_before(&target, BlockBuilder::paragraph("Invalid")) + .is_err() + ); + assert!( + editor + .replace_placeholder(&target, BlockBuilder::paragraph("Invalid")) + .is_err() + ); + assert!(editor.remove_section(&target).is_err()); + assert!(editor.discard_placeholder(&target).is_err()); + } + let section = handles.first().ok_or("section")?; + let pending = handles.get(1).ok_or("pending")?; + let stay = handles.get(2).ok_or("stay")?; + let snapshot = handles.clone(); + assert_eq!(editor.query().select(BlockContext::Extension).count(), 1); + editor.remove_section(section)?; + assert!(editor.deferred_blocks().is_empty()); + assert_eq!(editor.query().select(BlockContext::Extension).count(), 0); + let new = editor.insert_before( + stay, + BlockBuilder::paragraph("New owner").with_id(reused_id.clone()), + )?; + assert_eq!( + editor.query().get(&new).and_then(|view| view.output_id()), + Some(reused_id.as_str()) + ); + assert!(!snapshot.contains(&new)); + for removed in [section, pending] { + assert!(editor.query().get(removed).is_none()); + assert!(editor.ensure_id(removed).is_err()); + assert!( + editor + .insert_before(removed, BlockBuilder::paragraph("Invalid")) + .is_err() + ); + assert!(editor.remove_section(removed).is_err()); + assert!( + editor + .replace_placeholder(removed, BlockBuilder::paragraph("Invalid")) + .is_err() + ); + assert!(editor.discard_placeholder(removed).is_err()); + } + let surviving = snapshot + .iter() + .filter(|target| editor.query().get(target).is_some()) + .count(); + assert_eq!(surviving, 2); + assert_eq!(editor.query().blocks().count(), 3); + } + Ok(()) +} + #[test] fn extensions_query_targets_are_document_local_and_preserve_deferred_identity() -> TestResult { let registry = support::registry(); @@ -97,11 +234,19 @@ fn extensions_ids_avoid_authored_inline_and_generated_section_ids() -> TestResul #[test] fn extensions_ids_preserve_existing_ids_and_query_order() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + ids_preserve_existing_ids_and_query_order(mode)?; + } + Ok(()) +} + +fn ids_preserve_existing_ids_and_query_order(mode: CompatibilityMode) -> TestResult { let input = "[#authored]\nimage::one.svg[]\n\nimage::two.svg[]\n\n== Heading\n\nimage::three.svg[]"; let registry = Registry::default(); - let mut first = registry.parse(input, &Options::default())?; - let mut second = registry.parse(input, &Options::default())?; + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut first = registry.parse(input, &options)?; + let mut second = registry.parse(input, &options)?; let first_targets: Vec<_> = first .query() .blocks() diff --git a/acdc-parser/src/extensions/tests/support.rs b/acdc-parser/src/extensions/tests/support.rs index f684a6867..f986269a8 100644 --- a/acdc-parser/src/extensions/tests/support.rs +++ b/acdc-parser/src/extensions/tests/support.rs @@ -1,8 +1,11 @@ #![allow(clippy::expect_used)] use acdc_parser::{ - ElementAttributes, - extensions::{BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry}, + ElementAttributes, Error, + extensions::{ + BlockBuilder, BlockMacro, BlockMacroOutput, BlockMacroProcessor, DocumentEditor, + MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, + }, }; #[derive(Default)] @@ -57,9 +60,62 @@ pub(super) fn registry() -> Registry { builder .register(BlockMacro::new("configure", || configure).with_positional_attributes(["value"])) .expect("valid fixture macro"); + builder + .register(BlockMacro::new("query", || Defer)) + .expect("valid query fixture macro"); + builder + .register_tree_processor(TreeProcessorRegistration::new("query", || Query)) + .expect("valid query fixture processor"); builder.build() } +struct Query; + +impl TreeProcessor for Query { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let requests: Vec<_> = editor + .deferred_blocks() + .iter() + .filter(|request| request.invocation.name == "query") + .map(|request| request.target().clone()) + .collect(); + if requests.is_empty() { + return Ok(()); + } + let targets: Vec<_> = editor + .query() + .blocks() + .filter(|view| view.attributes().is_some() && !requests.contains(view.target())) + .map(|view| view.target().clone()) + .collect(); + for target in &targets { + let id = editor.ensure_id(target)?.to_owned(); + assert_eq!(editor.ensure_id(target)?, id); + } + let query = editor.query(); + let observations: Vec<_> = query.blocks() + .filter(|view| !requests.contains(view.target())) + .map(|view| { + let title = view.title_source(); + serde_json::json!({ + "context": format!("{:?}", view.context()), + "id": view.output_id(), + "section": view.containing_section().and_then(|target| query.get(target)).and_then(|section| section.output_id()), + "raw_title": title.map(acdc_parser::extensions::TitleSource::raw_source), + "title_line": title.map(|title| title.source_location().location.start.line), + "substitutions": title.map(acdc_parser::extensions::TitleSource::substitutions), + "label": title.and_then(|title| title.attributes().get("label")).and_then(acdc_parser::DocumentAttributeValue::as_str), + "caption": view.caption().map(|caption| format!("{caption:?}")), + }) + }).collect(); + let text = serde_json::Value::Array(observations).to_string(); + for request in requests { + editor.replace_placeholder(&request, BlockBuilder::paragraph(text.clone()))?; + } + Ok(()) + } +} + pub(super) fn configure( invocation: &MacroInvocation<'_>, context: &mut acdc_parser::extensions::MacroExecutionContext, From 1b3150ec3ec37a9baaa262e8c54fc6ad35e201fc Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 14 Nov 2026 23:08:26 +0100 Subject: [PATCH 15/55] feat(parser): construct and replace extension blocks atomically Let tree processors generate image and verbatim output or replace retained source through parser builders. Normalize metadata in the target's source context while retaining its identity, title, and inherited attributes. Validate and repair a candidate before publishing edits so a failed edit leaves the document and counters intact. Preserve surviving numbers, advance new captions beyond used ordinals and local numeric seeds, and expose idempotent normalization without callbacks. Refs SC-538. --- acdc-parser/CHANGELOG.md | 9 + acdc-parser/README.adoc | 57 +- acdc-parser/README.md | 57 +- .../schemas/asg/support-inventory.json | 4 + acdc-parser/src/extensions/builder.rs | 176 +++++- acdc-parser/src/extensions/editor.rs | 251 +++----- .../src/extensions/editor/transaction.rs | 337 +++++++++++ acdc-parser/src/extensions/finalization.rs | 100 ++-- acdc-parser/src/extensions/mod.rs | 29 +- acdc-parser/src/extensions/query.rs | 21 +- acdc-parser/src/extensions/registry.rs | 6 +- acdc-parser/src/extensions/session.rs | 23 +- .../src/extensions/tests/construction.rs | 543 ++++++++++++++++++ acdc-parser/src/extensions/tests/mod.rs | 1 + acdc-parser/src/extensions/traversal.rs | 73 ++- acdc-parser/src/grammar/document.rs | 5 + acdc-parser/src/grammar/document/generated.rs | 332 +++++++++++ acdc-parser/src/grammar/document/metadata.rs | 42 ++ acdc-parser/src/grammar/mod.rs | 4 +- acdc-parser/src/grammar/state.rs | 23 + acdc-parser/src/model/caption.rs | 15 +- acdc-parser/src/model/metadata.rs | 3 + acdc-parser/src/parsed.rs | 11 + 23 files changed, 1841 insertions(+), 281 deletions(-) create mode 100644 acdc-parser/src/extensions/editor/transaction.rs create mode 100644 acdc-parser/src/extensions/tests/construction.rs create mode 100644 acdc-parser/src/grammar/document/generated.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 21631886d..604dc1e6b 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -200,6 +200,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Empty registries and unused registrations preserve ordinary diagnostic order. Edits repair references, TOC and scoped footnotes while preserving surviving section and caption numbers. + `BlockBuilder` also builds images, listings, and literal figures with normal + attribute lists, weak defaults, and explicit unsets. `replace_block()` keeps + the target handle and inherited metadata; `replace_source()` interprets retained + paragraph or verbatim source using its local attributes and substitutions. + New captions honor local numeric counter seeds and advance beyond existing and + removed ordinals; textual diagrams can opt into figure captions with + `with_caption_kind()`. Failed edits preserve + the visible document, handles, numbering, and diagnostics. `normalize()` repairs + catalogs idempotently without rerunning processors. Extension queries also expose raw title source, inline substitutions, original locations, and source-position document attributes through `BlockView::title_source()`, including attribute titles and titles that expand diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 27b0960b5..33c9c4027 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2084,19 +2084,58 @@ quote-dependent policy of attribute titles. `caption()` reads the host's resolve prefix and ordinal. Ordinary parser entry points retain no extension title snapshots. Queries and borrowed title views end before an edit or ID assignment; query again afterward to observe the repaired tree. Copied handle selections remain snapshots. -Document-local `TargetId` handles survive insertions and placeholder replacement; -removed handles cannot bind to another block. The scoped `DocumentEditor` builds -literal paragraphs and lists, assigns IDs, replaces requests, and removes sections. -Edits repair catalogs and scoped footnotes while preserving surviving section and -caption numbers. Generated text is literal and is not reparsed. +Document-local `TargetId` handles survive insertions and ordinary-block replacement; +removed handles cannot bind to another block. `DocumentEditor::replace_block()` +retains the target's handle, location, title, ID, roles, options, and reftext unless +overridden. Descendant handles and pending requests are removed. Sections have a +separate `remove_section()` operation. Tree processors run once in registration +order and observe earlier edits; copied selections and generated summaries remain +snapshots and are not rerun. + +`BlockBuilder` builds paragraphs, unordered lists, images, listings, and literal +blocks. Body strings remain literal and converters apply ordinary output escaping. +`with_attributes()` interprets one attribute-list line, without square brackets, +using the parser's rules and the target's source-position document attributes. +`with_default_attributes()` supplies weak defaults; inherited metadata then explicit +lists take precedence. Positional/named attributes, quote-dependent substitutions, +empty values, titles, roles, options, and content-bearing attributes use ordinary +normalization. `without_attribute()` removes selected inherited/default metadata; +`with_id()` supplies the final explicit ID. Image replacements retain existing alt +content unless explicitly overridden. No constructor runs block grammar or callbacks. +`replace_source()` explicitly interprets a paragraph or listing/literal body with +its captured attributes and `subs=` settings. Raw source, parsed inline content, +and rendered output are separate views; extensions need no arena allocation or +whole-document reparse. + +Successful edits repair references, TOC, scoped footnotes, and unresolved/duplicate +ID warnings before returning. Other parse and construction warnings retain their +order; repair refreshes only reference-related warnings. Validation or repair +errors leave the visible tree, handles, assigned numbers, and diagnostics unchanged. Explicit duplicate IDs are +rejected; duplicate IDs inside interpreted inline content produce warnings. +Surviving section/caption numbers and custom, formatted, or disabled captions stay +unchanged. New numbered captions advance beyond the highest original or generated +ordinal, including removed figures, using the target's source-position caption label. +Numeric `-number` seeds at that position provide a lower bound; a later reset +cannot reuse an assigned ordinal. Counter expressions in literal builder bodies +remain literal. Use `with_caption_kind(CaptionKind::Figure)` for textual diagrams. A title that +expands to empty content still receives a number. Direct HTML comparisons with +Asciidoctor 2.0.26 confirm surviving numbers after section removal. Its tree-processor +image helper can reuse lower numbers after body counter state is restored; acdc's +monotonic allocation is an intentional policy that avoids those collisions. + ID assignment preserves authored IDs, avoids registered targets and unresolved reference names, and reuses assigned IDs. Identical conversions produce the same IDs regardless of request order; IDs need not remain stable across document edits. -Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used -for conversion or serialization. It rejects unresolved deferred requests at their -source locations. See the `extensions` module documentation for registration and -processor examples. An empty registry uses the ordinary parser path. +The working `ExtensionParseResult` retains processors, handles, and pending +requests. `normalize()` repeats catalog repair idempotently without callbacks or +renumbering. `finish()` consumes the working session and returns the ordinary +`ParseResult` used for conversion or serialization; unresolved requests return a +located error. Checked ASG export also rejects pending blocks in either profile. +Earlier successful edits and external callback effects remain if a later processor +fails; a processor sequence is not a transaction. See the `extensions` module +documentation for registration and processor examples. An empty registry uses the +ordinary parser path. [#parser-fixtures] == Parser fixtures diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 03792f7e4..7290f89e8 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1728,19 +1728,58 @@ quote-dependent policy of attribute titles. `caption()` reads the host's resolve prefix and ordinal. Ordinary parser entry points retain no extension title snapshots. Queries and borrowed title views end before an edit or ID assignment; query again afterward to observe the repaired tree. Copied handle selections remain snapshots. -Document-local `TargetId` handles survive insertions and placeholder replacement; -removed handles cannot bind to another block. The scoped `DocumentEditor` builds -literal paragraphs and lists, assigns IDs, replaces requests, and removes sections. -Edits repair catalogs and scoped footnotes while preserving surviving section and -caption numbers. Generated text is literal and is not reparsed. +Document-local `TargetId` handles survive insertions and ordinary-block replacement; +removed handles cannot bind to another block. `DocumentEditor::replace_block()` +retains the target's handle, location, title, ID, roles, options, and reftext unless +overridden. Descendant handles and pending requests are removed. Sections have a +separate `remove_section()` operation. Tree processors run once in registration +order and observe earlier edits; copied selections and generated summaries remain +snapshots and are not rerun. + +`BlockBuilder` builds paragraphs, unordered lists, images, listings, and literal +blocks. Body strings remain literal and converters apply ordinary output escaping. +`with_attributes()` interprets one attribute-list line, without square brackets, +using the parser's rules and the target's source-position document attributes. +`with_default_attributes()` supplies weak defaults; inherited metadata then explicit +lists take precedence. Positional/named attributes, quote-dependent substitutions, +empty values, titles, roles, options, and content-bearing attributes use ordinary +normalization. `without_attribute()` removes selected inherited/default metadata; +`with_id()` supplies the final explicit ID. Image replacements retain existing alt +content unless explicitly overridden. No constructor runs block grammar or callbacks. +`replace_source()` explicitly interprets a paragraph or listing/literal body with +its captured attributes and `subs=` settings. Raw source, parsed inline content, +and rendered output are separate views; extensions need no arena allocation or +whole-document reparse. + +Successful edits repair references, TOC, scoped footnotes, and unresolved/duplicate +ID warnings before returning. Other parse and construction warnings retain their +order; repair refreshes only reference-related warnings. Validation or repair +errors leave the visible tree, handles, assigned numbers, and diagnostics unchanged. Explicit duplicate IDs are +rejected; duplicate IDs inside interpreted inline content produce warnings. +Surviving section/caption numbers and custom, formatted, or disabled captions stay +unchanged. New numbered captions advance beyond the highest original or generated +ordinal, including removed figures, using the target's source-position caption label. +Numeric `-number` seeds at that position provide a lower bound; a later reset +cannot reuse an assigned ordinal. Counter expressions in literal builder bodies +remain literal. Use `with_caption_kind(CaptionKind::Figure)` for textual diagrams. A title that +expands to empty content still receives a number. Direct HTML comparisons with +Asciidoctor 2.0.26 confirm surviving numbers after section removal. Its tree-processor +image helper can reuse lower numbers after body counter state is restored; acdc's +monotonic allocation is an intentional policy that avoids those collisions. + ID assignment preserves authored IDs, avoids registered targets and unresolved reference names, and reuses assigned IDs. Identical conversions produce the same IDs regardless of request order; IDs need not remain stable across document edits. -Call `ExtensionParseResult::finish()` to obtain the ordinary `ParseResult` used -for conversion or serialization. It rejects unresolved deferred requests at their -source locations. See the `extensions` module documentation for registration and -processor examples. An empty registry uses the ordinary parser path. +The working `ExtensionParseResult` retains processors, handles, and pending +requests. `normalize()` repeats catalog repair idempotently without callbacks or +renumbering. `finish()` consumes the working session and returns the ordinary +`ParseResult` used for conversion or serialization; unresolved requests return a +located error. Checked ASG export also rejects pending blocks in either profile. +Earlier successful edits and external callback effects remain if a later processor +fails; a processor sequence is not a transaction. See the `extensions` module +documentation for registration and processor examples. An empty registry uses the +ordinary parser path. ## Parser fixtures diff --git a/acdc-parser/schemas/asg/support-inventory.json b/acdc-parser/schemas/asg/support-inventory.json index dbf951a6f..5b23b5ac3 100644 --- a/acdc-parser/schemas/asg/support-inventory.json +++ b/acdc-parser/schemas/asg/support-inventory.json @@ -3635,6 +3635,7 @@ "shape": { "kind": "struct", "fields": [ + "source_context", "attribute_positions", "prefix_events", "caption", @@ -3662,6 +3663,9 @@ "upstream": "#/$defs/blockMetadata" }, "properties": { + "source_context": { + "policy": "source-state" + }, "attribute_positions": { "policy": "source-state" }, diff --git a/acdc-parser/src/extensions/builder.rs b/acdc-parser/src/extensions/builder.rs index 37fe220ad..de4d7e82f 100644 --- a/acdc-parser/src/extensions/builder.rs +++ b/acdc-parser/src/extensions/builder.rs @@ -1,51 +1,151 @@ +use std::sync::Arc; + use bumpalo::Bump; use crate::{ - Anchor, Block, BlockMetadata, CaptionKind, InlineNode, ListItem, Location, Paragraph, Plain, - Title, UnorderedList, + Anchor, Block, BlockMetadata, CaptionKind, CompatibilityMode, DelimitedBlock, + DelimitedBlockType, DocumentAttributes, Image, InlineNode, ListItem, Location, Paragraph, + Plain, Source, Title, UnorderedList, Verbatim, }; +#[derive(Clone, Debug)] +pub(crate) struct SourceContext<'a> { + pub(crate) attributes: DocumentAttributes<'a>, + pub(crate) mode: CompatibilityMode, +} + +impl<'a> SourceContext<'a> { + pub(crate) fn capture(state: &crate::grammar::ParserState<'a>) -> Option> { + if !state.options.extensions.as_ref()?.has_tree_processors() { + return None; + } + Some(Arc::new(Self { + attributes: state.document_attributes.as_ref().clone(), + mode: state.options.compatibility_mode, + })) + } +} + /// Ordinary content whose strings are allocated by the document host. /// -/// Text is literal. Converters apply the block's normal output policies. -/// Construction does not invoke inline parsing, attribute substitution, or -/// extension callbacks. -#[derive(Debug)] +/// Body text is literal. Converters apply the block's normal output policies. +/// Attribute lists use ordinary metadata interpretation and source-position +/// substitutions. Construction never invokes block grammar or callbacks. +#[derive(Clone, Debug)] pub struct BlockBuilder { - content: Content, + pub(crate) content: Content, pub(super) id: Option, + pub(crate) attributes: Vec, + pub(crate) defaults: Option, + pub(crate) unsets: Vec, + caption: Option, + pub(crate) source_body: bool, } -#[derive(Debug)] -enum Content { +#[derive(Clone, Debug)] +pub(crate) enum Content { Paragraph(String), UnorderedList(Vec), + Image(String), + Literal(String), + Listing(String), } impl BlockBuilder { + pub(crate) fn is_image(&self) -> bool { + matches!(self.content, Content::Image(_)) + } + pub(crate) fn is_verbatim(&self) -> bool { + matches!(self.content, Content::Literal(_) | Content::Listing(_)) + } + pub(crate) fn is_listing(&self) -> bool { + matches!(self.content, Content::Listing(_)) + } pub(super) fn caption_kind(&self, style: Option<&str>) -> Option { + if self.caption.is_some() { + return self.caption; + } match &self.content { Content::Paragraph(_) => CaptionKind::for_style(style), + Content::Image(_) => Some(CaptionKind::Figure), + Content::Listing(_) => CaptionKind::for_verbatim(style, Some(CaptionKind::Listing)), + Content::Literal(_) => CaptionKind::for_verbatim(style, None), Content::UnorderedList(_) => None, } } - /// Build a paragraph of literal text. - #[must_use] - pub fn paragraph(text: impl Into) -> Self { + fn new(content: Content) -> Self { Self { - content: Content::Paragraph(text.into()), + content, id: None, + attributes: Vec::new(), + defaults: None, + unsets: Vec::new(), + caption: None, + source_body: false, } } + /// Build a paragraph of literal text. + #[must_use] + pub fn paragraph(text: impl Into) -> Self { + Self::new(Content::Paragraph(text.into())) + } + /// Build an unordered list whose items contain literal text. #[must_use] pub fn unordered_list(items: impl IntoIterator>) -> Self { - Self { - content: Content::UnorderedList(items.into_iter().map(Into::into).collect()), - id: None, - } + Self::new(Content::UnorderedList( + items.into_iter().map(Into::into).collect(), + )) + } + + /// Build an ordinary image without interpreting its target as markup. + #[must_use] + pub fn image(target: impl Into) -> Self { + Self::new(Content::Image(target.into())) + } + + /// Build literal text, preserving whitespace and markup characters. + #[must_use] + pub fn literal(text: impl Into) -> Self { + Self::new(Content::Literal(text.into())) + } + + /// Build listing text, preserving whitespace and markup characters. + #[must_use] + pub fn listing(text: impl Into) -> Self { + Self::new(Content::Listing(text.into())) + } + + /// Interpret an attribute list through the parser's ordinary attribute rules. + /// Supply the list contents without square brackets. This interprets metadata, + /// not the generated body, and never invokes block processors. + #[must_use] + pub fn with_attributes(mut self, source: impl Into) -> Self { + self.attributes.push(source.into()); + self + } + + /// Supply weak attribute defaults. Inherited and explicit attributes take precedence. + #[must_use] + pub fn with_default_attributes(mut self, source: impl Into) -> Self { + self.defaults = Some(source.into()); + self + } + + /// Remove an inherited or default attribute, including dedicated metadata. + #[must_use] + pub fn without_attribute(mut self, name: impl Into) -> Self { + self.unsets.push(name.into()); + self + } + + /// Request a host caption category, including for textual diagram output. + #[must_use] + pub fn with_caption_kind(mut self, kind: CaptionKind) -> Self { + self.caption = Some(kind); + self } /// Request an explicit output ID. The editor rejects empty or duplicate IDs. @@ -61,7 +161,7 @@ impl BlockBuilder { location: Location, mut metadata: BlockMetadata<'a>, title: Title<'a>, - ) -> Block<'a> { + ) -> Result, crate::Error> { if let Some(id) = self.id { metadata.id = Some(Anchor::new(arena.alloc_str(&id), location.clone())); } @@ -72,7 +172,7 @@ impl BlockBuilder { escaped: true, })] }; - match self.content { + Ok(match self.content { Content::Paragraph(text) => { let mut block = Paragraph::new(plain(&text), location); block.metadata = metadata; @@ -96,6 +196,42 @@ impl BlockBuilder { marker: "*", location, }), - } + Content::Image(target) => Block::Image(Image { + source: Source::from_str_borrowed(arena.alloc_str(&target))?, + alt: None, + title, + metadata, + location, + }), + Content::Literal(text) => { + build_verbatim(arena, &text, false, location, metadata, title) + } + Content::Listing(text) => build_verbatim(arena, &text, true, location, metadata, title), + }) } } + +fn build_verbatim<'a>( + arena: &'a Bump, + text: &str, + listing: bool, + location: Location, + metadata: BlockMetadata<'a>, + title: Title<'a>, +) -> Block<'a> { + let text = arena.alloc_str(text); + let nodes = vec![InlineNode::VerbatimText(Verbatim::new( + text, + location.clone(), + ))]; + let inner = if listing { + DelimitedBlockType::DelimitedListing(nodes) + } else { + DelimitedBlockType::DelimitedLiteral(nodes) + }; + let mut block = DelimitedBlock::new(inner, if listing { "----" } else { "...." }, location); + block.metadata = metadata; + block.title = title; + block.source_text = Some(text); + Block::DelimitedBlock(block) +} diff --git a/acdc-parser/src/extensions/editor.rs b/acdc-parser/src/extensions/editor.rs index dc98e1293..a3e1ef1f0 100644 --- a/acdc-parser/src/extensions/editor.rs +++ b/acdc-parser/src/extensions/editor.rs @@ -1,15 +1,14 @@ -use crate::{Block, BlockMetadata, Caption, Error, SourceLocation, Title}; - use super::{ BlockBuilder, DeferredBlock, DocumentQuery, ExtensionParseResult, TargetId, traversal::BlockPath, }; +use crate::{Block, Error, SourceLocation}; +mod transaction; +use transaction::Edit; -/// Scoped access to queries, builders, and checked structural edits. -/// -/// Every edit repairs catalogs before the next query. Surviving targets keep -/// their handles and section/caption numbers; removed handles never become live -/// again, even if a new block uses the same output ID. Footnotes are compacted. +/// Scoped queries and checked edits. Successful edits repair catalogs before the +/// next observation. Validation and repair failures preserve the tree, handles, +/// assigned numbers, and diagnostics. Surviving targets retain their identity. pub struct DocumentEditor<'doc> { result: &'doc mut ExtensionParseResult, } @@ -18,24 +17,21 @@ impl<'doc> DocumentEditor<'doc> { pub(super) const fn new(result: &'doc mut ExtensionParseResult) -> Self { Self { result } } - #[must_use] pub fn query(&self) -> DocumentQuery<'_> { self.result.query() } - #[cfg(test)] pub(super) fn document_storage(&self) -> &crate::Document<'_> { self.result.parsed.document_storage() } - - /// Pending requests whose placeholders are still in the document. + /// Pending requests whose placeholders remain in the document. #[must_use] pub fn deferred_blocks(&self) -> &[DeferredBlock] { self.result.deferred_blocks() } - /// Assign or return an output ID without changing block identity or numbering. + /// Return or assign an output ID without changing identity or numbering. /// /// # Errors /// Rejects foreign, removed, or unreferenceable targets. @@ -45,203 +41,104 @@ impl<'doc> DocumentEditor<'doc> { .ensure_id(target) .map_err(|error| Error::Extension(Box::new(location), error.to_string())) } - - /// Insert ordinary content immediately before a target in its own container. - /// - /// The new block uses the target's source location and receives a new handle. + /// Insert content before an ordinary block or section in its own container, + /// with a new handle. + /// The target supplies its location and source-position attribute context. /// /// # Errors - /// Rejects foreign/removed targets and empty or duplicate requested IDs. + /// Rejects foreign/removed targets, comments, attribute events, invalid + /// metadata, and duplicate IDs. pub fn insert_before( &mut self, target: &TargetId, content: BlockBuilder, ) -> Result { - let path = self.path(target)?; - self.validate_id(target, &content, false)?; - self.prepare_edit(); - let location = self.location(target); - self.result.parsed.with_document_mut(|owner, document| { - let block = content.build( - &owner.arena, - location.location.clone(), - BlockMetadata::default(), - Title::default(), - ); - let (blocks, position) = path.container_mut(&mut document.blocks).ok_or_else(|| { - Error::Extension(Box::new(location.clone()), "target is absent".into()) - })?; - blocks.insert(position, block); - Ok::<(), Error>(()) - })?; - let new_target = self - .result - .targets - .get_mut() - .and_then(|index| index.insert_before(target)) - .ok_or_else(|| self.error(target, "target is absent"))?; - self.result.repair_after_edit()?; - Ok(new_target) + self.apply(target, &Edit::Insert(content)) } - - /// Replace a pending placeholder, retaining its handle, source, title, and metadata. - /// A builder-supplied ID overrides the placeholder's ID. + /// Replace an ordinary block, retaining its handle, location, title, and + /// metadata unless overridden. Descendant handles and requests are removed. /// - /// The request is consumed. The replacement invokes no parsing or callbacks. + /// # Errors + /// Rejects foreign/removed targets, sections, attribute events, and invalid content. + pub fn replace_block(&mut self, target: &TargetId, content: BlockBuilder) -> Result<(), Error> { + self.apply(target, &Edit::Replace(content)).map(|_| ()) + } + /// Replace a pending placeholder through the shared construction and repair path. /// /// # Errors - /// Rejects targets that are not pending placeholders and invalid requested IDs. + /// Rejects nonpending, foreign, or removed targets and invalid content. pub fn replace_placeholder( &mut self, target: &TargetId, content: BlockBuilder, ) -> Result<(), Error> { - let path = self.path(target)?; - if !self - .result - .deferred_blocks() - .iter() - .any(|request| request.target() == target) - { - return Err(self.error(target, "target is not a pending placeholder")); - } - self.validate_id(target, &content, true)?; - self.prepare_edit(); - let caption_kind = self + self.pending(target)?; + self.replace_block(target, content) + } + /// Replace retained paragraph or listing/literal source. Inline substitutions + /// use the captured context and `subs=`. No block grammar or callbacks run. + /// + /// # Errors + /// Rejects unsupported, foreign, or removed targets and invalid inline content. + pub fn replace_source( + &mut self, + target: &TargetId, + source: impl Into, + ) -> Result<(), Error> { + let source = source.into(); + let view = self .query() .get(target) - .and_then(|view| view.storage().metadata()) - .and_then(|metadata| content.caption_kind(metadata.style)); - let numbered_kind = caption_kind.filter(|kind| { - self.query().get(target).is_some_and(|view| { - let Block::Extension(extension) = view.storage() else { - return false; - }; - !extension.title.is_empty() - && matches!( - Caption::resolve( - &extension.metadata, - &extension.invocation.document_attributes, - *kind - ), - Caption::Numbered { .. } - ) - }) - }); - let caption_number = - numbered_kind.and_then(|kind| self.result.targets.get_mut()?.next_caption(kind)); - let location = self.location(target); - self.result.parsed.with_document_mut(|owner, document| { - let block = path.get_mut(&mut document.blocks).ok_or_else(|| { - Error::Extension(Box::new(location.clone()), "target is absent".into()) - })?; - let Block::Extension(extension) = block else { - return Err(Error::Extension( - Box::new(location.clone()), - "target is not a placeholder".into(), - )); - }; - let mut metadata = std::mem::take(&mut extension.metadata); - if let Some(kind) = caption_kind { - metadata.caption = Some(Caption::resolve( - &metadata, - &extension.invocation.document_attributes, - kind, - )); - if let Some(Caption::Numbered { number, .. }) = &mut metadata.caption { - *number = caption_number; - } + .ok_or_else(|| self.error(target, "target is absent"))?; + let mut builder = if matches!(view.storage(), Block::Paragraph(_)) { + BlockBuilder::paragraph(source) + } else if let Block::DelimitedBlock(block) = view.storage() { + if matches!(block.inner, crate::DelimitedBlockType::DelimitedListing(_)) { + BlockBuilder::listing(source) + } else if matches!(block.inner, crate::DelimitedBlockType::DelimitedLiteral(_)) { + BlockBuilder::literal(source) + } else { + return Err(self.error(target, "target has no replaceable inline source body")); } - let title = std::mem::take(&mut extension.title); - *block = content.build(&owner.arena, extension.location.clone(), metadata, title); - Ok(()) - })?; - self.result - .session - .deferred - .retain(|request| request.target() != target); - self.result.repair_after_edit() + } else { + return Err(self.error(target, "target has no replaceable inline source body")); + }; + builder.source_body = true; + self.replace_block(target, builder) } - - /// Remove a section and its entire subtree, including pending placeholders. - /// - /// The host applies no empty-section policy; the processor decides what to remove. + /// Remove a section and its subtree without selecting an empty-section policy. /// /// # Errors /// Rejects foreign/removed targets and targets that are not sections. pub fn remove_section(&mut self, target: &TargetId) -> Result<(), Error> { - let path = self.path(target)?; - if !matches!( - path.get(&self.result.parsed.document_storage().blocks), - Some(Block::Section(_)) - ) { + if !self + .query() + .get(target) + .is_some_and(|view| matches!(view.storage(), Block::Section(_))) + { return Err(self.error(target, "target is not a section")); } - self.remove(target, &path) + self.apply(target, &Edit::Remove).map(|_| ()) } - /// Remove a pending placeholder and consume its request. /// /// # Errors - /// Rejects targets that are not pending placeholders. + /// Rejects nonpending, foreign, or removed targets. pub fn discard_placeholder(&mut self, target: &TargetId) -> Result<(), Error> { - let path = self.path(target)?; - if !self - .result + self.pending(target)?; + self.apply(target, &Edit::Remove).map(|_| ()) + } + fn pending(&self, target: &TargetId) -> Result<(), Error> { + if self .deferred_blocks() .iter() .any(|request| request.target() == target) { - return Err(self.error(target, "target is not a pending placeholder")); - } - self.remove(target, &path) - } - - fn remove(&mut self, target: &TargetId, path: &BlockPath) -> Result<(), Error> { - self.prepare_edit(); - let location = self.location(target); - self.result.parsed.with_document_mut(|_, document| { - let (blocks, position) = path.container_mut(&mut document.blocks).ok_or_else(|| { - Error::Extension(Box::new(location.clone()), "target is absent".into()) - })?; - blocks.remove(position); - Ok::<(), Error>(()) - })?; - if let Some(index) = self.result.targets.get_mut() { - index.remove(target); - self.result - .session - .deferred - .retain(|request| index.entry(request.target()).is_some()); - } - self.result.repair_after_edit() - } - - fn validate_id( - &self, - target: &TargetId, - content: &BlockBuilder, - replacing: bool, - ) -> Result<(), Error> { - if let Some(id) = &content.id { - if id.is_empty() { - return Err(self.error(target, "output ID must not be empty")); - } - let current = self.query().get(target).and_then(|view| view.output_id()); - if self - .result - .parsed - .document_storage() - .references - .contains_key(id.as_str()) - && !(replacing && current == Some(id.as_str())) - { - return Err(self.error(target, &format!("output ID is already in use: {id}"))); - } + Ok(()) + } else { + Err(self.error(target, "target is not a pending placeholder")) } - Ok(()) } - fn path(&self, target: &TargetId) -> Result { self.result .target_index() @@ -254,15 +151,6 @@ impl<'doc> DocumentEditor<'doc> { ) }) } - - fn prepare_edit(&mut self) { - if let Some(index) = self.result.targets.get_mut() { - self.result - .parsed - .with_document_mut(|_, document| index.prepare_edit(document)); - } - } - fn location(&self, target: &TargetId) -> SourceLocation { self.query().get(target).map_or_else( || { @@ -273,7 +161,6 @@ impl<'doc> DocumentEditor<'doc> { |view| view.source_location(), ) } - fn error(&self, target: &TargetId, message: &str) -> Error { Error::Extension(Box::new(self.location(target)), message.to_owned()) } diff --git a/acdc-parser/src/extensions/editor/transaction.rs b/acdc-parser/src/extensions/editor/transaction.rs new file mode 100644 index 000000000..4c2a8fb25 --- /dev/null +++ b/acdc-parser/src/extensions/editor/transaction.rs @@ -0,0 +1,337 @@ +use super::super::{ + BlockBuilder, SourceContext, TargetId, + finalization::repair_document, + query::{TargetIndex, output_id}, + traversal::{BlockPath, highest_footnote}, +}; +use super::DocumentEditor; +use crate::{ + Block, BlockMetadata, Caption, Document, Error, SourceLocation, Title, Warning, + grammar::GeneratedContext, parsed::OwnedInput, +}; + +pub(super) enum Edit { + Insert(BlockBuilder), + Replace(BlockBuilder), + Remove, +} + +impl DocumentEditor<'_> { + pub(super) fn apply(&mut self, target: &TargetId, edit: &Edit) -> Result { + let path = self.path(target)?; + let origin = self.location(target); + let mode = self.result.mode; + let index = self + .result + .targets + .get_mut() + .ok_or_else(|| failure(&origin, "query index is absent"))?; + let (new_target, reference_warnings, construction_warnings) = + self.result.parsed.with_document_mut(|owner, document| { + let prepared = prepare(owner, document, &path, edit, mode, &origin)?; + let mut candidate = snapshot(document); + let mut candidate_index = index.clone(); + candidate_index.prepare_edit(&mut candidate); + let outcome = transact( + &mut candidate, + &mut candidate_index, + target, + &path, + edit, + prepared, + &origin, + )?; + *document = candidate; + *index = candidate_index; + Ok::<_, Error>(outcome) + })?; + self.result.session.deferred.retain(|request| { + index + .entry(request.target()) + .and_then(|entry| { + entry + .path + .get(&self.result.parsed.document_storage().blocks) + }) + .is_some_and(|block| matches!(block, Block::Extension(_))) + }); + self.result + .parsed + .replace_reference_warnings(reference_warnings); + self.result + .parsed + .append_extension_warnings(construction_warnings); + index.reserve_warnings(&self.result.parsed); + Ok(new_target) + } +} + +fn snapshot<'a>(document: &Document<'a>) -> Document<'a> { + Document { + header: document.header.clone(), + untitled_header_location: document.untitled_header_location.clone(), + attributes: document.attributes.clone(), + blocks: document.blocks.clone(), + footnotes: document.footnotes.clone(), + toc_entries: document.toc_entries.clone(), + references: document.references.clone(), + location: document.location.clone(), + } +} + +struct Prepared<'a> { + block: Block<'a>, + kind: Option, + warnings: Vec, + recaption: bool, +} + +fn prepare<'a>( + owner: &'a OwnedInput, + document: &Document<'a>, + path: &BlockPath, + edit: &Edit, + mode: crate::CompatibilityMode, + origin: &SourceLocation, +) -> Result>, Error> { + let (builder, replacing) = match edit { + Edit::Insert(builder) => (builder, false), + Edit::Replace(builder) => (builder, true), + Edit::Remove => return Ok(None), + }; + let original = path + .get(&document.blocks) + .ok_or_else(|| failure(origin, "target is absent"))?; + if original.metadata().is_none() { + return Err(failure(origin, "target has no block construction context")); + } + if replacing && matches!(original, Block::Section(_)) { + return Err(failure( + origin, + "target is not a replaceable ordinary block", + )); + } + if builder.id.as_deref() == Some("") { + return Err(failure(origin, "output ID must not be empty")); + } + let context = original + .metadata() + .and_then(|metadata| metadata.source_context.as_deref()) + .cloned() + .unwrap_or_else(|| SourceContext { + attributes: document.attributes.clone(), + mode, + }); + let inline_context = GeneratedContext { + source: &context, + footnotes: path.footnotes(document), + next_footnote: highest_footnote(document) + .checked_add(1) + .ok_or_else(|| failure(origin, "too many footnotes"))?, + }; + if builder.source_body { + return prepare_source(owner, original, builder, &inline_context, origin).map(Some); + } + let mut inherited = if replacing { + original.metadata().cloned().unwrap_or_default() + } else { + BlockMetadata::default() + }; + inherited.attribute_positions = None; + inherited.positional_attributes.clear(); + inherited.reftext_source = None; + inherited.prefix_events = None; + let title = if replacing { + original.title().cloned().unwrap_or_default() + } else { + Title::default() + }; + let mut attributes = crate::grammar::prepare_generated( + &owner.arena, + builder, + inherited, + title, + &inline_context, + origin, + )?; + attributes.metadata.source_context = Some(std::sync::Arc::new(context)); + let kind = builder.caption_kind(attributes.metadata.style); + let id = builder + .id + .as_deref() + .or_else(|| attributes.metadata.id_anchor().map(|anchor| anchor.id)); + check_id(document, original, id, replacing, origin)?; + let mut block = builder + .clone() + .build( + &owner.arena, + origin.location.clone(), + attributes.metadata, + attributes.title, + ) + .map_err(|error| failure(origin, &error.to_string()))?; + if let Block::Image(image) = &mut block { + let inherited_alt = if replacing { + if let Block::Image(image) = original { + image.alt.clone() + } else { + None + } + } else { + None + }; + image.alt = if attributes.explicit_alt { + attributes.alt + } else { + inherited_alt.or(attributes.alt) + }; + } + Ok(Some(Prepared { + block, + kind, + warnings: attributes.warnings, + recaption: true, + })) +} + +fn check_id( + document: &Document<'_>, + original: &Block<'_>, + id: Option<&str>, + replacing: bool, + origin: &SourceLocation, +) -> Result<(), Error> { + let Some(id) = id else { + return Ok(()); + }; + if id.is_empty() { + return Err(failure(origin, "output ID must not be empty")); + } + if document.references.contains_key(id) && !(replacing && output_id(original) == Some(id)) { + return Err(failure( + origin, + &format!("output ID is already in use: {id}"), + )); + } + Ok(()) +} + +fn prepare_source<'a>( + owner: &'a OwnedInput, + original: &Block<'a>, + builder: &BlockBuilder, + context: &GeneratedContext<'_, 'a>, + origin: &SourceLocation, +) -> Result, Error> { + let source = match &builder.content { + super::super::builder::Content::Paragraph(source) + | super::super::builder::Content::Literal(source) + | super::super::builder::Content::Listing(source) => owner.arena.alloc_str(source), + super::super::builder::Content::Image(_) + | super::super::builder::Content::UnorderedList(_) => { + return Err(failure(origin, "source body is unsupported")); + } + }; + let mut block = original.clone(); + if let Some(metadata) = block.metadata_mut() { + metadata.source_context = Some(std::sync::Arc::new(context.source.clone())); + } + let warnings = + crate::grammar::replace_generated_source(&owner.arena, &mut block, source, context, origin) + .map_err(|error| failure(origin, &error.to_string()))?; + Ok(Prepared { + block, + kind: None, + warnings, + recaption: false, + }) +} + +type Outcome = (TargetId, Vec, Vec); + +fn transact<'a>( + document: &mut Document<'a>, + index: &mut TargetIndex, + target: &TargetId, + path: &BlockPath, + edit: &Edit, + mut prepared: Option>, + origin: &SourceLocation, +) -> Result { + if let Some(prepared) = &mut prepared + && prepared.recaption + { + caption(&mut prepared.block, prepared.kind, index, origin)?; + } + let (blocks, position) = path + .container_mut(&mut document.blocks) + .ok_or_else(|| failure(origin, "target container is absent"))?; + let warnings = prepared + .as_mut() + .map_or_else(Vec::new, |prepared| std::mem::take(&mut prepared.warnings)); + let handle = match edit { + Edit::Insert(_) => { + blocks.insert( + position, + prepared + .ok_or_else(|| failure(origin, "construction is absent"))? + .block, + ); + index + .insert_before(target) + .ok_or_else(|| failure(origin, "target is absent"))? + } + Edit::Replace(_) => { + *blocks + .get_mut(position) + .ok_or_else(|| failure(origin, "target is absent"))? = prepared + .ok_or_else(|| failure(origin, "construction is absent"))? + .block; + index.replace(target); + target.clone() + } + Edit::Remove => { + blocks.remove(position); + index.remove(target); + target.clone() + } + }; + Ok((handle, repair_document(document, Some(index))?, warnings)) +} + +fn caption( + block: &mut Block<'_>, + kind: Option, + index: &mut TargetIndex, + origin: &SourceLocation, +) -> Result<(), Error> { + let titled = block.title().is_some(); + let Some(metadata) = block.metadata_mut() else { + return Ok(()); + }; + let Some(kind) = kind else { + return Ok(()); + }; + if matches!(metadata.caption, Some(Caption::Numbered { kind: previous, number, .. }) if previous == kind && (number.is_some() || !titled)) + { + return Ok(()); + } + let Some(context) = &metadata.source_context else { + return Ok(()); + }; + metadata.caption = Some(Caption::resolve(metadata, &context.attributes, kind)); + if let Some(Caption::Numbered { number, .. }) = &mut metadata.caption + && titled + { + *number = Some( + index + .next_caption(kind, kind.source_counter(&context.attributes)) + .ok_or_else(|| failure(origin, "caption counter overflow"))?, + ); + } + Ok(()) +} + +fn failure(origin: &SourceLocation, message: &str) -> Error { + Error::Extension(Box::new(origin.clone()), message.into()) +} diff --git a/acdc-parser/src/extensions/finalization.rs b/acdc-parser/src/extensions/finalization.rs index d8e7c8e55..9a2925cae 100644 --- a/acdc-parser/src/extensions/finalization.rs +++ b/acdc-parser/src/extensions/finalization.rs @@ -13,15 +13,13 @@ struct Uses<'a> { impl<'a> Uses<'a> { fn register(&mut self, id: &'a str, location: &crate::Location) { if let Some(first) = self.seen.get(id) { - if first != location { - self.warnings.push(Warning::new( - WarningKind::DuplicateId { - id: id.into(), - first: Box::new(crate::SourceLocation::at_location(None, first.clone())), - }, - Some(crate::SourceLocation::at_location(None, location.clone())), - )); - } + self.warnings.push(Warning::new( + WarningKind::DuplicateId { + id: id.into(), + first: Box::new(crate::SourceLocation::at_location(None, first.clone())), + }, + Some(crate::SourceLocation::at_location(None, location.clone())), + )); } else { self.seen.insert(id, location.clone()); } @@ -61,45 +59,7 @@ impl<'a> ReferenceVisitor<'a> for Uses<'a> { impl ExtensionParseResult { pub(super) fn repair_after_edit(&mut self) -> Result<(), Error> { let warnings = self.parsed.with_document_mut(|_, document| { - document - .rebuild_footnotes() - .map_err(|error| failure(document, error))?; - document - .rebuild_extension_references() - .map_err(|error| failure(document, error))?; - if let Some(index) = self.targets.get() { - index.repair_section_references(document); - } - let mut uses = Uses::default(); - if let Some(header) = &document.header { - reference_walk::header(&mut uses, header).unwrap_or_else(|never| match never {}); - } - reference_walk::blocks(&mut uses, &mut document.blocks, true) - .unwrap_or_else(|never| match never {}); - crate::grammar::walk_document_inline_nodes_mut(document, &mut |inline| { - if let crate::InlineNode::Macro(crate::InlineMacro::CrossReference(reference)) = - inline - && (reference.target_is_local - || reference.source_syntax.target_is_local(reference.target)) - { - uses.xrefs - .push((reference.target, reference.location.clone())); - } - }); - uses.warnings.extend( - uses.xrefs - .into_iter() - .filter(|(target, _)| !document.references.contains_key(target)) - .map(|(target, location)| { - Warning::new( - WarningKind::UnresolvedReference { - target: target.into(), - }, - Some(crate::SourceLocation::at_location(None, location)), - ) - }), - ); - Ok::<_, Error>(uses.warnings) + repair_document(document, self.targets.get().map(Box::as_ref)) })?; self.parsed.replace_reference_warnings(warnings); if let Some(index) = self.targets.get_mut() { @@ -109,6 +69,50 @@ impl ExtensionParseResult { } } +pub(super) fn repair_document( + document: &mut crate::Document<'_>, + index: Option<&super::query::TargetIndex>, +) -> Result, Error> { + document + .rebuild_footnotes() + .map_err(|error| failure(document, error))?; + document + .rebuild_extension_references() + .map_err(|error| failure(document, error))?; + if let Some(index) = index { + index.repair_section_references(document); + } + let mut uses = Uses::default(); + if let Some(header) = &document.header { + reference_walk::header(&mut uses, header).unwrap_or_else(|never| match never {}); + } + reference_walk::blocks(&mut uses, &mut document.blocks, true) + .unwrap_or_else(|never| match never {}); + crate::grammar::walk_document_inline_nodes_mut(document, &mut |inline| { + if let crate::InlineNode::Macro(crate::InlineMacro::CrossReference(reference)) = inline + && (reference.target_is_local + || reference.source_syntax.target_is_local(reference.target)) + { + uses.xrefs + .push((reference.target, reference.location.clone())); + } + }); + uses.warnings.extend( + uses.xrefs + .into_iter() + .filter(|(target, _)| !document.references.contains_key(target)) + .map(|(target, location)| { + Warning::new( + WarningKind::UnresolvedReference { + target: target.into(), + }, + Some(crate::SourceLocation::at_location(None, location)), + ) + }), + ); + Ok::<_, Error>(uses.warnings) +} + fn failure(document: &crate::Document<'_>, error: impl std::fmt::Display) -> Error { Error::Extension( Box::new(crate::SourceLocation::at_location( diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index a4bae00db..5111a4617 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -80,12 +80,14 @@ //! [`BlockView::title_source`] retains raw title input, its inline substitution //! order, original location, and document attributes before title interpretation. //! This includes titles that expand to empty content, attribute titles, sections, -//! and discrete headings. Constructed titles have no authored source snapshot. +//! and discrete headings. Titles supplied through builder attribute lists retain +//! that input with the target's location and source-position attributes. //! Ordinary parser entry points do not retain these extension snapshots. //! //! Tree processors run after block macros and can replace pending requests with -//! ordinary content. Builders accept literal text; markup and substitutions are -//! not run again. +//! ordinary content. Builder bodies are literal; attribute lists use the parser's +//! metadata rules. Use [`DocumentEditor::replace_source`] explicitly to interpret +//! retained paragraph or listing/literal source with its original substitutions. //! //! ``` //! use acdc_parser::{Error, Options, extensions::{ @@ -123,6 +125,26 @@ //! removed handles never resolve to another block. Section removal repairs TOC and //! reference catalogs, preserves surviving section/caption numbers, and compacts //! footnotes. Replacing a placeholder preserves its handle, metadata, and source. +//! [`DocumentEditor::replace_block`] offers the same construction path for ordinary +//! blocks, invalidating descendant handles and requests. Images and verbatim blocks +//! render through the usual converters. Attribute defaults are weaker than inherited +//! metadata and explicit lists; unsets apply afterward. Textual figures opt into +//! [`crate::CaptionKind::Figure`] through [`BlockBuilder::with_caption_kind`]. New +//! numbers advance beyond original and generated ordinals, including removed blocks. +//! Source-position caption labels and surviving numbers remain unchanged. Asciidoctor +//! 2.0.26 also retains surviving numbers on removal; its tree-processor image helper +//! may reuse lower ordinals, while acdc deliberately allocates monotonically. +//! +//! Each edit validates before mutation and repairs catalogs and reference warnings +//! before returning. An edit error leaves the visible tree, handles, numbering, and +//! diagnostics unchanged. Earlier successful edits and external effects remain if +//! a later processor fails; the processor sequence is not transactional. Generated +//! summaries and copied selections are snapshots. [`ExtensionParseResult::normalize`] +//! repeats structural repair idempotently without rerunning callbacks or numbering. +//! The working result retains session state and pending requests; consuming it with +//! [`ExtensionParseResult::finish`] yields an ordinary finalized [`crate::ParseResult`] +//! or a located error for an unresolved request. Checked ASG export rejects pending +//! blocks in both profiles and compatibility modes. mod block_macro; mod builder; @@ -144,6 +166,7 @@ pub use block_macro::{ MacroInvocation, MacroTarget, }; pub use builder::BlockBuilder; +pub(crate) use builder::SourceContext; pub use deferred::{DeferredBlock, ExtensionBlock, PlaceholderId}; pub use editor::DocumentEditor; pub use query::{BlockContext, BlockView, DocumentQuery}; diff --git a/acdc-parser/src/extensions/query.rs b/acdc-parser/src/extensions/query.rs index 83afe87a0..dcd551946 100644 --- a/acdc-parser/src/extensions/query.rs +++ b/acdc-parser/src/extensions/query.rs @@ -106,14 +106,14 @@ impl BlockContext { } } -#[derive(Debug)] +#[derive(Clone, Debug)] pub(super) struct Entry { pub(super) target: TargetId, pub(super) path: BlockPath, section: Option, } -#[derive(Debug)] +#[derive(Clone, Debug)] pub(super) struct TargetIndex { document: DocumentIdentity, entries: Vec, @@ -124,6 +124,15 @@ pub(super) struct TargetIndex { } impl TargetIndex { + pub(super) fn replace(&mut self, at: &TargetId) { + let Some(entry) = self.entry(at) else { + return; + }; + let path = entry.path.clone(); + self.entries + .retain(|entry| entry.target == *at || !entry.path.is_within(&path)); + self.reindex(); + } pub(super) fn prepare_edit(&mut self, document: &mut Document<'_>) { if self.caption_high_water.is_some() { return; @@ -179,14 +188,18 @@ impl TargetIndex { }); } - pub(super) fn next_caption(&mut self, kind: CaptionKind) -> Option { + pub(super) fn next_caption( + &mut self, + kind: CaptionKind, + source_counter: u32, + ) -> Option { let counter = self.caption_high_water.as_mut()?.get_mut(match kind { CaptionKind::Example => 0, CaptionKind::Figure => 1, CaptionKind::Listing => 2, CaptionKind::Table => 3, })?; - *counter = counter.saturating_add(1); + *counter = (*counter).max(source_counter).checked_add(1)?; NonZeroU32::new(*counter) } diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 2f1fea734..4c911d760 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -136,6 +136,10 @@ impl Registry { self.0.macros.is_empty() && self.0.trees.is_empty() } + pub(crate) fn has_tree_processors(&self) -> bool { + !self.0.trees.is_empty() + } + /// Parse with fresh processors and retain this document's deferred requests. /// /// Macro processors run once at committed block boundaries, before the @@ -181,7 +185,7 @@ impl Registry { &options, (!self.0.macros.is_empty()).then_some(&mut session), )?; - let mut result = ExtensionParseResult::new(parsed, session); + let mut result = ExtensionParseResult::new(parsed, session, options.compatibility_mode); if result.session.processed_blocks { result.repair_after_edit()?; } diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index 4eb249905..58d217cc4 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -27,6 +27,7 @@ impl fmt::Debug for Session { #[derive(Debug)] #[must_use] pub struct ExtensionParseResult { + pub(super) mode: crate::CompatibilityMode, pub(super) parsed: ParseResult, pub(super) session: Session, // Keep unqueried extension results small. @@ -34,8 +35,13 @@ pub struct ExtensionParseResult { } impl ExtensionParseResult { - pub(super) fn new(parsed: ParseResult, session: Session) -> Self { + pub(super) fn new( + parsed: ParseResult, + session: Session, + mode: crate::CompatibilityMode, + ) -> Self { Self { + mode, parsed, session, targets: OnceCell::new(), @@ -62,6 +68,21 @@ impl ExtensionParseResult { Ok(self.parsed) } + /// Repair structural catalogs and diagnostics without invoking processors. + /// Successful edits already normalize before returning. Repeating this + /// operation preserves their observable result and assigned numbers. + /// + /// # Errors + /// Returns a located error if retained semantic content cannot be repaired. + pub fn normalize(&mut self) -> Result<(), Error> { + self.target_index(); + if let Some(index) = self.targets.get_mut() { + self.parsed + .with_document_mut(|_, document| index.prepare_edit(document)); + } + self.repair_after_edit() + } + #[must_use] pub fn deferred_blocks(&self) -> &[DeferredBlock] { &self.session.deferred diff --git a/acdc-parser/src/extensions/tests/construction.rs b/acdc-parser/src/extensions/tests/construction.rs new file mode 100644 index 000000000..fc49ac1be --- /dev/null +++ b/acdc-parser/src/extensions/tests/construction.rs @@ -0,0 +1,543 @@ +use super::{TestResult, support}; +use acdc_parser::{ + CaptionKind, CompatibilityMode, Options, WarningKind, + ast::{BlockKind, CaptionRef, InlineKind}, + extensions::{BlockBuilder, BlockContext, DocumentEditor}, +}; + +#[test] +fn extensions_image_replacement_preserves_identity_title_and_source_context() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let source = "= Document\n:label: Early\n:figure-caption: Picture\n\n.Original *{label}*\n[#diagram.keep%nowrap,reftext='{label} *label*']\n[source,rust]\n----\noriginal\n----\n\n:label: Late\n:figure-caption: Later\n\n.Existing\nimage::existing.svg[]"; + let mut result = support::registry().parse(source, &options)?; + let target = result + .query() + .select(BlockContext::Listing) + .next() + .ok_or("listing")? + .target() + .clone(); + let before = result.query().get(&target).ok_or("original")?; + let title = serde_json::to_value(before.title())?; + let location = before.source_location(); + let mut editor = DocumentEditor::new(&mut result); + editor.replace_block( + &target, + BlockBuilder::image("generated.svg") + .with_default_attributes("'Default alt',100,200,title='Default',role=weak") + .with_attributes("'Chosen alt',320,240,width=640,link=target.html"), + )?; + let query = editor.query(); + let view = query.get(&target).ok_or("replacement")?; + assert_eq!(view.output_id(), Some("diagram")); + assert_eq!(view.source_location(), location); + assert_eq!(serde_json::to_value(view.title())?, title); + assert!( + matches!(view.caption(), Some(CaptionRef::Numbered { label: "Picture", number: Some(number), .. }) if number.get() == 2) + ); + let BlockKind::Image(image) = view.block().kind() else { + return Err("image".into()); + }; + assert!(image.roles().iter().any(|role| role == "keep")); + assert!(image.options().iter().any(|option| option == "nowrap")); + let stored = view.storage().metadata().ok_or("metadata")?; + assert_eq!( + stored + .attributes + .get("width") + .map(ToString::to_string) + .as_deref(), + Some("640") + ); + assert_eq!( + stored + .attributes + .get("height") + .map(ToString::to_string) + .as_deref(), + Some("240") + ); + let parsed = result.finish()?; + let label = parsed + .document() + .references() + .get("diagram") + .and_then(crate::ast::ReferenceTargetRef::xreflabel) + .ok_or("reference label")?; + assert!( + label + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + ); + } + Ok(()) +} + +#[test] +fn extensions_literal_diagrams_keep_custom_disabled_and_generated_captions() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse("= Document\n\n.Custom\n[caption='*Custom* ']\ndefer::one[]\n\n:figure-caption!:\n\n.Disabled\ndefer::two[]\n\n:figure-caption: Later\n\n.Numbered\ndefer::three[]", &options)?; + let targets: Vec<_> = result + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + let mut editor = DocumentEditor::new(&mut result); + for (position, target) in targets.iter().enumerate() { + let literal = BlockBuilder::literal("*literal* <&>\n spaces"); + editor.replace_placeholder( + target, + if position == 0 { + literal + } else { + literal.with_caption_kind(CaptionKind::Figure) + }, + )?; + } + let query = editor.query(); + let first = query.get(targets.first().ok_or("first")?).ok_or("custom")?; + assert!(matches!( + first.caption(), + Some(CaptionRef::CustomContent(_)) + )); + assert!(matches!( + query + .get(targets.get(1).ok_or("second")?) + .and_then(|view| view.caption()), + Some(CaptionRef::Unnumbered) + )); + assert!( + matches!(query.get(targets.get(2).ok_or("third")?).and_then(|view| view.caption()), Some(CaptionRef::Numbered { label: "Later", number: Some(number), .. }) if number.get() == 1) + ); + assert!(result.deferred_blocks().is_empty()); + let _ = result.finish()?; + } + Ok(()) +} + +#[test] +fn extensions_generated_captions_respect_local_counter_seeds_without_reusing_numbers() -> TestResult +{ + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "= Document\n:figure-number: 8\n\n.First\ndefer::first[]\n\n:figure-number: 40\n\n.Second\ndefer::second[]\n\n:figure-number: 2\n\n.Third\ndefer::third[]", + &options, + )?; + let targets: Vec<_> = result + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + let mut editor = DocumentEditor::new(&mut result); + for target in &targets { + editor.replace_placeholder(target, BlockBuilder::image("generated.svg"))?; + } + for (target, expected) in targets.iter().zip([9, 41, 42]) { + assert!( + matches!(editor.query().get(target).and_then(|view| view.caption()), Some(CaptionRef::Numbered {number: Some(number), ..}) if number.get() == expected) + ); + } + let before = serde_json::to_value(result.parsed.document())?; + result.normalize()?; + assert_eq!(serde_json::to_value(result.parsed.document())?, before); + let _ = result.finish()?; + } + Ok(()) +} + +#[test] +fn extensions_repair_failure_does_not_publish_edits_or_consume_caption_numbers() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "= Document\n:sectnums:\n\n== Section\n\n.Existing\nimage::existing.svg[]\n\n[#body]\nOriginal footnote:cycle[Original definition].", + &options, + )?; + let target = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("body")? + .target() + .clone(); + let before = serde_json::to_value(result.parsed.document())?; + let warnings = format!("{:?}", result.warnings()); + let mut editor = DocumentEditor::new(&mut result); + let error = editor.replace_block( + &target, + BlockBuilder::image("new.svg") + .with_attributes("title='footnote:cycle[footnote:cycle[]]'"), + ); + assert!(error.is_err(), "cyclic retained footnote must fail repair"); + assert_eq!(serde_json::to_value(editor.document_storage())?, before); + assert_eq!( + editor.query().get(&target).ok_or("unchanged")?.context(), + BlockContext::Paragraph + ); + editor.replace_block( + &target, + BlockBuilder::image("new.svg").with_attributes("title='Valid'"), + )?; + assert!( + matches!(editor.query().get(&target).and_then(|view| view.caption()), Some(CaptionRef::Numbered {number: Some(number), ..}) if number.get() == 2) + ); + assert_eq!(format!("{:?}", result.warnings()), warnings); + let _ = result.finish()?; + } + Ok(()) +} + +#[test] +fn extensions_verbatim_styles_follow_ordinary_caption_rules() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (content, numbered) in [ + ( + BlockBuilder::literal("raw").with_attributes("source,rust"), + true, + ), + ( + BlockBuilder::listing("raw").with_attributes("literal"), + false, + ), + (BlockBuilder::listing("raw"), true), + ] { + let mut result = support::registry().parse( + "= Document\n:listing-caption: Code\n\n.Title\ndefer::[]", + &options, + )?; + let target = result + .deferred_blocks() + .first() + .ok_or("request")? + .target() + .clone(); + DocumentEditor::new(&mut result).replace_placeholder(&target, content)?; + assert_eq!( + matches!( + result.query().get(&target).and_then(|view| view.caption()), + Some(CaptionRef::Numbered { + kind: CaptionKind::Listing, + number: Some(_), + .. + }) + ), + numbered + ); + } + } + Ok(()) +} + +#[test] +fn extensions_caption_overflow_rejects_the_edit_without_consuming_the_request() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "= Document\n:figure-number: 4294967295\n\n.Title\ndefer::[]", + &options, + )?; + let target = result + .deferred_blocks() + .first() + .ok_or("overflow request")? + .target() + .clone(); + let before = serde_json::to_value(result.parsed.document())?; + assert!( + DocumentEditor::new(&mut result) + .replace_placeholder(&target, BlockBuilder::image("x.svg")) + .is_err() + ); + assert_eq!(serde_json::to_value(result.parsed.document())?, before); + assert_eq!(result.deferred_blocks().len(), 1); + } + Ok(()) +} + +#[test] +fn extensions_source_replacement_uses_local_substitutions_and_repairs_references() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse("= Document\n:label: Early\n\n[#body]\nOld footnote:old[Old definition] <>.\n\n[subs=attributes]\n----\nOld\n----\n\n:label: Late\n\n[#later]\nLater.", &options)?; + let paragraph = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("paragraph")? + .target() + .clone(); + let listing = result + .query() + .select(BlockContext::Listing) + .next() + .ok_or("listing")? + .target() + .clone(); + assert!( + result + .warnings() + .iter() + .any(|warning| matches!(warning.kind, WarningKind::UnresolvedReference { .. })) + ); + let mut editor = DocumentEditor::new(&mut result); + editor.replace_source( + ¶graph, + "New *{label}* footnote:new[New definition] <>.", + )?; + editor.replace_source(&listing, "*{label}* <&>\n spaces")?; + let query = editor.query(); + let view = query.get(¶graph).ok_or("paragraph")?; + let BlockKind::Paragraph(block) = view.block().kind() else { + return Err("paragraph".into()); + }; + assert_eq!( + block.source_text(), + Some("New *{label}* footnote:new[New definition] <>.") + ); + assert!( + block + .content() + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + ); + let before = serde_json::to_value(result.parsed.document())?; + let warnings = format!("{:?}", result.warnings()); + result.normalize()?; + result.normalize()?; + assert_eq!(serde_json::to_value(result.parsed.document())?, before); + assert_eq!(format!("{:?}", result.warnings()), warnings); + assert!( + !result + .warnings() + .iter() + .any(|warning| matches!(warning.kind, WarningKind::UnresolvedReference { .. })) + ); + assert_eq!(result.parsed.document().footnotes().count(), 1); + let _ = result.finish()?; + } + Ok(()) +} + +#[test] +fn extensions_invalid_construction_is_atomic_and_removes_replaced_descendants() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "[#container]\n--\n.Child\n[#child]\ndefer::[]\n--\n\n[#duplicate]\nOther.", + &options, + )?; + let target = result + .query() + .select(BlockContext::Open) + .next() + .ok_or("open")? + .target() + .clone(); + let child = result + .deferred_blocks() + .first() + .ok_or("child")? + .target() + .clone(); + let before = serde_json::to_value(result.parsed.document())?; + let warnings = format!("{:?}", result.warnings()); + let mut editor = DocumentEditor::new(&mut result); + assert!( + editor + .replace_block(&target, BlockBuilder::image("x.svg").with_id("duplicate")) + .is_err() + ); + assert!( + editor + .replace_block(&target, BlockBuilder::image("http://[invalid")) + .is_err() + ); + assert!( + editor + .replace_block( + &target, + BlockBuilder::paragraph("x").with_attributes("role=one\nrole=two") + ) + .is_err() + ); + assert_eq!(serde_json::to_value(editor.document_storage())?, before); + assert!(editor.query().get(&child).is_some()); + editor.replace_block(&target, BlockBuilder::literal("Replacement"))?; + assert!(editor.query().get(&child).is_none()); + assert!(editor.ensure_id(&child).is_err()); + assert!(editor.deferred_blocks().is_empty()); + assert_eq!(format!("{:?}", result.warnings()), warnings); + assert!(result.parsed.document().references().get("child").is_none()); + let _ = result.finish()?; + } + Ok(()) +} + +#[test] +fn extensions_generated_metadata_distinguishes_empty_values_and_unsets() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + ".Original\n[#image.keep%nowrap,reftext='Label']\nimage::old.svg['Original alt',100,200]", + &options, + )?; + let target = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")? + .target() + .clone(); + let mut editor = DocumentEditor::new(&mut result); + editor.replace_block( + &target, + BlockBuilder::image("new.svg") + .with_default_attributes("'Weak alt',width=10,height=20") + .with_attributes("alt='',width='',role='',opts='',title=''"), + )?; + let query = editor.query(); + let view = query.get(&target).ok_or("empty image")?; + assert!(view.title().is_some()); + let metadata = view.storage().metadata().ok_or("metadata")?; + assert_eq!( + metadata.roles.is_empty(), + mode == CompatibilityMode::Asciidoctor + ); + assert!(metadata.options.contains(&"nowrap")); + assert_eq!( + metadata + .attributes + .get("width") + .map(ToString::to_string) + .as_deref(), + Some("") + ); + assert_eq!( + metadata + .attributes + .get("height") + .map(ToString::to_string) + .as_deref(), + Some("200") + ); + let BlockKind::Image(image) = view.block().kind() else { + return Err("image".into()); + }; + assert!( + image + .alt() + .is_some_and(|alt| alt.inlines().next().is_none()) + ); + editor.replace_block( + &target, + BlockBuilder::image("last.svg") + .without_attribute("id") + .without_attribute("title") + .without_attribute("reftext") + .without_attribute("roles") + .without_attribute("options") + .without_attribute("alt") + .without_attribute("height"), + )?; + let query = editor.query(); + let view = query.get(&target).ok_or("unset image")?; + assert_eq!(view.output_id(), None); + assert!(view.title().is_none()); + let metadata = view.storage().metadata().ok_or("metadata")?; + assert!(metadata.reftext.is_none()); + assert!(metadata.roles.is_absent()); + assert!(metadata.options.is_absent()); + assert!(!metadata.attributes.contains_key("height")); + let BlockKind::Image(image) = view.block().kind() else { + return Err("image".into()); + }; + assert!(image.alt().is_none()); + } + Ok(()) +} + +#[test] +fn extensions_source_replacement_reuses_scoped_notes_without_number_collisions() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "Original footnote:[Anonymous] footnote:shared[Named].\n\n[#body]\nReplace.\n\n[cols=a]\n|===\n|Cell footnote:shared[Cell named].\n\n[#cell]\nReplace cell.\n|===", + &options, + )?; + let targets: Vec<_> = result + .query() + .select(BlockContext::Paragraph) + .filter(|view| matches!(view.output_id(), Some("body" | "cell"))) + .map(|view| view.target().clone()) + .collect(); + let mut editor = DocumentEditor::new(&mut result); + for target in targets { + editor.replace_source(&target, "New footnote:[New anonymous] footnote:shared[].")?; + } + result.normalize()?; + assert!(result.warnings().is_empty(), "{:?}", result.warnings()); + let original = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("original")? + .target() + .clone(); + DocumentEditor::new(&mut result) + .replace_source(&original, "Updated footnote:shared[Updated named].")?; + let document = result.finish()?; + assert_eq!(document.document().footnotes().count(), 2); + assert!(serde_json::to_string(&document.document())?.contains("Updated named")); + } + Ok(()) +} + +#[test] +fn extensions_normalize_preserves_unedited_numbers_and_clears_stale_duplicate_warnings() +-> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "= Document\n:sectnums:\n\n== First\n\n[#body]\n[[duplicate]] Original.\n\n== Second\n\n[[duplicate]] Other.", + &options, + )?; + let before = serde_json::to_value(result.parsed.document())?; + result.normalize()?; + result.normalize()?; + assert_eq!(serde_json::to_value(result.parsed.document())?, before); + assert!( + result + .warnings() + .iter() + .any(|warning| matches!(warning.kind, WarningKind::DuplicateId { .. })) + ); + let target = result + .query() + .select(BlockContext::Paragraph) + .find(|view| view.output_id() == Some("body")) + .ok_or("body")? + .target() + .clone(); + DocumentEditor::new(&mut result).replace_source(&target, "Replacement.")?; + assert!( + !result + .warnings() + .iter() + .any(|warning| matches!(warning.kind, WarningKind::DuplicateId { .. })) + ); + DocumentEditor::new(&mut result).replace_source(&target, "[[fresh]] One [[fresh]] two.")?; + assert_eq!( + result + .warnings() + .iter() + .filter(|warning| matches!(warning.kind, WarningKind::DuplicateId { .. })) + .count(), + 1 + ); + } + Ok(()) +} diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index 51b674942..0eccb21db 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -24,6 +24,7 @@ mod support; #[path = "queries.rs"] mod queries; +mod construction; mod title_sources; #[path = "tree_processors.rs"] diff --git a/acdc-parser/src/extensions/traversal.rs b/acdc-parser/src/extensions/traversal.rs index a33ab7324..1737af5f6 100644 --- a/acdc-parser/src/extensions/traversal.rs +++ b/acdc-parser/src/extensions/traversal.rs @@ -1,4 +1,7 @@ -use crate::{Block, ColumnStyle, DelimitedBlockType, ListItem, Table, TableCell}; +use crate::{ + Block, ColumnStyle, DelimitedBlockType, Document, FootnoteDefinition, ListItem, Table, + TableCell, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Children { @@ -25,6 +28,28 @@ pub(super) struct BlockPath { } impl BlockPath { + pub(super) fn footnotes<'doc, 'a>( + &self, + document: &'doc Document<'a>, + ) -> &'doc [FootnoteDefinition<'a>] { + let mut definitions = document.footnotes.as_slice(); + let Some(mut block) = document.blocks.get(self.root) else { + return definitions; + }; + for &(children, index) in &self.nested { + if let Some(cell) = children.cell(block) + && cell.style == Some(ColumnStyle::AsciiDoc) + { + definitions = cell.footnotes.as_deref().unwrap_or_default(); + } + let Some(child) = children.get(block).and_then(|blocks| blocks.get(index)) else { + break; + }; + block = child; + } + definitions + } + pub(super) fn container_mut<'doc, 'a>( &self, blocks: &'doc mut Vec>, @@ -102,6 +127,24 @@ impl BlockPath { } impl Children { + fn cell<'doc, 'a>(self, block: &'doc Block<'a>) -> Option<&'doc TableCell<'a>> { + let Self::Cell { part, row, column } = self else { + return None; + }; + let Block::DelimitedBlock(block) = block else { + return None; + }; + let DelimitedBlockType::DelimitedTable(table) = &block.inner else { + return None; + }; + let rows = match part { + TablePart::Head => table.header.as_slice(), + TablePart::Body => &table.rows, + TablePart::Foot => table.footer.as_slice(), + }; + rows.get(row)?.columns.get(column) + } + fn get<'doc, 'a>(self, block: &'doc Block<'a>) -> Option<&'doc [Block<'a>]> { match (self, block) { (Self::Body, Block::Section(block)) => Some(&block.content), @@ -167,6 +210,34 @@ impl Children { } } +pub(super) fn highest_footnote(document: &Document<'_>) -> u32 { + fn blocks_high_water(blocks: &[Block<'_>], number: &mut u32) { + for block in blocks { + visit_children(block, |children, blocks| { + if let Some(cell) = children.cell(block) { + *number = (*number).max( + cell.footnotes + .iter() + .flatten() + .map(|note| note.number) + .max() + .unwrap_or(0), + ); + } + blocks_high_water(blocks, number); + }); + } + } + let mut number = document + .footnotes + .iter() + .map(|note| note.number) + .max() + .unwrap_or(0); + blocks_high_water(&document.blocks, &mut number); + number +} + pub(crate) fn table_cell_mut<'doc, 'a>( table: &'doc mut Table<'a>, part: TablePart, diff --git a/acdc-parser/src/grammar/document.rs b/acdc-parser/src/grammar/document.rs index 1086d60df..4aebb8789 100644 --- a/acdc-parser/src/grammar/document.rs +++ b/acdc-parser/src/grammar/document.rs @@ -8,6 +8,7 @@ mod coordinator; mod delimited; mod doctype; mod finish; +mod generated; mod header; mod input; pub(super) mod lists; @@ -24,6 +25,10 @@ mod table; mod verbatim; pub(crate) use coordinator::document; +pub(crate) use generated::{ + Context as GeneratedContext, prepare as prepare_generated, + replace_source as replace_generated_source, +}; pub(crate) use peg::document_parser; pub(crate) use source::{Assignments as SourceAssignments, SourceHandler, document_from_source}; diff --git a/acdc-parser/src/grammar/document/generated.rs b/acdc-parser/src/grammar/document/generated.rs new file mode 100644 index 000000000..f7401e65a --- /dev/null +++ b/acdc-parser/src/grammar/document/generated.rs @@ -0,0 +1,332 @@ +//! Attribute and inline preparation for declarative extension construction. + +use std::rc::Rc; + +use bumpalo::Bump; + +use crate::{ + BlockMetadata, ContentAttribute, Error, FootnoteDefinition, Location, Options, SourceLocation, + Title, Warning, + extensions::{BlockBuilder, SourceContext}, + grammar::{BlockAttributeMode, ParserState}, +}; + +use super::{ + delimited::DelimitedKind, + metadata::{self, AttributeBlockForm, ParsedAttributeList}, +}; + +pub(crate) struct Context<'doc, 'a> { + pub(crate) source: &'doc SourceContext<'a>, + pub(crate) footnotes: &'doc [FootnoteDefinition<'a>], + pub(crate) next_footnote: u32, +} + +impl<'a> Context<'_, 'a> { + fn state(&self, input: &'a str, arena: &'a Bump) -> Result, Error> { + let mut options = Options::builder() + .with_compatibility_mode(self.source.mode) + .build()?; + options.document_attributes = self.source.attributes.clone(); + // Retain titles supplied by generated attribute lists, without callbacks. + options.extensions = Some(crate::extensions::Registry::default()); + let state = ParserState::new(input, arena, Rc::new(options)); + state + .footnote_tracker + .borrow_mut() + .seed(self.footnotes, self.next_footnote); + Ok(state) + } +} + +pub(crate) struct Prepared<'a> { + pub(crate) metadata: BlockMetadata<'a>, + pub(crate) title: Title<'a>, + pub(crate) alt: Option>, + pub(crate) explicit_alt: bool, + pub(crate) warnings: Vec, +} + +pub(crate) fn prepare<'a>( + arena: &'a Bump, + builder: &BlockBuilder, + inherited: BlockMetadata<'a>, + title: Title<'a>, + context: &Context<'_, 'a>, + origin: &SourceLocation, +) -> Result, Error> { + let sources: Vec<_> = builder.defaults.iter().chain(&builder.attributes).collect(); + if sources.iter().any(|source| source.contains(['\n', '\r'])) { + return Err(Error::Extension( + Box::new(origin.clone()), + "generated attribute lists must fit on one line".into(), + )); + } + let input = arena.alloc_str( + &sources + .iter() + .map(|source| source.as_str()) + .collect::>() + .join("\n"), + ); + let mut state = context.state(input, arena)?; + let mode = if builder.is_image() { + BlockAttributeMode::Macro + } else { + BlockAttributeMode::Block + }; + let mut attributes = ParsedAttributeList::default(); + let mut offset = 0; + if let Some(defaults) = &builder.defaults { + let source = input.get(..defaults.len()).unwrap_or_default(); + attributes = metadata::parse_block_attribute_list(&mut state, source, 0, mode, 0)?; + offset = defaults.len() + 1; + } + if title.is_present() { + attributes.title = None; + } + let previous = inherited.clone(); + attributes.overlay_prepared(inherited, context.source.mode); + let mut explicit_alt = builder.unsets.iter().any(|name| name == "alt"); + for source in &builder.attributes { + let source = input.get(offset..offset + source.len()).unwrap_or_default(); + let parsed = metadata::parse_block_attribute_list(&mut state, source, offset, mode, 0)?; + explicit_alt |= + parsed.metadata.first_source.is_some() || parsed.metadata.alt_source.is_some(); + attributes.merge(parsed, context.source.mode); + offset += source.len() + 1; + } + let explicit_title = attributes.title.is_some(); + let mut prepared = finish(&mut state, builder, attributes, title)?; + prepared.explicit_alt = explicit_alt; + for name in &builder.unsets { + unset(&mut prepared, name); + } + prepared.warnings = std::mem::take(&mut *state.warnings.borrow_mut()).into_vec(); + for warning in &mut prepared.warnings { + warning.location = Some(origin.clone()); + } + if explicit_title && let Some(source) = prepared.title.source() { + let mut source = source.clone(); + source.location = origin.clone(); + prepared.title = + std::mem::take(&mut prepared.title).with_source(Some(std::sync::Arc::new(source))); + } + remap(&mut prepared, &previous, explicit_title, &origin.location); + Ok(prepared) +} + +fn finish<'a>( + state: &mut ParserState<'a>, + builder: &BlockBuilder, + mut attributes: ParsedAttributeList<'a>, + inherited_title: Title<'a>, +) -> Result, Error> { + if !builder.is_image() { + let form = if builder.is_verbatim() { + AttributeBlockForm::Delimited( + if builder.is_listing() { + DelimitedKind::Listing + } else { + DelimitedKind::Literal + }, + None, + ) + } else { + AttributeBlockForm::Paragraph + }; + metadata::route_block_positions(state, &mut attributes, form); + } + let media = builder.is_image().then(|| attributes.metadata.clone()); + let alt = metadata::resolve_block_content_attributes( + state, + &mut attributes, + media.as_ref(), + builder.is_image(), + )?; + let title = attributes + .title + .take() + .map_or(Ok(inherited_title), |source| { + metadata::resolve_title(state, source, 0) + })?; + let mut parsed = metadata::finish_block_parsing_metadata(state, attributes, title, None)?; + if let Some(media) = media { + metadata::route_media_positions( + &mut parsed.metadata, + &media, + state.options.compatibility_mode, + false, + ); + parsed.metadata.attributes.remove("alt"); + } + parsed.metadata.first_source = None; + parsed.metadata.alt_source = None; + parsed.metadata.move_positional_attributes_to_attributes(); + Ok(Prepared { + metadata: parsed.metadata, + title: parsed.title, + alt, + explicit_alt: false, + warnings: Vec::new(), + }) +} + +fn unset(prepared: &mut Prepared<'_>, name: &str) { + match name { + "id" => { + prepared.metadata.id = None; + prepared.metadata.anchors.clear(); + } + "role" | "roles" => prepared.metadata.roles = crate::TokenAssignment::default(), + "opts" | "options" => prepared.metadata.options = crate::TokenAssignment::default(), + "style" => prepared.metadata.style = None, + "title" => prepared.title = Title::default(), + "caption" => prepared.metadata.caption = None, + "reftext" => prepared.metadata.reftext = None, + "subs" => prepared.metadata.substitutions = None, + "attribution" => prepared.metadata.attribution = None, + "citetitle" => prepared.metadata.citetitle = None, + "alt" => prepared.alt = None, + name => { + prepared.metadata.attributes.remove(name); + } + } +} + +fn remap<'a>( + prepared: &mut Prepared<'a>, + previous: &BlockMetadata<'a>, + explicit_title: bool, + origin: &Location, +) { + for anchor in prepared + .metadata + .id + .iter_mut() + .chain(&mut prepared.metadata.anchors) + { + if !previous + .id + .iter() + .chain(&previous.anchors) + .any(|old| old == anchor) + { + anchor.location = origin.clone(); + } + } + if explicit_title { + for inline in prepared.title.inlines_mut() { + crate::grammar::location_walk::walk_inline_locations_mut(inline, &mut |location| { + *location = origin.clone(); + }); + } + } + for (current, old) in [ + (&mut prepared.alt, &None), + (&mut prepared.metadata.reftext, &previous.reftext), + (&mut prepared.metadata.attribution, &previous.attribution), + (&mut prepared.metadata.citetitle, &previous.citetitle), + ] { + if current != old + && let Some(content) = current + { + remap_content(content, origin); + } + } + if prepared.metadata.caption != previous.caption + && let Some(crate::Caption::CustomContent(content)) = &mut prepared.metadata.caption + { + remap_content(content, origin); + } +} + +fn remap_content(content: &mut ContentAttribute<'_>, origin: &Location) { + for inline in content.inlines_mut() { + crate::grammar::location_walk::walk_inline_locations_mut(inline, &mut |location| { + *location = origin.clone(); + }); + } +} + +pub(crate) fn replace_source<'a>( + arena: &'a Bump, + block: &mut crate::Block<'a>, + source: &'a str, + context: &Context<'_, 'a>, + origin: &SourceLocation, +) -> Result, Error> { + let metadata = block.metadata().cloned().unwrap_or_default(); + let mut state = context.state(source, arena)?; + let substitutions = metadata.substitutions.as_ref().map_or_else( + || crate::model::substitution::SubstitutionPlan::for_mode(context.source.mode), + |spec| { + crate::model::substitution::SubstitutionPlan::for_block_spec(spec, context.source.mode) + }, + ); + let parsing = crate::grammar::helpers::BlockParsingMetadata { + metadata, + substitutions, + ..Default::default() + }; + let nodes = if let crate::Block::Paragraph(paragraph) = block { + paragraph.content = + crate::grammar::process_inlines(&mut state, &parsing, 0, source.len(), 0, source)?.0; + paragraph.source_text = Some(source); + &mut paragraph.content + } else if let crate::Block::DelimitedBlock(delimited) = block { + let kind = if matches!( + delimited.inner, + crate::DelimitedBlockType::DelimitedListing(_) + ) { + DelimitedKind::Listing + } else { + DelimitedKind::Literal + }; + let params = super::delimited::DelimitedParams { + open_start: 0, + source_text: source, + start: 0, + offset: 0, + content_start: 0, + content_end: source.len(), + end: source.len(), + open_delim: delimited.delimiter, + close: None, + content: source, + kind, + }; + delimited.inner = super::verbatim::verbatim_inner( + &mut state, + &parsing, + &mut delimited.metadata, + ¶ms, + )?; + delimited.source_text = Some(source); + if let crate::DelimitedBlockType::DelimitedListing(nodes) + | crate::DelimitedBlockType::DelimitedLiteral(nodes) = &mut delimited.inner + { + nodes + } else { + return Err(Error::Extension( + Box::new(origin.clone()), + "source replacement produced an unsupported body".into(), + )); + } + } else { + return Err(Error::Extension( + Box::new(origin.clone()), + "source body is unsupported".into(), + )); + }; + for node in nodes { + crate::grammar::location_walk::walk_inline_locations_mut(node, &mut |location| { + *location = origin.location.clone(); + }); + } + let mut warnings = std::mem::take(&mut *state.warnings.borrow_mut()).into_vec(); + for warning in &mut warnings { + warning.location = Some(origin.clone()); + } + Ok(warnings) +} diff --git a/acdc-parser/src/grammar/document/metadata.rs b/acdc-parser/src/grammar/document/metadata.rs index 8e1c8c257..e66e684be 100644 --- a/acdc-parser/src/grammar/document/metadata.rs +++ b/acdc-parser/src/grammar/document/metadata.rs @@ -118,6 +118,38 @@ impl<'a> QuoteSources<'a> { } impl<'a> ParsedAttributeList<'a> { + pub(super) fn overlay_prepared( + &mut self, + metadata: BlockMetadata<'a>, + mode: CompatibilityMode, + ) { + if metadata.caption.is_some() { + self.caption_source = None; + } + if metadata.attribution.is_some() { + self.quote_sources.attribution = None; + } + if metadata.citetitle.is_some() { + self.quote_sources.citetitle = None; + } + let roles = (!metadata.roles.is_absent()).then(|| metadata.roles.clone()); + let options = (!metadata.options.is_absent()).then(|| metadata.options.clone()); + let context = metadata.source_context.clone(); + let reftext = metadata.reftext.clone(); + self.merge(Self::from_metadata(metadata), mode); + if let Some(roles) = roles { + self.metadata.roles = roles; + } + if let Some(options) = options { + self.metadata.options = options; + } + if reftext.is_some() { + self.metadata.reftext = reftext; + self.metadata.reftext_source = None; + } + self.metadata.source_context = context; + } + pub(super) fn merge(&mut self, other: Self, mode: CompatibilityMode) { merge_attribute_metadata(&mut self.metadata, other.metadata, mode); if other.title.is_some() { @@ -487,6 +519,7 @@ pub(super) fn finish_block_parsing_metadata<'input>( mut caption_source, .. } = attributes; + metadata.source_context = crate::extensions::SourceContext::capture(state); crate::grammar::reference_text::resolve_metadata(state, &mut metadata)?; let discrete = matches!(metadata.style, Some("discrete" | "float")); let substitutions = metadata.substitutions.as_ref().map_or_else( @@ -656,6 +689,15 @@ pub(super) fn route_media_attributes<'a>( video: bool, ) { merge_macro_metadata(metadata, attributes, mode); + route_media_positions(metadata, attributes, mode, video); +} + +pub(super) fn route_media_positions<'a>( + metadata: &mut BlockMetadata<'a>, + attributes: &BlockMetadata<'a>, + mode: CompatibilityMode, + video: bool, +) { let selected = if mode == CompatibilityMode::Draft { &*metadata } else { diff --git a/acdc-parser/src/grammar/mod.rs b/acdc-parser/src/grammar/mod.rs index 81577f970..5dab02072 100644 --- a/acdc-parser/src/grammar/mod.rs +++ b/acdc-parser/src/grammar/mod.rs @@ -31,8 +31,8 @@ pub(crate) use attributes::{ BlockAttributeMode, block_attribute_line, block_attribute_style, style_overrides_block_form, }; pub(crate) use document::{ - SourceAssignments, SourceHandler, document as parse_document, document_from_source, - document_parser, + GeneratedContext, SourceAssignments, SourceHandler, document as parse_document, + document_from_source, document_parser, prepare_generated, replace_generated_source, }; pub(crate) use inline_preprocessor::{ InlinePreprocessorParserState, ProcessedContent, inline_preprocessing, diff --git a/acdc-parser/src/grammar/state.rs b/acdc-parser/src/grammar/state.rs index 63f581bb7..b7d1cf997 100644 --- a/acdc-parser/src/grammar/state.rs +++ b/acdc-parser/src/grammar/state.rs @@ -285,6 +285,9 @@ pub(super) struct FootnoteTracker<'a> { // Ordinary documents need no shared counter allocation. shared_next_number: Option>>, named_footnotes: HashMap<&'a str, NamedFootnote<'a>>, + // Catalog names available to a host-owned inline edit. Authored definitions + // in that edit still parse normally and can replace a removed definition. + retained_names: Option>>, /// Footnote numbers whose stored entry has already had its location/content /// finalized to document-absolute coordinates (see [`Self::finalize`]). The first /// occurrence of a number wins, so a later bare reference of a named footnote does @@ -299,6 +302,7 @@ impl<'a> FootnoteTracker<'a> { next_number: 1, shared_next_number: None, named_footnotes: HashMap::new(), + retained_names: None, location_finalized: HashSet::new(), } } @@ -330,9 +334,20 @@ impl<'a> FootnoteTracker<'a> { pub(super) fn discard_definitions(&mut self) { self.footnotes.clear(); self.named_footnotes.clear(); + self.retained_names = None; self.location_finalized.clear(); } + /// Start a host-owned inline edit with retained definitions from its owner. + pub(super) fn seed(&mut self, definitions: &[FootnoteDefinition<'a>], next_number: u32) { + self.next_number = next_number; + let names: HashMap<_, _> = definitions + .iter() + .filter_map(|note| Some((note.id?, note.number))) + .collect(); + self.retained_names = (!names.is_empty()).then(|| Rc::new(names)); + } + /// Update the first definition after its locations become document-absolute. /// Later occurrences keep that body and location. Return the first location /// when a repeated definition has different captured text. @@ -378,6 +393,14 @@ impl<'a> FootnoteTracker<'a> { return false; }; if content.is_empty() { + if let Some(number) = footnote + .id + .and_then(|id| self.retained_names.as_ref()?.get(id)) + { + footnote.number = *number; + footnote.content = None; + return true; + } return false; } footnote.number = self.next_number(); diff --git a/acdc-parser/src/model/caption.rs b/acdc-parser/src/model/caption.rs index 5ae919e0d..6fe6fa3e9 100644 --- a/acdc-parser/src/model/caption.rs +++ b/acdc-parser/src/model/caption.rs @@ -54,6 +54,19 @@ pub enum CaptionKind { } impl CaptionKind { + pub(crate) fn source_counter(self, attributes: &DocumentAttributes<'_>) -> u32 { + let name = match self { + Self::Example => "example-number", + Self::Figure => "figure-number", + Self::Listing => "listing-number", + Self::Table => "table-number", + }; + attributes + .text(name) + .and_then(|value| value.parse().ok()) + .unwrap_or(0) + } + const fn attribute_name(self) -> &'static str { match self { Self::Example => "example-caption", @@ -146,7 +159,7 @@ impl CaptionKind { /// The context of a verbatim block, where only `literal`, `listing` and `source` override /// the delimiter's own `default`. - fn for_verbatim(style: Option<&str>, default: Option) -> Option { + pub(crate) fn for_verbatim(style: Option<&str>, default: Option) -> Option { match style { Some("listing" | "source") => Some(Self::Listing), Some("literal") => None, diff --git a/acdc-parser/src/model/metadata.rs b/acdc-parser/src/model/metadata.rs index d4249cf34..6be6f0588 100644 --- a/acdc-parser/src/model/metadata.rs +++ b/acdc-parser/src/model/metadata.rs @@ -56,6 +56,8 @@ impl<'a> BlockPrefixEvents<'a> { #[derive(Clone, Debug, Default, Serialize)] #[non_exhaustive] pub struct BlockMetadata<'a> { + #[serde(skip)] + pub(crate) source_context: Option>>, #[serde(skip)] pub(crate) attribute_positions: Option>>, // Store uncommon parser events separately to keep each block's metadata small. @@ -121,6 +123,7 @@ pub struct BlockMetadata<'a> { impl PartialEq for BlockMetadata<'_> { fn eq(&self, other: &Self) -> bool { let Self { + source_context: _, attribute_positions: _, prefix_events, caption, diff --git a/acdc-parser/src/parsed.rs b/acdc-parser/src/parsed.rs index 93f57d572..d5736b117 100644 --- a/acdc-parser/src/parsed.rs +++ b/acdc-parser/src/parsed.rs @@ -338,6 +338,17 @@ impl ParseResult { self.warnings = combined.into_vec(); } + pub(crate) fn append_extension_warnings(&mut self, warnings: Vec) { + let mut combined = WarningCollection::default(); + for warning in std::mem::take(&mut self.warnings) + .into_iter() + .chain(warnings) + { + combined.push_unique_from(warning, 0); + } + self.warnings = combined.into_vec(); + } + /// Borrow the preprocessed source the AST was parsed from. /// /// Note: this is the text as seen by the grammar, after include From 38b7855276bd4f6afc5a54e0273e951d9e704f64 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 14 Nov 2026 23:10:31 +0100 Subject: [PATCH 16/55] test(parser): cover construction with public diagram consumers Exercise image and literal construction through paired parser fixtures with separate producer and query processors. Add an HTML diagram consumer using public handles and builders to verify inherited source context, captions, escaping, and cross references in both compatibility modes. Refs SC-538. --- .../tests/extensions/construction.adoc | 28 + .../construction.asciidoctor.diagnostics.json | 4 + .../extensions/construction.asciidoctor.json | 745 +++++++++++++++++ .../construction.draft.diagnostics.json | 4 + .../tests/extensions/construction.draft.json | 751 ++++++++++++++++++ acdc-parser/src/extensions/tests/support.rs | 36 +- .../html/tests/extension_construction.rs | 99 +++ 7 files changed, 1666 insertions(+), 1 deletion(-) create mode 100644 acdc-parser/fixtures/tests/extensions/construction.adoc create mode 100644 acdc-parser/fixtures/tests/extensions/construction.asciidoctor.diagnostics.json create mode 100644 acdc-parser/fixtures/tests/extensions/construction.asciidoctor.json create mode 100644 acdc-parser/fixtures/tests/extensions/construction.draft.diagnostics.json create mode 100644 acdc-parser/fixtures/tests/extensions/construction.draft.json create mode 100644 converters/html/tests/extension_construction.rs diff --git a/acdc-parser/fixtures/tests/extensions/construction.adoc b/acdc-parser/fixtures/tests/extensions/construction.adoc new file mode 100644 index 000000000..18e0f23b3 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/construction.adoc @@ -0,0 +1,28 @@ += Host construction +:label: Early +:figure-caption: Picture + +.Image *{label}* +[#image.keep%nowrap,reftext='Diagram *label*'] +fixture-build::image[] + +.Text *{label}* +[#literal,caption='*Custom* '] +fixture-build::literal[] + +:figure-caption!: + +.Unnumbered +[#disabled] +fixture-build::literal[] + +:figure-caption: Later +:label: Late + +.Last +[#last] +fixture-build::image[] + +See <>, <>, <>, and <>. + +query::[] diff --git a/acdc-parser/fixtures/tests/extensions/construction.asciidoctor.diagnostics.json b/acdc-parser/fixtures/tests/extensions/construction.asciidoctor.diagnostics.json new file mode 100644 index 000000000..849eafd43 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/construction.asciidoctor.diagnostics.json @@ -0,0 +1,4 @@ +{ + "recovery": null, + "warnings": [] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/extensions/construction.asciidoctor.json b/acdc-parser/fixtures/tests/extensions/construction.asciidoctor.json new file mode 100644 index 000000000..60338fb13 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/construction.asciidoctor.json @@ -0,0 +1,745 @@ +{ + "name": "document", + "type": "block", + "header": { + "title": [ + { + "name": "text", + "type": "string", + "value": "Host construction", + "location": [ + { + "line": 1, + "col": 3 + }, + { + "line": 1, + "col": 19 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 3, + "col": 24 + } + ] + }, + "attributes": { + "figure-caption": "Picture", + "label": "Early" + }, + "blocks": [ + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "attributes": { + "height": "200", + "width": "320" + }, + "reftext": [ + { + "name": "text", + "type": "string", + "value": "Diagram ", + "location": [ + { + "line": 6, + "col": 30 + }, + { + "line": 6, + "col": 37 + } + ] + }, + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "label", + "location": [ + { + "line": 6, + "col": 39 + }, + { + "line": 6, + "col": 43 + } + ] + } + ], + "location": [ + { + "line": 6, + "col": 38 + }, + { + "line": 6, + "col": 44 + } + ] + } + ], + "roles": [ + "keep" + ], + "options": [ + "nowrap" + ], + "id": { + "id": "image", + "location": [ + { + "line": 6, + "col": 3 + }, + { + "line": 6, + "col": 7 + } + ] + } + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Image ", + "location": [ + { + "line": 5, + "col": 2 + }, + { + "line": 5, + "col": 7 + } + ] + }, + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Early", + "location": [ + { + "line": 5, + "col": 9 + }, + { + "line": 5, + "col": 15 + } + ] + } + ], + "location": [ + { + "line": 5, + "col": 8 + }, + { + "line": 5, + "col": 16 + } + ] + } + ], + "alt": [ + { + "name": "text", + "type": "string", + "value": "Alt Early", + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 7, + "col": 22 + } + ] + } + ], + "source": { + "type": "path", + "value": "generated.svg" + }, + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 7, + "col": 22 + } + ] + }, + { + "name": "literal", + "type": "block", + "form": "delimited", + "delimiter": "....", + "metadata": { + "caption": [ + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Custom", + "location": [ + { + "line": 10, + "col": 21 + }, + { + "line": 10, + "col": 26 + } + ] + } + ], + "location": [ + { + "line": 10, + "col": 20 + }, + { + "line": 10, + "col": 27 + } + ] + }, + { + "name": "text", + "type": "string", + "value": " ", + "location": [ + { + "line": 10, + "col": 28 + }, + { + "line": 10, + "col": 28 + } + ] + } + ], + "id": { + "id": "literal", + "location": [ + { + "line": 10, + "col": 3 + }, + { + "line": 10, + "col": 9 + } + ] + } + }, + "inlines": [ + { + "name": "text", + "type": "string", + "value": "<&>\n*literal*\n spaces", + "location": [ + { + "line": 9, + "col": 1 + }, + { + "line": 11, + "col": 24 + } + ] + } + ], + "title": [ + { + "name": "text", + "type": "string", + "value": "Text ", + "location": [ + { + "line": 9, + "col": 2 + }, + { + "line": 9, + "col": 6 + } + ] + }, + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Early", + "location": [ + { + "line": 9, + "col": 8 + }, + { + "line": 9, + "col": 14 + } + ] + } + ], + "location": [ + { + "line": 9, + "col": 7 + }, + { + "line": 9, + "col": 15 + } + ] + } + ], + "location": [ + { + "line": 9, + "col": 1 + }, + { + "line": 11, + "col": 24 + } + ] + }, + { + "name": "figure-caption", + "type": "attribute", + "value": false, + "location": [ + { + "line": 13, + "col": 1 + }, + { + "line": 13, + "col": 17 + } + ] + }, + { + "name": "literal", + "type": "block", + "form": "delimited", + "delimiter": "....", + "metadata": { + "anchors": [ + { + "id": "disabled", + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 16, + "col": 12 + } + ] + } + ] + }, + "inlines": [ + { + "name": "text", + "type": "string", + "value": "<&>\n*literal*\n spaces", + "location": [ + { + "line": 15, + "col": 1 + }, + { + "line": 17, + "col": 24 + } + ] + } + ], + "title": [ + { + "name": "text", + "type": "string", + "value": "Unnumbered", + "location": [ + { + "line": 15, + "col": 2 + }, + { + "line": 15, + "col": 11 + } + ] + } + ], + "location": [ + { + "line": 15, + "col": 1 + }, + { + "line": 17, + "col": 24 + } + ] + }, + { + "name": "figure-caption", + "type": "attribute", + "value": "Later", + "location": [ + { + "line": 19, + "col": 1 + }, + { + "line": 19, + "col": 22 + } + ] + }, + { + "name": "label", + "type": "attribute", + "value": "Late", + "location": [ + { + "line": 20, + "col": 1 + }, + { + "line": 20, + "col": 12 + } + ] + }, + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "attributes": { + "height": "200", + "width": "320" + }, + "anchors": [ + { + "id": "last", + "location": [ + { + "line": 23, + "col": 1 + }, + { + "line": 23, + "col": 8 + } + ] + } + ] + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Last", + "location": [ + { + "line": 22, + "col": 2 + }, + { + "line": 22, + "col": 5 + } + ] + } + ], + "alt": [ + { + "name": "text", + "type": "string", + "value": "Alt Late", + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 24, + "col": 22 + } + ] + } + ], + "source": { + "type": "path", + "value": "generated.svg" + }, + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 24, + "col": 22 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "See ", + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 26, + "col": 4 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "image", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 5 + }, + { + "line": 26, + "col": 13 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ", ", + "location": [ + { + "line": 26, + "col": 14 + }, + { + "line": 26, + "col": 15 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "literal", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 16 + }, + { + "line": 26, + "col": 26 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ", ", + "location": [ + { + "line": 26, + "col": 27 + }, + { + "line": 26, + "col": 28 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "disabled", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 29 + }, + { + "line": 26, + "col": 40 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ", and ", + "location": [ + { + "line": 26, + "col": 41 + }, + { + "line": 26, + "col": 46 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "last", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 47 + }, + { + "line": 26, + "col": 54 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ".", + "location": [ + { + "line": 26, + "col": 55 + }, + { + "line": 26, + "col": 55 + } + ] + } + ], + "metadata": { + "id": { + "id": "_acdc_9", + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 26, + "col": 55 + } + ] + } + }, + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 26, + "col": 55 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "[{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(1) }\",\"context\":\"Image\",\"id\":\"image\",\"label\":\"Early\",\"raw_title\":\"Image *{label}*\",\"section\":null,\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":5},{\"caption\":\"CustomContent(ContentRef { nodes: [BoldText(Bold { role: None, id: None, form: Constrained, content: [PlainText(Plain { content: \\\"Custom\\\", location: Location { absolute_start: 184, absolute_end: 189, start: Position { line: 10, column: 21, file: None }, end: Position { line: 10, column: 26, file: None } }, escaped: false })], location: Location { absolute_start: 183, absolute_end: 190, start: Position { line: 10, column: 20, file: None }, end: Position { line: 10, column: 27, file: None } } }), PlainText(Plain { content: \\\" \\\", location: Location { absolute_start: 191, absolute_end: 191, start: Position { line: 10, column: 28, file: None }, end: Position { line: 10, column: 28, file: None } }, escaped: false })] })\",\"context\":\"Literal\",\"id\":\"literal\",\"label\":\"Early\",\"raw_title\":\"Text *{label}*\",\"section\":null,\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":9},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null},{\"caption\":\"Unnumbered\",\"context\":\"Literal\",\"id\":\"disabled\",\"label\":\"Early\",\"raw_title\":\"Unnumbered\",\"section\":null,\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":15},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null},{\"caption\":\"Numbered { kind: Figure, label: \\\"Later\\\", number: Some(2) }\",\"context\":\"Image\",\"id\":\"last\",\"label\":\"Late\",\"raw_title\":\"Last\",\"section\":null,\"substitutions\":[\"special_chars\",\"quotes\",\"attributes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":22},{\"caption\":null,\"context\":\"Paragraph\",\"id\":\"_acdc_9\",\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null}]", + "location": [ + { + "line": 28, + "col": 1 + }, + { + "line": 28, + "col": 9 + } + ] + } + ], + "location": [ + { + "line": 28, + "col": 1 + }, + { + "line": 28, + "col": 9 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 28, + "col": 9 + } + ] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/extensions/construction.draft.diagnostics.json b/acdc-parser/fixtures/tests/extensions/construction.draft.diagnostics.json new file mode 100644 index 000000000..849eafd43 --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/construction.draft.diagnostics.json @@ -0,0 +1,4 @@ +{ + "recovery": null, + "warnings": [] +} \ No newline at end of file diff --git a/acdc-parser/fixtures/tests/extensions/construction.draft.json b/acdc-parser/fixtures/tests/extensions/construction.draft.json new file mode 100644 index 000000000..06b57808a --- /dev/null +++ b/acdc-parser/fixtures/tests/extensions/construction.draft.json @@ -0,0 +1,751 @@ +{ + "name": "document", + "type": "block", + "header": { + "title": [ + { + "name": "text", + "type": "string", + "value": "Host construction", + "location": [ + { + "line": 1, + "col": 3 + }, + { + "line": 1, + "col": 19 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 3, + "col": 24 + } + ] + }, + "attributes": { + "figure-caption": "Picture", + "label": "Early" + }, + "blocks": [ + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "attributes": { + "height": "200", + "width": "320" + }, + "reftext": [ + { + "name": "text", + "type": "string", + "value": "Diagram ", + "location": [ + { + "line": 6, + "col": 30 + }, + { + "line": 6, + "col": 37 + } + ] + }, + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "label", + "location": [ + { + "line": 6, + "col": 39 + }, + { + "line": 6, + "col": 43 + } + ] + } + ], + "location": [ + { + "line": 6, + "col": 38 + }, + { + "line": 6, + "col": 44 + } + ] + } + ], + "roles": [ + "keep" + ], + "options": [ + "nowrap" + ], + "id": { + "id": "image", + "location": [ + { + "line": 6, + "col": 3 + }, + { + "line": 6, + "col": 7 + } + ] + } + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Image ", + "location": [ + { + "line": 5, + "col": 2 + }, + { + "line": 5, + "col": 7 + } + ] + }, + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Early", + "location": [ + { + "line": 5, + "col": 9 + }, + { + "line": 5, + "col": 15 + } + ] + } + ], + "location": [ + { + "line": 5, + "col": 8 + }, + { + "line": 5, + "col": 16 + } + ] + } + ], + "alt": [ + { + "name": "raw", + "type": "string", + "value": "Alt Early", + "substitutions": [ + "special_chars" + ], + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 7, + "col": 22 + } + ] + } + ], + "source": { + "type": "path", + "value": "generated.svg" + }, + "location": [ + { + "line": 5, + "col": 1 + }, + { + "line": 7, + "col": 22 + } + ] + }, + { + "name": "literal", + "type": "block", + "form": "delimited", + "delimiter": "....", + "metadata": { + "caption": [ + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Custom", + "location": [ + { + "line": 10, + "col": 21 + }, + { + "line": 10, + "col": 26 + } + ] + } + ], + "location": [ + { + "line": 10, + "col": 20 + }, + { + "line": 10, + "col": 27 + } + ] + }, + { + "name": "text", + "type": "string", + "value": " ", + "location": [ + { + "line": 10, + "col": 28 + }, + { + "line": 10, + "col": 28 + } + ] + } + ], + "id": { + "id": "literal", + "location": [ + { + "line": 10, + "col": 3 + }, + { + "line": 10, + "col": 9 + } + ] + } + }, + "inlines": [ + { + "name": "text", + "type": "string", + "value": "<&>\n*literal*\n spaces", + "location": [ + { + "line": 9, + "col": 1 + }, + { + "line": 11, + "col": 24 + } + ] + } + ], + "title": [ + { + "name": "text", + "type": "string", + "value": "Text ", + "location": [ + { + "line": 9, + "col": 2 + }, + { + "line": 9, + "col": 6 + } + ] + }, + { + "name": "span", + "type": "inline", + "variant": "strong", + "form": "constrained", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "Early", + "location": [ + { + "line": 9, + "col": 8 + }, + { + "line": 9, + "col": 14 + } + ] + } + ], + "location": [ + { + "line": 9, + "col": 7 + }, + { + "line": 9, + "col": 15 + } + ] + } + ], + "location": [ + { + "line": 9, + "col": 1 + }, + { + "line": 11, + "col": 24 + } + ] + }, + { + "name": "figure-caption", + "type": "attribute", + "value": false, + "location": [ + { + "line": 13, + "col": 1 + }, + { + "line": 13, + "col": 17 + } + ] + }, + { + "name": "literal", + "type": "block", + "form": "delimited", + "delimiter": "....", + "metadata": { + "anchors": [ + { + "id": "disabled", + "location": [ + { + "line": 16, + "col": 1 + }, + { + "line": 16, + "col": 12 + } + ] + } + ] + }, + "inlines": [ + { + "name": "text", + "type": "string", + "value": "<&>\n*literal*\n spaces", + "location": [ + { + "line": 15, + "col": 1 + }, + { + "line": 17, + "col": 24 + } + ] + } + ], + "title": [ + { + "name": "text", + "type": "string", + "value": "Unnumbered", + "location": [ + { + "line": 15, + "col": 2 + }, + { + "line": 15, + "col": 11 + } + ] + } + ], + "location": [ + { + "line": 15, + "col": 1 + }, + { + "line": 17, + "col": 24 + } + ] + }, + { + "name": "figure-caption", + "type": "attribute", + "value": "Later", + "location": [ + { + "line": 19, + "col": 1 + }, + { + "line": 19, + "col": 22 + } + ] + }, + { + "name": "label", + "type": "attribute", + "value": "Late", + "location": [ + { + "line": 20, + "col": 1 + }, + { + "line": 20, + "col": 12 + } + ] + }, + { + "name": "image", + "type": "block", + "form": "macro", + "metadata": { + "attributes": { + "height": "200", + "width": "320" + }, + "anchors": [ + { + "id": "last", + "location": [ + { + "line": 23, + "col": 1 + }, + { + "line": 23, + "col": 8 + } + ] + } + ] + }, + "title": [ + { + "name": "text", + "type": "string", + "value": "Last", + "location": [ + { + "line": 22, + "col": 2 + }, + { + "line": 22, + "col": 5 + } + ] + } + ], + "alt": [ + { + "name": "raw", + "type": "string", + "value": "Alt Late", + "substitutions": [ + "special_chars" + ], + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 24, + "col": 22 + } + ] + } + ], + "source": { + "type": "path", + "value": "generated.svg" + }, + "location": [ + { + "line": 22, + "col": 1 + }, + { + "line": 24, + "col": 22 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "See ", + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 26, + "col": 4 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "image", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 5 + }, + { + "line": 26, + "col": 13 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ", ", + "location": [ + { + "line": 26, + "col": 14 + }, + { + "line": 26, + "col": 15 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "literal", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 16 + }, + { + "line": 26, + "col": 26 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ", ", + "location": [ + { + "line": 26, + "col": 27 + }, + { + "line": 26, + "col": 28 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "disabled", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 29 + }, + { + "line": 26, + "col": 40 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ", and ", + "location": [ + { + "line": 26, + "col": 41 + }, + { + "line": 26, + "col": 46 + } + ] + }, + { + "name": "xref", + "type": "inline", + "target": "last", + "target_is_local": true, + "location": [ + { + "line": 26, + "col": 47 + }, + { + "line": 26, + "col": 54 + } + ] + }, + { + "name": "text", + "type": "string", + "value": ".", + "location": [ + { + "line": 26, + "col": 55 + }, + { + "line": 26, + "col": 55 + } + ] + } + ], + "metadata": { + "id": { + "id": "_acdc_9", + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 26, + "col": 55 + } + ] + } + }, + "location": [ + { + "line": 26, + "col": 1 + }, + { + "line": 26, + "col": 55 + } + ] + }, + { + "name": "paragraph", + "type": "block", + "inlines": [ + { + "name": "text", + "type": "string", + "value": "[{\"caption\":\"Numbered { kind: Figure, label: \\\"Picture\\\", number: Some(1) }\",\"context\":\"Image\",\"id\":\"image\",\"label\":\"Early\",\"raw_title\":\"Image *{label}*\",\"section\":null,\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":5},{\"caption\":\"CustomContent(ContentRef { nodes: [BoldText(Bold { role: None, id: None, form: Constrained, content: [PlainText(Plain { content: \\\"Custom\\\", location: Location { absolute_start: 184, absolute_end: 189, start: Position { line: 10, column: 21, file: None }, end: Position { line: 10, column: 26, file: None } }, escaped: false })], location: Location { absolute_start: 183, absolute_end: 190, start: Position { line: 10, column: 20, file: None }, end: Position { line: 10, column: 27, file: None } } }), PlainText(Plain { content: \\\" \\\", location: Location { absolute_start: 191, absolute_end: 191, start: Position { line: 10, column: 28, file: None }, end: Position { line: 10, column: 28, file: None } }, escaped: false })] })\",\"context\":\"Literal\",\"id\":\"literal\",\"label\":\"Early\",\"raw_title\":\"Text *{label}*\",\"section\":null,\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":9},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null},{\"caption\":\"Unnumbered\",\"context\":\"Literal\",\"id\":\"disabled\",\"label\":\"Early\",\"raw_title\":\"Unnumbered\",\"section\":null,\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":15},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null},{\"caption\":null,\"context\":\"DocumentAttribute\",\"id\":null,\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null},{\"caption\":\"Numbered { kind: Figure, label: \\\"Later\\\", number: Some(2) }\",\"context\":\"Image\",\"id\":\"last\",\"label\":\"Late\",\"raw_title\":\"Last\",\"section\":null,\"substitutions\":[\"special_chars\",\"attributes\",\"quotes\",\"replacements\",\"macros\",\"post_replacements\",\"callouts\"],\"title_line\":22},{\"caption\":null,\"context\":\"Paragraph\",\"id\":\"_acdc_9\",\"label\":null,\"raw_title\":null,\"section\":null,\"substitutions\":null,\"title_line\":null}]", + "location": [ + { + "line": 28, + "col": 1 + }, + { + "line": 28, + "col": 9 + } + ] + } + ], + "location": [ + { + "line": 28, + "col": 1 + }, + { + "line": 28, + "col": 9 + } + ] + } + ], + "location": [ + { + "line": 1, + "col": 1 + }, + { + "line": 28, + "col": 9 + } + ] +} \ No newline at end of file diff --git a/acdc-parser/src/extensions/tests/support.rs b/acdc-parser/src/extensions/tests/support.rs index f986269a8..18adb2cfe 100644 --- a/acdc-parser/src/extensions/tests/support.rs +++ b/acdc-parser/src/extensions/tests/support.rs @@ -1,7 +1,7 @@ #![allow(clippy::expect_used)] use acdc_parser::{ - ElementAttributes, Error, + CaptionKind, ElementAttributes, Error, extensions::{ BlockBuilder, BlockMacro, BlockMacroOutput, BlockMacroProcessor, DocumentEditor, MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, @@ -63,12 +63,46 @@ pub(super) fn registry() -> Registry { builder .register(BlockMacro::new("query", || Defer)) .expect("valid query fixture macro"); + builder + .register(BlockMacro::new("fixture-build", || Defer)) + .expect("valid construction fixture macro"); + builder + .register_tree_processor(TreeProcessorRegistration::new("construct", || Construct)) + .expect("valid construction fixture processor"); builder .register_tree_processor(TreeProcessorRegistration::new("query", || Query)) .expect("valid query fixture processor"); builder.build() } +struct Construct; + +impl TreeProcessor for Construct { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let requests: Vec<_> = editor + .deferred_blocks() + .iter() + .filter(|request| request.invocation.name == "fixture-build") + .map(|request| { + ( + request.target().clone(), + request.invocation.target.to_string(), + ) + }) + .collect(); + for (target, format) in requests { + let content = if format == "image" { + BlockBuilder::image("generated.svg").with_attributes("'Alt {label}',320,200") + } else { + BlockBuilder::literal("<&>\n*literal*\n spaces") + .with_caption_kind(CaptionKind::Figure) + }; + editor.replace_placeholder(&target, content)?; + } + Ok(()) + } +} + struct Query; impl TreeProcessor for Query { diff --git a/converters/html/tests/extension_construction.rs b/converters/html/tests/extension_construction.rs new file mode 100644 index 000000000..b8d69bbf3 --- /dev/null +++ b/converters/html/tests/extension_construction.rs @@ -0,0 +1,99 @@ +//! A diagram-shaped consumer using only public extension contracts. +use acdc_converters_core::{Converter as _, Options}; +use acdc_converters_html::{Converter, RenderOptions}; +use acdc_parser::{ + CaptionKind, CompatibilityMode, Error, + ast::{AttributeValueRef, BlockKind}, + extensions::{ + BlockBuilder, BlockContext, BlockMacro, BlockMacroOutput, DocumentEditor, MacroInvocation, + Registry, TreeProcessor, TreeProcessorRegistration, + }, +}; + +struct DiagramProducer; +impl TreeProcessor for DiagramProducer { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let diagrams: Vec<_> = editor + .query() + .select(BlockContext::Listing) + .filter(|view| { + view.attributes() + .and_then(|attributes| attributes.get("style")) + .is_some_and(|style| matches!(style, AttributeValueRef::Text("diagram"))) + }) + .map(|view| view.target().clone()) + .collect(); + for target in diagrams { + editor.replace_block( + &target, + BlockBuilder::image("diagram.svg") + .with_attributes("'Alt <&>',320,200,link=target.html"), + )?; + } + let requests: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| request.target().clone()) + .collect(); + for target in requests { + editor.replace_placeholder( + &target, + BlockBuilder::literal("<&>\n*literal*\n spaces") + .with_caption_kind(CaptionKind::Figure), + )?; + } + Ok(()) + } +} + +#[test] +fn diagram_consumer_builds_images_and_literal_figures_with_normal_rendering() +-> Result<(), Box> { + let source = "= Diagrams\n:imagesdir: images\n:figure-caption: Picture\n:label: Early\n\n.Image *{label}*\n[#diagram.diagram-role%nowrap,reftext='Caption *label*']\n[diagram]\n----\na -> b\n----\n\n.Text *{label}*\n[#text]\ndiagram::text[]\n\n:label: Late\n\nSee <> and <>."; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("diagram", || { + |_: &MacroInvocation<'_>, _: &mut acdc_parser::extensions::MacroExecutionContext| { + Ok(BlockMacroOutput::Deferred) + } + }))?; + builder.register_tree_processor(TreeProcessorRegistration::new("diagram", || { + DiagramProducer + }))?; + let converter = Converter::new( + Options::builder().embedded(true).build(), + acdc_parser::Options::builder().with_compatibility_mode(mode), + )?; + let mut working = builder.build().parse(source, converter.parser_options())?; + let image = working + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")?; + assert!(matches!(image.block().kind(), BlockKind::Image(_))); + working.normalize()?; + working.normalize()?; + let parsed = working.finish()?; + assert_eq!(parsed.warnings(), []); + let render = RenderOptions { + embedded: true, + ..Default::default() + }; + let html = converter.convert_to_string(parsed.document(), &render)?; + assert!(html.contains("src=\"images/diagram.svg\""), "{html}"); + assert!(html.contains("alt=\"Alt <&>\""), "{html}"); + assert!( + html.contains("Picture 1. Image Early"), + "{html}" + ); + assert!( + html.contains("Picture 2. Text Early"), + "{html}" + ); + assert!(html.contains("<&>\n*literal*"), "{html}"); + assert!(!html.contains("&lt;"), "{html}"); + assert!(html.contains("href=\"#diagram\""), "{html}"); + assert!(html.contains("href=\"#text\""), "{html}"); + } + Ok(()) +} From 87353891a7b2c8210c6c429fa6bf62d8144b6ef0 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 15 Nov 2026 17:25:40 +0100 Subject: [PATCH 17/55] feat(extensions): capture and resolve deferred display content Freeze selected titles and source context behind document-local target identities. Bind final captions and output IDs after edits, then let converter core request ordinary explicit cross-reference labels from parser-owned builders. Accept literal and structured list items through the same constructor. --- acdc-parser/CHANGELOG.md | 11 + .../schemas/asg/support-inventory.json | 12 + acdc-parser/src/asg/references.rs | 6 + acdc-parser/src/ast/blocks.rs | 6 + acdc-parser/src/ast/inlines/xrefs.rs | 8 + acdc-parser/src/extensions/builder.rs | 108 ++++- acdc-parser/src/extensions/display.rs | 452 ++++++++++++++++++ .../src/extensions/display/prepared.rs | 197 ++++++++ acdc-parser/src/extensions/editor.rs | 6 +- .../src/extensions/editor/transaction.rs | 15 +- acdc-parser/src/extensions/mod.rs | 14 + acdc-parser/src/extensions/query.rs | 2 +- acdc-parser/src/extensions/session.rs | 3 +- acdc-parser/src/extensions/tests/display.rs | 372 ++++++++++++++ acdc-parser/src/extensions/tests/mod.rs | 1 + acdc-parser/src/grammar/document/finish.rs | 1 + acdc-parser/src/grammar/location_walk.rs | 2 +- acdc-parser/src/grammar/mod.rs | 1 + acdc-parser/src/model/inlines/macros.rs | 3 + acdc-parser/src/model/inlines/mod.rs | 6 + acdc-parser/src/model/mod.rs | 1 + acdc-parser/src/parsed.rs | 4 + converters/core/CHANGELOG.md | 4 + converters/core/src/display.rs | 43 ++ converters/core/src/lib.rs | 1 + 25 files changed, 1252 insertions(+), 27 deletions(-) create mode 100644 acdc-parser/src/extensions/display.rs create mode 100644 acdc-parser/src/extensions/display/prepared.rs create mode 100644 acdc-parser/src/extensions/tests/display.rs create mode 100644 converters/core/src/display.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 604dc1e6b..b386b21f7 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Tree processors can capture titles with `DocumentEditor::capture()` and build + caption, title, or caption-and-title links through `DisplayIntent` and the inline + block builders. `BlockBuilder::unordered_list()` accepts both literal strings + and structured inline items. Titles keep their original substitutions and + attributes; + captions and renamed IDs follow surviving targets at finalization. Removed + targets produce located unresolved-reference warnings and cannot bind to reused + IDs. Custom converters prepare these requests through converter core before + traversal or checked ASG export. Unlike string-based Asciidoctor extensions, + later attribute edits do not refresh captured titles. + - The end of the document header now follows the compatibility mode. Asciidoctor mode matches Asciidoctor and ignores empty lines before the document title: attribute entries, comments, block anchors, and attribute lists above the diff --git a/acdc-parser/schemas/asg/support-inventory.json b/acdc-parser/schemas/asg/support-inventory.json index 5b23b5ac3..72cb2ffb2 100644 --- a/acdc-parser/schemas/asg/support-inventory.json +++ b/acdc-parser/schemas/asg/support-inventory.json @@ -1312,6 +1312,7 @@ "shape": { "kind": "struct", "fields": [ + "generated_display", "target", "target_is_local", "text", @@ -1384,6 +1385,9 @@ }, "document_reftext": { "policy": "named-document-label-context" + }, + "generated_display": { + "policy": "reject-symbolic-display-until-conversion-context-lowers-to-ordinary-link" } }, "strict_export_group": "references" @@ -4444,6 +4448,7 @@ "shape": { "kind": "struct", "fields": [ + "generated_displays", "header", "untitled_header_location", "attributes", @@ -4487,6 +4492,9 @@ "location": { "policy": "use-authored-endpoint-coordinates-omit-an-unavailable", "upstream": "#/$defs/location" + }, + "generated_displays": { + "policy": "source-state" } }, "strict_export_group": "core" @@ -5914,6 +5922,10 @@ "named-document-label-context": { "handling": "context-dependent", "reason": "The named profile retains the document label selected at an automatic reference, including empty content for title fallback and known declaration locations. Strict upstream export rejects this context. Authored inline text remains separate." + }, + "reject-symbolic-display-until-conversion-context-lowers-to-ordinary-link": { + "handling": "reject", + "reason": "Generated display intent and frozen titles must be lowered into ordinary explicit cross-reference labels by a conversion context before either checked ASG profile is exported." } }, "strict_export_groups": { diff --git a/acdc-parser/src/asg/references.rs b/acdc-parser/src/asg/references.rs index 3d3743495..bb2f2001a 100644 --- a/acdc-parser/src/asg/references.rs +++ b/acdc-parser/src/asg/references.rs @@ -143,6 +143,12 @@ fn cross_reference( path: &str, settings: InlineContext, ) -> Result { + if xref.generated_display.is_some() { + return Err(unsupported( + &pointer(path, "generated_display"), + "resolve generated display content in a conversion context before ASG export", + )); + } for (present, property) in [ (xref.xrefstyle != XrefStyle::Default, "xrefstyle"), ( diff --git a/acdc-parser/src/ast/blocks.rs b/acdc-parser/src/ast/blocks.rs index 03599d87b..0af37945a 100644 --- a/acdc-parser/src/ast/blocks.rs +++ b/acdc-parser/src/ast/blocks.rs @@ -222,6 +222,11 @@ impl<'doc> BlockRef<'doc> { } impl<'doc> DocumentRef<'doc> { + /// Whether conversion must lower symbolic display requests first. + #[must_use] + pub fn has_deferred_displays(self) -> bool { + self.node.generated_displays.is_active() + } /// The highest stored caption ordinal for this category, or zero if none is assigned. /// /// Scans the block tree, including nested lists and table cells, without @@ -523,6 +528,7 @@ impl<'doc> From> for Document<'doc> { location: header.location.clone(), }), untitled_header_location: document.untitled_header_location.clone(), + generated_displays: document.generated_displays.clone(), attributes: document.attributes.clone(), blocks: document.blocks.clone(), footnotes: document.footnotes.clone(), diff --git a/acdc-parser/src/ast/inlines/xrefs.rs b/acdc-parser/src/ast/inlines/xrefs.rs index 03bba71dd..9028f1927 100644 --- a/acdc-parser/src/ast/inlines/xrefs.rs +++ b/acdc-parser/src/ast/inlines/xrefs.rs @@ -6,6 +6,14 @@ use crate::{ use super::CrossReferenceRef; impl<'doc> CrossReferenceRef<'doc> { + /// A symbolic label that converter core must lower before rendering. + #[must_use] + pub fn generated_display(self) -> Option> { + self.node + .generated_display + .as_deref() + .map(crate::extensions::GeneratedDisplayRef::new) + } /// Effective target after local reference resolution. #[must_use] pub fn target(self) -> &'doc str { diff --git a/acdc-parser/src/extensions/builder.rs b/acdc-parser/src/extensions/builder.rs index de4d7e82f..25f4154c8 100644 --- a/acdc-parser/src/extensions/builder.rs +++ b/acdc-parser/src/extensions/builder.rs @@ -1,5 +1,6 @@ use std::sync::Arc; +use super::InlineBuilder; use bumpalo::Bump; use crate::{ @@ -45,7 +46,8 @@ pub struct BlockBuilder { #[derive(Clone, Debug)] pub(crate) enum Content { Paragraph(String), - UnorderedList(Vec), + UnorderedList(Vec), + ParagraphInlines(Vec), Image(String), Literal(String), Listing(String), @@ -66,7 +68,7 @@ impl BlockBuilder { return self.caption; } match &self.content { - Content::Paragraph(_) => CaptionKind::for_style(style), + Content::Paragraph(_) | Content::ParagraphInlines(_) => CaptionKind::for_style(style), Content::Image(_) => Some(CaptionKind::Figure), Content::Listing(_) => CaptionKind::for_verbatim(style, Some(CaptionKind::Listing)), Content::Literal(_) => CaptionKind::for_verbatim(style, None), @@ -92,14 +94,49 @@ impl BlockBuilder { Self::new(Content::Paragraph(text.into())) } - /// Build an unordered list whose items contain literal text. + /// Build an unordered list with literal text or structured inline content. + /// + /// Strings remain literal. Arrays and vectors of [`InlineBuilder`] group + /// fragments into one item; an individual builder can also be an item. + /// + /// ``` + /// use acdc_parser::extensions::{BlockBuilder, InlineBuilder}; + /// + /// let literal = BlockBuilder::unordered_list(["One", "Two"]); + /// let owned = BlockBuilder::unordered_list(vec![String::from("Owned")]); + /// let structured = BlockBuilder::unordered_list([ + /// InlineBuilder::text("Literal *markup*"), + /// InlineBuilder::from([ + /// InlineBuilder::text("Several "), + /// InlineBuilder::text("fragments"), + /// ]), + /// ]); + /// ``` #[must_use] - pub fn unordered_list(items: impl IntoIterator>) -> Self { + pub fn unordered_list(items: impl IntoIterator>) -> Self { Self::new(Content::UnorderedList( items.into_iter().map(Into::into).collect(), )) } + /// Build a paragraph from literal text and captured display requests. + #[must_use] + pub fn paragraph_inlines(content: impl IntoIterator) -> Self { + Self::new(Content::ParagraphInlines(content.into_iter().collect())) + } + + pub(super) fn has_displays(&self) -> bool { + match &self.content { + Content::ParagraphInlines(content) | Content::UnorderedList(content) => { + content.iter().any(InlineBuilder::has_displays) + } + Content::Paragraph(_) + | Content::Image(_) + | Content::Literal(_) + | Content::Listing(_) => false, + } + } + /// Build an ordinary image without interpreting its target as markup. #[must_use] pub fn image(target: impl Into) -> Self { @@ -161,6 +198,7 @@ impl BlockBuilder { location: Location, mut metadata: BlockMetadata<'a>, title: Title<'a>, + mut inline: impl FnMut(InlineBuilder) -> Result>, crate::Error>, ) -> Result, crate::Error> { if let Some(id) = self.id { metadata.id = Some(Anchor::new(arena.alloc_str(&id), location.clone())); @@ -179,23 +217,30 @@ impl BlockBuilder { block.title = title; Block::Paragraph(block) } - Content::UnorderedList(items) => Block::UnorderedList(UnorderedList { - title, - metadata, - items: items + Content::UnorderedList(items) => build_list( + items .into_iter() - .map(|text| ListItem { - level: 1, - marker: "*", - checked: None, - principal: plain(&text), - blocks: Vec::new(), - location: location.clone(), - }) - .collect(), - marker: "*", + .map(&mut inline) + .collect::, _>>()?, location, - }), + metadata, + title, + ), + Content::ParagraphInlines(content) => { + let mut block = Paragraph::new( + content + .into_iter() + .map(&mut inline) + .collect::, _>>()? + .into_iter() + .flatten() + .collect(), + location, + ); + block.metadata = metadata; + block.title = title; + Block::Paragraph(block) + } Content::Image(target) => Block::Image(Image { source: Source::from_str_borrowed(arena.alloc_str(&target))?, alt: None, @@ -211,6 +256,31 @@ impl BlockBuilder { } } +fn build_list<'a>( + items: Vec>>, + location: Location, + metadata: BlockMetadata<'a>, + title: Title<'a>, +) -> Block<'a> { + Block::UnorderedList(UnorderedList { + title, + metadata, + marker: "*", + items: items + .into_iter() + .map(|principal| ListItem { + level: 1, + marker: "*", + checked: None, + principal, + blocks: Vec::new(), + location: location.clone(), + }) + .collect(), + location, + }) +} + fn build_verbatim<'a>( arena: &'a Bump, text: &str, diff --git a/acdc-parser/src/extensions/display.rs b/acdc-parser/src/extensions/display.rs new file mode 100644 index 000000000..a7d3b270f --- /dev/null +++ b/acdc-parser/src/extensions/display.rs @@ -0,0 +1,452 @@ +//! Frozen selections and declarative inline display requests. + +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; + +use bumpalo::Bump; + +use crate::{ + Caption, CrossReference, Document, Error, InlineMacro, InlineNode, Plain, SourceLocation, + Title, + ast::{CaptionRef, ContentRef}, + grammar::walk_document_inline_nodes_mut, +}; + +use super::{ + DocumentEditor, ExtensionParseResult, TargetId, TitleSource, target::DocumentIdentity, +}; + +mod prepared; +pub use prepared::{DisplayLabel, PreparedDocument}; + +/// Explicit link content, independently of a target's generic reference label. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub enum DisplayIntent { + /// Link the finalized caption prefix. + Caption, + /// Link the title captured during selection. + Title, + /// Link the finalized caption, then append the captured title outside the link. + CaptionAndTitle, +} + +/// An immutable selection belonging to one working document. +#[derive(Clone, Debug)] +pub struct CapturedTarget { + document: DocumentIdentity, + selection: usize, +} + +impl CapturedTarget { + /// Describe an inline reference without allocating document storage. + #[must_use] + pub fn display(&self, intent: DisplayIntent) -> InlineBuilder { + InlineBuilder(vec![InlineContent::Display(self.clone(), intent)]) + } +} + +/// Inline content composed of literal text and symbolic display requests. +/// +/// Strings become literal text. Arrays and vectors of builders group fragments +/// into one content value without interpreting markup or invoking processors. +#[derive(Clone, Debug)] +pub struct InlineBuilder(Vec); + +#[derive(Clone, Debug)] +enum InlineContent { + Text(String), + Display(CapturedTarget, DisplayIntent), +} + +impl InlineBuilder { + /// Literal text, escaped by the ordinary converter pipeline. + #[must_use] + pub fn text(text: impl Into) -> Self { + Self(vec![InlineContent::Text(text.into())]) + } + + pub(super) fn has_displays(&self) -> bool { + self.0 + .iter() + .any(|content| matches!(content, InlineContent::Display(..))) + } + + pub(super) fn build<'a>( + self, + arena: &'a Bump, + document: &Document<'a>, + identity: &DocumentIdentity, + origin: &SourceLocation, + ) -> Result>, Error> { + let mut nodes = Vec::new(); + for content in self.0 { + nodes.extend(content.build(arena, document, identity, origin)?); + } + Ok(nodes) + } +} + +impl From for InlineBuilder { + fn from(text: String) -> Self { + Self::text(text) + } +} + +impl From<&str> for InlineBuilder { + fn from(text: &str) -> Self { + Self::text(text) + } +} + +impl From<&String> for InlineBuilder { + fn from(text: &String) -> Self { + Self::text(text) + } +} + +impl FromIterator for InlineBuilder { + fn from_iter>(content: T) -> Self { + Self(content.into_iter().flat_map(|inline| inline.0).collect()) + } +} + +impl From> for InlineBuilder { + fn from(content: Vec) -> Self { + content.into_iter().collect() + } +} + +impl From<[InlineBuilder; N]> for InlineBuilder { + fn from(content: [InlineBuilder; N]) -> Self { + content.into_iter().collect() + } +} + +impl InlineContent { + fn build<'a>( + self, + arena: &'a Bump, + document: &Document<'a>, + identity: &DocumentIdentity, + origin: &SourceLocation, + ) -> Result>, Error> { + let (target, intent) = match self { + InlineContent::Text(text) => return Ok(vec![plain(arena.alloc_str(&text), origin)]), + InlineContent::Display(target, intent) => (target, intent), + }; + if target.document != *identity { + return Err(failure( + origin, + "display selection belongs to another document", + )); + } + let selection = document + .generated_displays + .selection(target.selection) + .ok_or_else(|| failure(origin, "display selection is absent"))?; + let mut xref = CrossReference::new(selection.id, origin.location.clone()); + xref.target_is_local = true; + xref.generated_display = Some(Box::new(GeneratedDisplay { + selection: Arc::clone(selection), + intent, + origin: origin.clone(), + resolved: None, + })); + let mut nodes = vec![InlineNode::Macro(InlineMacro::CrossReference(Box::new( + xref, + )))]; + if intent == DisplayIntent::CaptionAndTitle && selection.title.is_present() { + nodes.push(plain(" ", origin)); + nodes.extend(selection.title.as_inlines().iter().cloned()); + } + Ok(nodes) + } +} + +fn plain<'a>(text: &'a str, origin: &SourceLocation) -> InlineNode<'a> { + InlineNode::PlainText(Plain { + content: text, + location: origin.location.clone(), + escaped: true, + }) +} + +#[derive(Clone, Debug, PartialEq)] +struct Selection<'a> { + target: usize, + id: &'a str, + title: Title<'a>, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct GeneratedDisplay<'a> { + selection: Arc>, + intent: DisplayIntent, + origin: SourceLocation, + resolved: Option>, +} + +#[derive(Clone, Debug, PartialEq)] +struct ResolvedTarget<'a> { + id: &'a str, + caption: Option>, + missing: bool, +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct DisplayState<'a>(Option>>); + +#[derive(Clone, Debug, Default)] +struct Selections<'a> { + captured: Vec>>, + active: bool, +} + +// This cache is not semantic document content. Requests themselves participate +// in cross-reference equality, and neither output nor identity depends on the cache. +impl PartialEq for DisplayState<'_> { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl<'a> DisplayState<'a> { + fn selection(&self, index: usize) -> Option<&Arc>> { + self.0.as_ref()?.captured.get(index) + } + + pub(crate) fn is_active(&self) -> bool { + self.0.as_ref().is_some_and(|state| state.active) + } + + pub(super) fn activate(&mut self) { + self.0.get_or_insert_with(Default::default).active = true; + } +} + +impl DocumentEditor<'_> { + /// Freeze a target's title and source context, assigning an output ID when needed. + /// Later edits do not refresh this selection. The target may subsequently be removed. + /// + /// # Errors + /// Rejects foreign, removed, and unreferenceable targets. + pub fn capture(&mut self, target: &TargetId) -> Result { + self.ensure_id(target)?; + let path = self.path(target)?; + let origin = self.location(target); + let selection = self.result.parsed.with_document_mut(|_, document| { + let block = path + .get(&document.blocks) + .ok_or_else(|| failure(&origin, "target is absent"))?; + let selected = Selection { + target: target.slot, + id: super::query::output_id(block) + .ok_or_else(|| failure(&origin, "output ID is absent"))?, + title: block.title().cloned().unwrap_or_default(), + }; + let state = document + .generated_displays + .0 + .get_or_insert_with(Default::default); + let index = state.captured.len(); + state.captured.push(Arc::new(selected)); + Ok::<_, Error>(index) + })?; + Ok(CapturedTarget { + document: target.document.clone(), + selection, + }) + } +} + +/// Read-only display intent after structural finalization. +#[derive(Clone, Copy, Debug)] +pub struct GeneratedDisplayRef<'doc>(&'doc GeneratedDisplay<'doc>); + +impl<'doc> GeneratedDisplayRef<'doc> { + pub(crate) const fn new(value: &'doc GeneratedDisplay<'doc>) -> Self { + Self(value) + } + #[must_use] + pub fn intent(self) -> DisplayIntent { + self.0.intent + } + #[must_use] + pub fn title(self) -> Option> { + self.0.selection.title.content() + } + #[must_use] + pub fn title_source(self) -> Option<&'doc TitleSource<'doc>> { + self.0.selection.title.source() + } + #[must_use] + pub fn caption(self) -> Option> { + self.0 + .resolved + .as_ref()? + .caption + .as_ref() + .map(CaptionRef::from) + } + #[must_use] + pub fn target(self) -> &'doc str { + self.0 + .resolved + .as_ref() + .filter(|target| !target.missing) + .map_or(self.0.selection.id, |target| target.id) + } + #[must_use] + pub fn is_missing(self) -> bool { + self.0.resolved.as_ref().is_none_or(|target| target.missing) + } +} + +impl serde::Serialize for GeneratedDisplayRef<'_> { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeMap as _; + let mut map = serializer.serialize_map(None)?; + map.serialize_entry("intent", &self.0.intent)?; + if self.0.selection.title.is_present() { + map.serialize_entry("title", &self.0.selection.title)?; + } + if let Some(target) = &self.0.resolved { + map.serialize_entry("missing", &target.missing)?; + } + map.end() + } +} + +impl ExtensionParseResult { + pub(super) fn bind_displays(&mut self) -> Result<(), Error> { + let Some(state) = self.parsed.document_storage().generated_displays.0.as_ref() else { + return Ok(()); + }; + if !state.active { + self.parsed.with_document_mut(|_, document| { + document.generated_displays = DisplayState::default(); + }); + return Ok(()); + } + let paths: HashMap<_, _> = state + .captured + .iter() + .map(|selection| { + let target = TargetId { + document: self.session.identity().clone(), + slot: selection.target, + }; + ( + selection.target, + self.target_index() + .entry(&target) + .map(|entry| entry.path.clone()), + ) + }) + .collect(); + let reserved: HashSet<_> = self + .warnings() + .iter() + .filter_map(|warning| { + if let crate::WarningKind::UnresolvedReference { target } = &warning.kind { + Some(target.clone()) + } else { + None + } + }) + .collect(); + let remapping = self.parsed.with_document_mut(|owner, document| { + let resolved = resolve_targets(&owner.arena, document, paths, &reserved); + let mut remapping = Vec::new(); + let mut active = false; + walk_document_inline_nodes_mut(document, &mut |node| { + if let InlineNode::Macro(InlineMacro::CrossReference(xref)) = node + && let Some(display) = &mut xref.generated_display + && let Some(target) = resolved.get(&display.selection.target) + { + active = true; + xref.target = target.id; + display.resolved = Some(target.clone()); + if target.missing { + remapping.push(( + target.id.to_string(), + display.selection.id.to_string(), + display.origin.clone(), + )); + } + } + }); + if active { + if let Some(state) = &mut document.generated_displays.0 { + state.captured.clear(); + } + } else { + document.generated_displays = DisplayState::default(); + } + remapping + }); + self.repair_after_edit()?; + for warning in self.parsed.extension_warnings_mut() { + if let crate::WarningKind::UnresolvedReference { target } = &mut warning.kind + && let Some((_, original, origin)) = + remapping.iter().find(|(internal, _, origin)| { + internal == target + && warning + .location + .as_ref() + .is_some_and(|location| location.location == origin.location) + }) + { + target.clone_from(original); + warning.location = Some(origin.clone()); + } + } + Ok(()) + } +} + +fn resolve_targets<'a>( + arena: &'a Bump, + document: &Document<'a>, + paths: HashMap>, + reserved: &HashSet, +) -> HashMap> { + let mut resolved = HashMap::new(); + for (slot, path) in paths { + let found = path.and_then(|path| { + let block = path.get(&document.blocks)?; + Some(ResolvedTarget { + id: super::query::output_id(block)?, + caption: block + .metadata() + .and_then(|metadata| metadata.caption.clone()), + missing: false, + }) + }); + let target = found.unwrap_or_else(|| { + let mut id = format!("_acdc_missing_{}", slot + 1); + while document.references.contains_key(id.as_str()) + || reserved.contains(&id) + || resolved + .values() + .any(|value: &ResolvedTarget<'_>| value.id == id) + { + id.push('_'); + } + ResolvedTarget { + id: arena.alloc_str(&id), + caption: None, + missing: true, + } + }); + resolved.insert(slot, target); + } + resolved +} + +fn failure(origin: &SourceLocation, message: &str) -> Error { + Error::Extension(Box::new(origin.clone()), message.into()) +} diff --git a/acdc-parser/src/extensions/display/prepared.rs b/acdc-parser/src/extensions/display/prepared.rs new file mode 100644 index 000000000..643406dea --- /dev/null +++ b/acdc-parser/src/extensions/display/prepared.rs @@ -0,0 +1,197 @@ +use std::fmt; + +use bumpalo::Bump; + +use crate::{ + Caption, Document, Error, InlineMacro, InlineNode, ast::DocumentRef, + grammar::try_walk_document_inline_nodes_mut, +}; + +use super::{DisplayState, GeneratedDisplay, GeneratedDisplayRef, failure, plain}; + +/// A converter's label decision, lowered by parser-owned constructors. +#[derive(Clone, Debug)] +pub enum DisplayLabel { + /// Use the captured title's ordinary inline nodes. + Title, + /// Copy the caption's inline content, optionally trimming final whitespace. + Caption { trim_end: bool }, + /// Literal text with ordinary output escaping. + Text(String), +} + +struct Preparation<'doc> { + source: DocumentRef<'doc>, + arena: Bump, +} + +self_cell::self_cell! { + struct PreparedCell<'doc> { + owner: Preparation<'doc>, + #[covariant] + dependent: Document, + } +} + +/// One conversion's ordinary document. The source document is never mutated. +pub struct PreparedDocument<'doc> { + source: DocumentRef<'doc>, + prepared: Option>, +} + +impl fmt::Debug for PreparedDocument<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PreparedDocument") + .field("resolved", &self.prepared.is_some()) + .finish_non_exhaustive() + } +} + +impl<'doc> PreparedDocument<'doc> { + /// Borrow ordinary nodes for conversion or checked serialization. + #[must_use] + pub fn document(&self) -> DocumentRef<'_> { + self.prepared.as_ref().map_or(self.source, |cell| { + DocumentRef::from(cell.borrow_dependent()) + }) + } + + /// Prepare symbolic references without rerunning selection or processors. + /// No allocation or tree copy occurs when there are no display requests. + /// + /// # Errors + /// Rejects unfinalized requests or content that cannot be repaired. + pub fn new( + source: DocumentRef<'doc>, + mut resolve: impl FnMut(GeneratedDisplayRef<'_>) -> DisplayLabel, + ) -> Result { + if !source.has_deferred_displays() { + return Ok(Self { + source, + prepared: None, + }); + } + let prepared = PreparedCell::try_new( + Preparation { + source, + arena: Bump::new(), + }, + |owner| { + let mut document = Document::from(owner.source); + try_walk_document_inline_nodes_mut(&mut document, &mut |node| { + if let InlineNode::Macro(InlineMacro::CrossReference(xref)) = node + && let Some(display) = xref.generated_display.take() + { + let target = display.resolved.as_ref().ok_or_else(|| { + failure(&display.origin, "display target has not been finalized") + })?; + let label = if target.missing { + DisplayLabel::Text(format!("[{}]", display.selection.id)) + } else { + resolve(GeneratedDisplayRef(&display)) + }; + xref.text = build_label(&owner.arena, &display, label); + // A present-empty label must not fall back to generic reftext. + if xref.text.is_empty() { + xref.text.push(plain("", &display.origin)); + } + } + Ok::<_, Error>(()) + })?; + document.generated_displays = DisplayState::default(); + repair(&mut document)?; + Ok::<_, Error>(document) + }, + )?; + Ok(Self { + source, + prepared: Some(prepared), + }) + } +} + +fn build_label<'a>( + arena: &'a Bump, + display: &GeneratedDisplay<'a>, + label: DisplayLabel, +) -> Vec> { + match label { + DisplayLabel::Title => { + if display.selection.title.is_present() { + display.selection.title.as_inlines().to_vec() + } else { + vec![plain( + arena.alloc_str(&format!("[{}]", GeneratedDisplayRef(display).target())), + &display.origin, + )] + } + } + DisplayLabel::Text(text) => vec![plain(arena.alloc_str(&text), &display.origin)], + DisplayLabel::Caption { trim_end } => { + let mut nodes = display + .resolved + .as_ref() + .and_then(|target| target.caption.as_ref()) + .and_then(|caption| { + if let Caption::CustomContent(content) = caption { + Some(content.as_inlines().to_vec()) + } else { + None + } + }) + .unwrap_or_default(); + if trim_end { + trim_caption(&mut nodes); + } + nodes + } + } +} + +fn trim_caption(nodes: &mut Vec>) { + while let Some(node) = nodes.last_mut() { + let text = if let InlineNode::PlainText(text) = node { + let trimmed = text.content.trim_end(); + text.replace_text(trimmed); + trimmed + } else if let InlineNode::RawText(text) = node { + let trimmed = text.content.trim_end(); + text.replace_text(trimmed); + trimmed + } else { + break; + }; + if !text.is_empty() { + break; + } + nodes.pop(); + } +} + +fn repair(document: &mut Document<'_>) -> Result<(), Error> { + let sections: std::collections::HashMap<_, _> = document + .references + .iter() + .map(|(id, reference)| { + ( + *id, + (reference.occurrence.clone(), reference.section.clone()), + ) + }) + .collect(); + let origin = crate::SourceLocation::at_location(None, document.location.clone()); + document + .rebuild_footnotes() + .map_err(|error| failure(&origin, &error.to_string()))?; + document + .rebuild_extension_references() + .map_err(|error| failure(&origin, &error.to_string()))?; + for (id, reference) in &mut document.references { + if let Some((occurrence, section)) = sections.get(id) + && reference.occurrence == *occurrence + { + reference.section.clone_from(section); + } + } + Ok(()) +} diff --git a/acdc-parser/src/extensions/editor.rs b/acdc-parser/src/extensions/editor.rs index a3e1ef1f0..10d505bb4 100644 --- a/acdc-parser/src/extensions/editor.rs +++ b/acdc-parser/src/extensions/editor.rs @@ -10,7 +10,7 @@ use transaction::Edit; /// next observation. Validation and repair failures preserve the tree, handles, /// assigned numbers, and diagnostics. Surviving targets retain their identity. pub struct DocumentEditor<'doc> { - result: &'doc mut ExtensionParseResult, + pub(super) result: &'doc mut ExtensionParseResult, } impl<'doc> DocumentEditor<'doc> { @@ -139,7 +139,7 @@ impl<'doc> DocumentEditor<'doc> { Err(self.error(target, "target is not a pending placeholder")) } } - fn path(&self, target: &TargetId) -> Result { + pub(super) fn path(&self, target: &TargetId) -> Result { self.result .target_index() .entry(target) @@ -151,7 +151,7 @@ impl<'doc> DocumentEditor<'doc> { ) }) } - fn location(&self, target: &TargetId) -> SourceLocation { + pub(super) fn location(&self, target: &TargetId) -> SourceLocation { self.query().get(target).map_or_else( || { self.result diff --git a/acdc-parser/src/extensions/editor/transaction.rs b/acdc-parser/src/extensions/editor/transaction.rs index 4c2a8fb25..8b2163dfd 100644 --- a/acdc-parser/src/extensions/editor/transaction.rs +++ b/acdc-parser/src/extensions/editor/transaction.rs @@ -21,6 +21,7 @@ impl DocumentEditor<'_> { let path = self.path(target)?; let origin = self.location(target); let mode = self.result.mode; + let identity = self.result.session.identity().clone(); let index = self .result .targets @@ -28,7 +29,7 @@ impl DocumentEditor<'_> { .ok_or_else(|| failure(&origin, "query index is absent"))?; let (new_target, reference_warnings, construction_warnings) = self.result.parsed.with_document_mut(|owner, document| { - let prepared = prepare(owner, document, &path, edit, mode, &origin)?; + let prepared = prepare(owner, document, &path, edit, mode, &origin, &identity)?; let mut candidate = snapshot(document); let mut candidate_index = index.clone(); candidate_index.prepare_edit(&mut candidate); @@ -68,6 +69,7 @@ impl DocumentEditor<'_> { fn snapshot<'a>(document: &Document<'a>) -> Document<'a> { Document { + generated_displays: document.generated_displays.clone(), header: document.header.clone(), untitled_header_location: document.untitled_header_location.clone(), attributes: document.attributes.clone(), @@ -84,6 +86,7 @@ struct Prepared<'a> { kind: Option, warnings: Vec, recaption: bool, + displays: bool, } fn prepare<'a>( @@ -93,6 +96,7 @@ fn prepare<'a>( edit: &Edit, mode: crate::CompatibilityMode, origin: &SourceLocation, + identity: &super::super::target::DocumentIdentity, ) -> Result>, Error> { let (builder, replacing) = match edit { Edit::Insert(builder) => (builder, false), @@ -168,6 +172,7 @@ fn prepare<'a>( origin.location.clone(), attributes.metadata, attributes.title, + |inline| inline.build(&owner.arena, document, identity, origin), ) .map_err(|error| failure(origin, &error.to_string()))?; if let Block::Image(image) = &mut block { @@ -191,6 +196,7 @@ fn prepare<'a>( kind, warnings: attributes.warnings, recaption: true, + displays: builder.has_displays(), })) } @@ -228,7 +234,8 @@ fn prepare_source<'a>( | super::super::builder::Content::Literal(source) | super::super::builder::Content::Listing(source) => owner.arena.alloc_str(source), super::super::builder::Content::Image(_) - | super::super::builder::Content::UnorderedList(_) => { + | super::super::builder::Content::UnorderedList(_) + | super::super::builder::Content::ParagraphInlines(_) => { return Err(failure(origin, "source body is unsupported")); } }; @@ -244,6 +251,7 @@ fn prepare_source<'a>( kind: None, warnings, recaption: false, + displays: false, }) } @@ -258,6 +266,9 @@ fn transact<'a>( mut prepared: Option>, origin: &SourceLocation, ) -> Result { + if prepared.as_ref().is_some_and(|prepared| prepared.displays) { + document.generated_displays.activate(); + } if let Some(prepared) = &mut prepared && prepared.recaption { diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 5111a4617..526a809c2 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -84,6 +84,14 @@ //! that input with the target's location and source-position attributes. //! Ordinary parser entry points do not retain these extension snapshots. //! +//! [`DocumentEditor::capture`] freezes a title and its source context. Use +//! [`CapturedTarget::display`] with [`BlockBuilder::paragraph_inlines`] or +//! [`BlockBuilder::unordered_list`] for explicit caption/title links. +//! Finalization follows surviving handles and their latest caption data, without +//! refreshing captured titles. Converter core prepares a fresh ordinary document +//! through [`PreparedDocument`] before traversal; the shared parse stays unchanged. +//! Checked ASG export rejects symbolic displays until they have been prepared. +//! //! Tree processors run after block macros and can replace pending requests with //! ordinary content. Builder bodies are literal; attribute lists use the parser's //! metadata rules. Use [`DocumentEditor::replace_source`] explicitly to interpret @@ -149,6 +157,7 @@ mod block_macro; mod builder; mod deferred; +mod display; mod editor; pub(crate) mod finalization; mod query; @@ -168,6 +177,11 @@ pub use block_macro::{ pub use builder::BlockBuilder; pub(crate) use builder::SourceContext; pub use deferred::{DeferredBlock, ExtensionBlock, PlaceholderId}; +pub use display::{ + CapturedTarget, DisplayIntent, DisplayLabel, GeneratedDisplayRef, InlineBuilder, + PreparedDocument, +}; +pub(crate) use display::{DisplayState, GeneratedDisplay}; pub use editor::DocumentEditor; pub use query::{BlockContext, BlockView, DocumentQuery}; pub use registry::{RegistrationError, Registry, RegistryBuilder}; diff --git a/acdc-parser/src/extensions/query.rs b/acdc-parser/src/extensions/query.rs index dcd551946..f7ebd0e6e 100644 --- a/acdc-parser/src/extensions/query.rs +++ b/acdc-parser/src/extensions/query.rs @@ -477,7 +477,7 @@ impl<'doc> BlockView<'doc> { } } -pub(super) fn output_id<'doc>(block: &'doc Block<'_>) -> Option<&'doc str> { +pub(super) fn output_id<'a>(block: &Block<'a>) -> Option<&'a str> { let id = if let Block::Section(section) = block { crate::Section::explicit_id(§ion.metadata).or(section.id) } else { diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index 58d217cc4..be156bf1e 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -58,13 +58,14 @@ impl ExtensionParseResult { /// /// # Errors /// Returns a located error if a deferred request remains unresolved. - pub fn finish(self) -> Result { + pub fn finish(mut self) -> Result { if let Some(request) = self.session.deferred.first() { return Err(Error::Extension( Box::new(request.invocation.location.clone()), "unresolved deferred block".into(), )); } + self.bind_displays()?; Ok(self.parsed) } diff --git a/acdc-parser/src/extensions/tests/display.rs b/acdc-parser/src/extensions/tests/display.rs new file mode 100644 index 000000000..8d9907ba4 --- /dev/null +++ b/acdc-parser/src/extensions/tests/display.rs @@ -0,0 +1,372 @@ +use super::{TestResult, support}; +use acdc_parser::{ + CompatibilityMode, Options, WarningKind, + ast::{BlockKind, InlineKind}, + extensions::{ + BlockBuilder, BlockContext, DisplayIntent, DisplayLabel, DocumentEditor, InlineBuilder, + PreparedDocument, TitleSource, + }, +}; + +fn modes() -> [CompatibilityMode; 2] { + [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] +} + +#[test] +fn extensions_unordered_list_combines_literal_and_grouped_display_items() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + ".A *title*\n[#image]\nimage::one.svg[]\n\nOutput.", + &options, + )?; + let image = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")? + .target() + .clone(); + let output = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("output")? + .target() + .clone(); + let owned = String::from("*literal* <&> {counter:x}"); + let mut editor = DocumentEditor::new(&mut result); + let captured = editor.capture(&image)?; + editor.replace_block( + &output, + BlockBuilder::unordered_list([ + InlineBuilder::from(owned.clone()), + InlineBuilder::from(&owned), + InlineBuilder::from(owned.as_str()), + InlineBuilder::from([ + InlineBuilder::text("Before "), + InlineBuilder::from(vec![captured.display(DisplayIntent::Title)]), + InlineBuilder::text(" after"), + ]), + InlineBuilder::from(Vec::new()), + ]), + )?; + let parsed = result.finish()?; + let prepared = PreparedDocument::new(parsed.document(), |_| DisplayLabel::Title)?; + let BlockKind::UnorderedList(list) = + prepared.document().blocks().last().ok_or("list")?.kind() + else { + return Err("list kind".into()); + }; + let mut items = list.items(); + for _ in 0..3 { + let content = items.next().ok_or("literal item")?.principal(); + assert_eq!(content.inlines().len(), 1); + assert!( + matches!(content.inlines().next().ok_or("literal")?.kind(), InlineKind::Plain(text) if text.text() == owned) + ); + } + let mut content = items.next().ok_or("structured item")?.principal().inlines(); + assert!( + matches!(content.next().ok_or("prefix")?.kind(), InlineKind::Plain(text) if text.text() == "Before ") + ); + let InlineKind::CrossReference(xref) = content.next().ok_or("xref")?.kind() else { + return Err("xref kind".into()); + }; + assert_eq!(xref.target(), "image"); + assert!( + xref.text() + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + ); + assert!( + matches!(content.next().ok_or("suffix")?.kind(), InlineKind::Plain(text) if text.text() == " after") + ); + assert!(content.next().is_none()); + assert!(items.next().ok_or("empty item")?.principal().is_empty()); + assert!(items.next().is_none()); + } + Ok(()) +} + +#[test] +fn extensions_display_freezes_titles_and_defers_renamed_target_captions() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "= Document\n:label: Early\n\n.Original *{label}* <&>\n[#figure,reftext='Custom reference']\nimage::original.svg[]\n\n:label: Late\n\n[#output]\nOutput.", &options, + )?; + let target = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")? + .target() + .clone(); + let output = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("paragraph")? + .target() + .clone(); + let mut editor = DocumentEditor::new(&mut result); + let selected = editor.capture(&target)?; + let second = editor.capture(&target)?; + editor.replace_block( + &output, + BlockBuilder::unordered_list([ + vec![selected.display(DisplayIntent::Title)], + vec![selected.display(DisplayIntent::CaptionAndTitle)], + vec![second.display(DisplayIntent::Caption)], + ]), + )?; + editor.replace_block( + &target, + BlockBuilder::listing("changed") + .with_attributes("id=renamed,title='Changed *later*',caption='*Updated* '"), + )?; + let parsed = result.finish()?; + assert!(parsed.warnings().is_empty(), "{:?}", parsed.warnings()); + let before = serde_json::to_value(parsed.document())?; + let mut observed = 0; + for _ in 0..2 { + let prepared = PreparedDocument::new(parsed.document(), |request| { + observed += 1; + assert_eq!(request.target(), "renamed"); + assert!(!request.is_missing()); + assert_eq!( + request.title_source().map(TitleSource::raw_source), + Some("Original *{label}* <&>") + ); + assert_eq!( + request + .title_source() + .and_then(|source| source.attributes().get("label")) + .and_then(|value| value.text()), + Some("Early") + ); + if request.intent() == DisplayIntent::Title { + DisplayLabel::Title + } else { + DisplayLabel::Caption { trim_end: true } + } + })?; + assert!(!prepared.document().has_deferred_displays()); + let block = prepared.document().blocks().last().ok_or("list")?; + let BlockKind::UnorderedList(list) = block.kind() else { + return Err("list kind".into()); + }; + for item in list.items() { + let mut nodes = item.principal().inlines(); + let InlineKind::CrossReference(xref) = nodes.next().ok_or("xref")?.kind() else { + return Err("xref kind".into()); + }; + assert_eq!(xref.target(), "renamed"); + assert!(xref.generated_display().is_none()); + assert!( + xref.text() + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))), + "{:?}", + xref.text() + ); + } + assert_eq!(serde_json::to_value(parsed.document())?, before); + } + assert_eq!(observed, 6); + } + Ok(()) +} + +#[test] +fn extensions_display_removed_identity_never_rebinds_to_reused_id() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + "= Document\n\n[#gone]\n== Removed\n\n[#figure]\n.Original\nimage::old.svg[]\n\n[#keep]\n== Kept\n\n[#output]\nOutput.", &options, + )?; + let image = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")? + .target() + .clone(); + let section = result + .query() + .select(BlockContext::Section) + .next() + .ok_or("section")? + .target() + .clone(); + let output = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("output")? + .target() + .clone(); + let origin = result + .query() + .get(&output) + .ok_or("output view")? + .source_location(); + let mut editor = DocumentEditor::new(&mut result); + let captured = editor.capture(&image)?; + editor.replace_block( + &output, + BlockBuilder::paragraph_inlines([captured.display(DisplayIntent::Title)]), + )?; + editor.remove_section(§ion)?; + editor.insert_before( + &output, + BlockBuilder::paragraph("Replacement").with_attributes("id=figure"), + )?; + let parsed = result.finish()?; + assert!(parsed.document().references().get("figure").is_some()); + let warning = parsed.warnings().iter().find(|warning| matches!(&warning.kind, WarningKind::UnresolvedReference { target } if target == "figure")).ok_or("missing generated warning")?; + assert_eq!(warning.location.as_ref(), Some(&origin)); + let prepared = PreparedDocument::new(parsed.document(), |_| { + panic!("missing request must use fallback") + })?; + let section = prepared.document().blocks().next().ok_or("kept")?; + let BlockKind::Section(section) = section.kind() else { + return Err("section kind".into()); + }; + let block = section.blocks().last().ok_or("output")?; + let BlockKind::Paragraph(paragraph) = block.kind() else { + return Err("paragraph kind".into()); + }; + let InlineKind::CrossReference(xref) = + paragraph.content().inlines().next().ok_or("xref")?.kind() + else { + return Err("xref kind".into()); + }; + assert_ne!(xref.target(), "figure"); + assert!( + prepared + .document() + .references() + .get(xref.target()) + .is_none() + ); + let label = xref.text().inlines().next().ok_or("label")?; + assert!(matches!(label.kind(), InlineKind::Plain(text) if text.text() == "[figure]")); + } + Ok(()) +} + +#[test] +fn extensions_foreign_display_is_rejected_atomically() -> TestResult { + let registry = support::registry(); + let mut first = registry.parse(".Title\nimage::one.svg[]", &Options::default())?; + let image = first + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")? + .target() + .clone(); + let captured = DocumentEditor::new(&mut first).capture(&image)?; + let mut second = registry.parse("Paragraph.", &Options::default())?; + let output = second + .query() + .blocks() + .next() + .ok_or("paragraph")? + .target() + .clone(); + let before = serde_json::to_value(second.parsed.document())?; + let error = DocumentEditor::new(&mut second).replace_block( + &output, + BlockBuilder::paragraph_inlines([captured.display(DisplayIntent::Title)]), + ); + assert!(error.is_err()); + assert_eq!(serde_json::to_value(second.parsed.document())?, before); + assert!(!second.finish()?.document().has_deferred_displays()); + Ok(()) +} + +#[test] +fn extensions_display_distinguishes_absent_and_present_empty_titles() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (prefix, expected) in [("", "[renamed]"), (":empty:\n\n.{empty}\n", "")] { + let mut result = support::registry().parse( + &format!("{prefix}[#target,reftext='Generic']\nParagraph."), + &options, + )?; + let target = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("paragraph")? + .target() + .clone(); + let mut editor = DocumentEditor::new(&mut result); + let captured = editor.capture(&target)?; + editor.insert_before( + &target, + BlockBuilder::paragraph_inlines([captured.display(DisplayIntent::Title)]), + )?; + editor.replace_block( + &target, + BlockBuilder::paragraph("Changed").with_attributes("id=renamed,title='Changed'"), + )?; + let parsed = result.finish()?; + let prepared = PreparedDocument::new(parsed.document(), |_| DisplayLabel::Title)?; + let BlockKind::Paragraph(paragraph) = + prepared.document().blocks().next().ok_or("output")?.kind() + else { + return Err("paragraph kind".into()); + }; + let InlineKind::CrossReference(xref) = + paragraph.content().inlines().next().ok_or("xref")?.kind() + else { + return Err("xref kind".into()); + }; + assert_eq!(xref.text().inlines().len(), 1); + assert!( + matches!(xref.text().inlines().next().ok_or("label")?.kind(), InlineKind::Plain(text) if text.text() == expected) + ); + } + } + Ok(()) +} + +#[cfg(feature = "asg")] +#[test] +fn extensions_symbolic_display_requires_lowering_before_checked_asg() -> TestResult { + fn require_send(_: impl Send) {} + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse("[#image]\nParagraph.", &options)?; + let target = result + .query() + .blocks() + .next() + .ok_or("image")? + .target() + .clone(); + let mut editor = DocumentEditor::new(&mut result); + let captured = editor.capture(&target)?; + editor.insert_before( + &target, + BlockBuilder::paragraph_inlines([captured.display(DisplayIntent::Title)]), + )?; + result.normalize()?; + let parsed = result.finish()?; + for profile in [crate::asg::Profile::Upstream, crate::asg::Profile::Acdc] { + let error = crate::asg::export_document_with_profile(parsed.document(), profile) + .expect_err("symbolic display"); + assert!( + matches!(error, crate::asg::Error::Unsupported { path, .. } if path.ends_with("/generated_display")) + ); + let prepared = PreparedDocument::new(parsed.document(), |_| DisplayLabel::Title)?; + crate::asg::export_document_with_profile(prepared.document(), profile)?; + } + require_send(parsed); + } + Ok(()) +} diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index 0eccb21db..df0ffc450 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -25,6 +25,7 @@ mod support; mod queries; mod construction; +mod display; mod title_sources; #[path = "tree_processors.rs"] diff --git a/acdc-parser/src/grammar/document/finish.rs b/acdc-parser/src/grammar/document/finish.rs index 5960ca1b3..b17053195 100644 --- a/acdc-parser/src/grammar/document/finish.rs +++ b/acdc-parser/src/grammar/document/finish.rs @@ -58,6 +58,7 @@ pub(super) fn finish<'a>( ); let mut document = Document { + generated_displays: crate::extensions::DisplayState::default(), header, untitled_header_location, location: document_location(state, start, end), diff --git a/acdc-parser/src/grammar/location_walk.rs b/acdc-parser/src/grammar/location_walk.rs index 47ab89c5d..b39384644 100644 --- a/acdc-parser/src/grammar/location_walk.rs +++ b/acdc-parser/src/grammar/location_walk.rs @@ -176,7 +176,7 @@ pub(super) fn try_walk_owned_inline_nodes_mut<'a, E>( walker.inline(node) } -pub(super) fn try_walk_document_inline_nodes_mut<'a, E>( +pub(crate) fn try_walk_document_inline_nodes_mut<'a, E>( document: &mut Document<'a>, visit: &mut impl FnMut(&mut InlineNode<'a>) -> Result<(), E>, ) -> Result<(), E> { diff --git a/acdc-parser/src/grammar/mod.rs b/acdc-parser/src/grammar/mod.rs index 5dab02072..5b566c928 100644 --- a/acdc-parser/src/grammar/mod.rs +++ b/acdc-parser/src/grammar/mod.rs @@ -17,6 +17,7 @@ pub(crate) mod inlines; mod line_map; mod location_mapping; mod location_walk; +pub(crate) use location_walk::try_walk_document_inline_nodes_mut; mod marked_text; mod passthrough_processing; pub(crate) mod reference_text; diff --git a/acdc-parser/src/model/inlines/macros.rs b/acdc-parser/src/model/inlines/macros.rs index fc74bb874..133b6040e 100644 --- a/acdc-parser/src/model/inlines/macros.rs +++ b/acdc-parser/src/model/inlines/macros.rs @@ -396,6 +396,7 @@ type Key<'a> = ContentAttribute<'a>; #[derive(Clone)] #[non_exhaustive] pub struct CrossReference<'a> { + pub(crate) generated_display: Option>>, /// The effective link target. A resolved natural reference contains the /// matching ID; references to fully included sources contain the fragment ID. /// An empty local target addresses the document top. Unresolved references @@ -439,6 +440,7 @@ impl<'a> CrossReference<'a> { document_reftext: None, resolve_natural_target: false, source_syntax: XrefSourceSyntax::Literal, + generated_display: None, } } @@ -665,6 +667,7 @@ impl fmt::Debug for CrossReference<'_> { impl PartialEq for CrossReference<'_> { fn eq(&self, other: &Self) -> bool { self.target == other.target + && self.generated_display == other.generated_display && self.target_is_local == other.target_is_local && self.text == other.text && self.location == other.location diff --git a/acdc-parser/src/model/inlines/mod.rs b/acdc-parser/src/model/inlines/mod.rs index 6ca522f29..82cc10c40 100644 --- a/acdc-parser/src/model/inlines/mod.rs +++ b/acdc-parser/src/model/inlines/mod.rs @@ -528,6 +528,12 @@ where } map.serialize_entry("target", &x.target)?; map.serialize_entry("target_is_local", &x.target_is_local)?; + if let Some(display) = &x.generated_display { + map.serialize_entry( + "generated_display", + &crate::extensions::GeneratedDisplayRef::new(display), + )?; + } if let Some(style) = x.xrefstyle.attribute_value() { map.serialize_entry("xrefstyle", style)?; } diff --git a/acdc-parser/src/model/mod.rs b/acdc-parser/src/model/mod.rs index 4f528de6a..08657f824 100644 --- a/acdc-parser/src/model/mod.rs +++ b/acdc-parser/src/model/mod.rs @@ -79,6 +79,7 @@ pub use token_assignment::TokenAssignment; #[derive(Default, Debug, PartialEq)] #[non_exhaustive] pub struct Document<'a> { + pub(crate) generated_displays: crate::extensions::DisplayState<'a>, pub(crate) header: Option>, /// Span of the leading attribute entries and comments of a document /// without a title. A titled header records its span in [`Header`]. diff --git a/acdc-parser/src/parsed.rs b/acdc-parser/src/parsed.rs index d5736b117..7cfa55174 100644 --- a/acdc-parser/src/parsed.rs +++ b/acdc-parser/src/parsed.rs @@ -338,6 +338,10 @@ impl ParseResult { self.warnings = combined.into_vec(); } + pub(crate) fn extension_warnings_mut(&mut self) -> &mut [Warning] { + &mut self.warnings + } + pub(crate) fn append_extension_warnings(&mut self, warnings: Vec) { let mut combined = WarningCollection::default(); for warning in std::mem::take(&mut self.warnings) diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index 752833774..e6e84ed4f 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Added `display::prepare()` for custom converters to resolve extension-generated + caption and captured-title labels into ordinary explicit cross-references for + each conversion, preserving the shared document and overriding generic `reftext`. + - **Breaking:** removed `TraversalContext::substitute_attributes()`. To expand references at a traversal position, call `DocumentAttributesRef::substitute_attributes()` from `acdc-parser` on the diff --git a/converters/core/src/display.rs b/converters/core/src/display.rs new file mode 100644 index 000000000..db09f79a8 --- /dev/null +++ b/converters/core/src/display.rs @@ -0,0 +1,43 @@ +//! Resolve symbolic labels into ordinary parser nodes for one conversion. + +use acdc_parser::{ + Error, + ast::{CaptionRef, DocumentRef}, + extensions::{DisplayIntent, DisplayLabel, GeneratedDisplayRef, PreparedDocument}, +}; + +/// Create a fresh display context without changing the shared parsed document. +/// The direct path borrows the original document when no requests are active. +/// Keep the returned context alive while traversing its `document()`. +/// Captions omit trailing whitespace and retain their final period; a requested +/// caption that has no prefix uses `[id]`. Select title intent for uncaptioned +/// targets. Present-empty captions remain explicit empty labels, overriding reftext. +/// +/// # Errors +/// Returns a parser error for an unfinalized request or invalid retained content. +pub fn prepare(document: DocumentRef<'_>) -> Result, Error> { + PreparedDocument::new(document, resolve) +} + +fn resolve(request: GeneratedDisplayRef<'_>) -> DisplayLabel { + if request.intent() == DisplayIntent::Title { + return DisplayLabel::Title; + } + match request.caption() { + Some(CaptionRef::Numbered { + label, + number: Some(number), + .. + }) => DisplayLabel::Text(if label.is_empty() { + format!("{number}.") + } else { + format!("{label} {number}.") + }), + Some(CaptionRef::Custom(text)) => DisplayLabel::Text(text.trim_end().to_string()), + Some(CaptionRef::CustomContent(_)) => DisplayLabel::Caption { trim_end: true }, + Some(CaptionRef::Unnumbered | CaptionRef::Numbered { number: None, .. }) | None => { + DisplayLabel::Text(format!("[{}]", request.target())) + } + Some(_) => DisplayLabel::Text(format!("[{}]", request.target())), + } +} diff --git a/converters/core/src/lib.rs b/converters/core/src/lib.rs index 8f218f43e..98eb88c44 100644 --- a/converters/core/src/lib.rs +++ b/converters/core/src/lib.rs @@ -46,6 +46,7 @@ use acdc_parser::{ mod backend; /// Source code syntax highlighting and callouts support. pub mod code; +pub mod display; mod doctype; mod document_attributes; pub mod icon; From 2bc2babfa4955cf956034af0d42147a3a44ba231 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 15 Nov 2026 17:27:47 +0100 Subject: [PATCH 18/55] feat(converters): render captured titles and finalized captions Prepare generated display labels for each conversion across HTML, Markdown, terminal, manpage, and PDF output. Preserve frozen title formatting, resolve caption edits and renamed targets, and collect captured PDF title assets before rendering. Exercise the public extension API with shared fixtures and repeated-conversion regressions. --- acdc-parser/README.adoc | 37 +++++ acdc-parser/README.md | 37 +++++ converters/dev/CHANGELOG.md | 4 + converters/dev/src/fixtures.rs | 29 +++- converters/dev/src/fixtures/display.rs | 99 ++++++++++++++ converters/html/CHANGELOG.md | 4 + converters/html/src/lib.rs | 3 +- converters/html/tests/extension_displays.rs | 39 ++++++ .../embedded/extension_display_removal.html | 26 ++++ .../html/embedded/extension_displays.html | 108 +++++++++++++++ .../embedded/extension_display_removal.html | 17 +++ .../html5s/embedded/extension_displays.html | 77 +++++++++++ .../embedded/extension_display_removal.adoc | 18 +++ .../html/embedded/extension_displays.adoc | 58 ++++++++ .../embedded/extension_display_removal.adoc | 1 + .../html5s/embedded/extension_displays.adoc | 1 + converters/manpage/CHANGELOG.md | 4 + converters/manpage/src/lib.rs | 5 +- .../expected/extension_display_removal.man | 39 ++++++ .../fixtures/expected/extension_displays.man | 101 ++++++++++++++ .../source/extension_display_removal.adoc | 1 + .../fixtures/source/extension_displays.adoc | 1 + converters/markdown/CHANGELOG.md | 4 + converters/markdown/src/lib.rs | 2 + .../expected/commonmark_extension_displays.md | 66 +++++++++ .../expected/extension_display_removal.md | 15 +++ .../fixtures/expected/extension_displays.md | 66 +++++++++ .../source/commonmark_extension_displays.adoc | 1 + .../source/extension_display_removal.adoc | 1 + .../fixtures/source/extension_displays.adoc | 1 + converters/pdf/CHANGELOG.md | 4 + converters/pdf/src/lib.rs | 4 + converters/pdf/tests/extension_displays.rs | 88 ++++++++++++ .../expected/extension_display_removal.typ | 90 +++++++++++++ .../fixtures/expected/extension_displays.typ | 126 ++++++++++++++++++ .../source/extension_display_removal.adoc | 1 + .../fixtures/source/extension_displays.adoc | 1 + converters/pdf/tests/support/mod.rs | 5 +- converters/terminal/CHANGELOG.md | 4 + converters/terminal/src/lib.rs | 3 +- converters/terminal/tests/fixtures/catalog.rs | 2 + .../extension_display_removal.osc8.txt | 15 +++ .../expected/extension_display_removal.txt | 15 +++ .../expected/extension_displays.osc8.txt | 56 ++++++++ .../fixtures/expected/extension_displays.txt | 56 ++++++++ .../source/extension_display_removal.adoc | 1 + .../fixtures/source/extension_displays.adoc | 1 + 47 files changed, 1329 insertions(+), 8 deletions(-) create mode 100644 converters/dev/src/fixtures/display.rs create mode 100644 converters/html/tests/extension_displays.rs create mode 100644 converters/html/tests/fixtures/expected/html/embedded/extension_display_removal.html create mode 100644 converters/html/tests/fixtures/expected/html/embedded/extension_displays.html create mode 100644 converters/html/tests/fixtures/expected/html5s/embedded/extension_display_removal.html create mode 100644 converters/html/tests/fixtures/expected/html5s/embedded/extension_displays.html create mode 100644 converters/html/tests/fixtures/source/html/embedded/extension_display_removal.adoc create mode 100644 converters/html/tests/fixtures/source/html/embedded/extension_displays.adoc create mode 120000 converters/html/tests/fixtures/source/html5s/embedded/extension_display_removal.adoc create mode 120000 converters/html/tests/fixtures/source/html5s/embedded/extension_displays.adoc create mode 100644 converters/manpage/tests/fixtures/expected/extension_display_removal.man create mode 100644 converters/manpage/tests/fixtures/expected/extension_displays.man create mode 120000 converters/manpage/tests/fixtures/source/extension_display_removal.adoc create mode 120000 converters/manpage/tests/fixtures/source/extension_displays.adoc create mode 100644 converters/markdown/tests/fixtures/expected/commonmark_extension_displays.md create mode 100644 converters/markdown/tests/fixtures/expected/extension_display_removal.md create mode 100644 converters/markdown/tests/fixtures/expected/extension_displays.md create mode 120000 converters/markdown/tests/fixtures/source/commonmark_extension_displays.adoc create mode 120000 converters/markdown/tests/fixtures/source/extension_display_removal.adoc create mode 120000 converters/markdown/tests/fixtures/source/extension_displays.adoc create mode 100644 converters/pdf/tests/extension_displays.rs create mode 100644 converters/pdf/tests/fixtures/expected/extension_display_removal.typ create mode 100644 converters/pdf/tests/fixtures/expected/extension_displays.typ create mode 120000 converters/pdf/tests/fixtures/source/extension_display_removal.adoc create mode 120000 converters/pdf/tests/fixtures/source/extension_displays.adoc create mode 100644 converters/terminal/tests/fixtures/expected/extension_display_removal.osc8.txt create mode 100644 converters/terminal/tests/fixtures/expected/extension_display_removal.txt create mode 100644 converters/terminal/tests/fixtures/expected/extension_displays.osc8.txt create mode 100644 converters/terminal/tests/fixtures/expected/extension_displays.txt create mode 120000 converters/terminal/tests/fixtures/source/extension_display_removal.adoc create mode 120000 converters/terminal/tests/fixtures/source/extension_displays.adoc diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 33c9c4027..46ef29312 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2107,6 +2107,43 @@ its captured attributes and `subs=` settings. Raw source, parsed inline content, and rendered output are separate views; extensions need no arena allocation or whole-document reparse. +Use `DocumentEditor::capture()` to freeze a target's title, including its raw +source, substitution order, formatting, and source-position attributes. A +`CapturedTarget` belongs to one working document and remains a snapshot across +later edits. Its `display()` method accepts `DisplayIntent::Caption`, `Title`, or +`CaptionAndTitle`; pass these requests and `InlineBuilder::text()` values to +`BlockBuilder::paragraph_inlines()` or `unordered_list()`. The list constructor +still accepts string items; arrays or vectors of `InlineBuilder` values combine +fragments into one item. Use `InlineBuilder::from()` to mix literal and structured +items in the same list. `CaptionAndTitle` places the captured title outside the +caption link. Explicit display labels take precedence over `reftext`, including +an explicitly empty caption. +Choose `Title` when a target has no caption; an explicit caption request without +a prefix uses `[id]` rather than the target's generic reference label. + +`finish()` binds requests to surviving handles and their final caption data, +following renamed output IDs without repeating selection or callbacks. A removed +handle adds a located unresolved-reference warning and retains a missing target, +even if another block reuses its old ID. Captions keep their final period and +omit trailing whitespace in generated links. Captured title inline nodes retain +their normal formatting and output-stage substitutions; caption resolution does +not render titles or retain backend strings. + +Converter core's `display::prepare()` creates a fresh conversion context whose +`document()` contains ordinary cross-references with explicit inline labels. +The standard converters call it automatically. Custom converters should keep the +returned context alive for traversal. Repeated conversions leave the shared +`ParseResult` unchanged. Documents without display requests use the borrowed path. +Native JSON identifies symbolic labels with `generated_display`; checked ASG +export rejects them in both profiles until prepared through a conversion context. + +Direct comparisons with Asciidoctor 2.0.26 and `asciidoctor-lists` confirm explicit +labels overriding `reftext` and caption punctuation. acdc intentionally freezes +title attributes at selection and defers captions: the reference extension can +reevaluate raw titles with later attributes, escape reused rendered titles, and +retain captions captured before a later edit. These timing behaviors are not +compatibility claims. User-defined late inline processors remain a later stage. + Successful edits repair references, TOC, scoped footnotes, and unresolved/duplicate ID warnings before returning. Other parse and construction warnings retain their order; repair refreshes only reference-related warnings. Validation or repair diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 7290f89e8..2916d8b29 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1751,6 +1751,43 @@ its captured attributes and `subs=` settings. Raw source, parsed inline content, and rendered output are separate views; extensions need no arena allocation or whole-document reparse. +Use `DocumentEditor::capture()` to freeze a target's title, including its raw +source, substitution order, formatting, and source-position attributes. A +`CapturedTarget` belongs to one working document and remains a snapshot across +later edits. Its `display()` method accepts `DisplayIntent::Caption`, `Title`, or +`CaptionAndTitle`; pass these requests and `InlineBuilder::text()` values to +`BlockBuilder::paragraph_inlines()` or `unordered_list()`. The list constructor +still accepts string items; arrays or vectors of `InlineBuilder` values combine +fragments into one item. Use `InlineBuilder::from()` to mix literal and structured +items in the same list. `CaptionAndTitle` places the captured title outside the +caption link. Explicit display labels take precedence over `reftext`, including +an explicitly empty caption. +Choose `Title` when a target has no caption; an explicit caption request without +a prefix uses `[id]` rather than the target's generic reference label. + +`finish()` binds requests to surviving handles and their final caption data, +following renamed output IDs without repeating selection or callbacks. A removed +handle adds a located unresolved-reference warning and retains a missing target, +even if another block reuses its old ID. Captions keep their final period and +omit trailing whitespace in generated links. Captured title inline nodes retain +their normal formatting and output-stage substitutions; caption resolution does +not render titles or retain backend strings. + +Converter core's `display::prepare()` creates a fresh conversion context whose +`document()` contains ordinary cross-references with explicit inline labels. +The standard converters call it automatically. Custom converters should keep the +returned context alive for traversal. Repeated conversions leave the shared +`ParseResult` unchanged. Documents without display requests use the borrowed path. +Native JSON identifies symbolic labels with `generated_display`; checked ASG +export rejects them in both profiles until prepared through a conversion context. + +Direct comparisons with Asciidoctor 2.0.26 and `asciidoctor-lists` confirm explicit +labels overriding `reftext` and caption punctuation. acdc intentionally freezes +title attributes at selection and defers captions: the reference extension can +reevaluate raw titles with later attributes, escape reused rendered titles, and +retain captions captured before a later edit. These timing behaviors are not +compatibility claims. User-defined late inline processors remain a later stage. + Successful edits repair references, TOC, scoped footnotes, and unresolved/duplicate ID warnings before returning. Other parse and construction warnings retain their order; repair refreshes only reference-related warnings. Validation or repair diff --git a/converters/dev/CHANGELOG.md b/converters/dev/CHANGELOG.md index bfffb14ca..4a6d1fd19 100644 --- a/converters/dev/CHANGELOG.md +++ b/converters/dev/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- Converter fixtures can use `fixture-display::id[]` to exercise captured titles, + finalized captions, renamed targets, and missing-target fallback through the + public extension API across backends. + ### Fixed - Fixture generation now exits with an error when parsing or conversion fails, so scripts cannot report success with missing output. Failed conversions preserve existing expectations. diff --git a/converters/dev/src/fixtures.rs b/converters/dev/src/fixtures.rs index 3eec8049a..e70faa42c 100644 --- a/converters/dev/src/fixtures.rs +++ b/converters/dev/src/fixtures.rs @@ -9,6 +9,8 @@ use std::{ use acdc_converters_core::Warning; use acdc_parser::{Options, ParseResult, SafeMode, parse_file}; +mod display; + /// Output and structured diagnostics produced by a fixture adapter. pub struct FixtureOutput { /// Rendered bytes, before test-specific normalization. @@ -25,7 +27,32 @@ pub fn parse_fixture(path: &Path) -> Result> { let options = Options::builder() .with_safe_mode(SafeMode::Unsafe) .build()?; - Ok(parse_file(path, &options)?) + parse_fixture_with_options(path, &options) +} + +/// Parse a fixture with caller-supplied backend defaults and generic fixture processors. +/// +/// # Errors +/// Returns an error when parsing or a fixture's extension request fails. +pub fn parse_fixture_with_options( + path: &Path, + options: &Options, +) -> Result> { + // Keep ordinary fixtures on the ordinary parser path. Only the display + // fixture family opts into this public extension consumer. + let display_fixture = path + .file_stem() + .and_then(|name| name.to_str()) + .is_some_and(|name| { + name.strip_prefix("commonmark_") + .unwrap_or(name) + .starts_with("extension_display") + }); + if display_fixture { + Ok(display::registry()?.parse_file(path, options)?.finish()?) + } else { + Ok(parse_file(path, options)?) + } } /// Discover sorted `.adoc` files directly inside a fixture source directory. diff --git a/converters/dev/src/fixtures/display.rs b/converters/dev/src/fixtures/display.rs new file mode 100644 index 000000000..dda0f4086 --- /dev/null +++ b/converters/dev/src/fixtures/display.rs @@ -0,0 +1,99 @@ +//! Generic public-API consumer shared by converter fixtures. + +use acdc_parser::{ + Error, + extensions::{ + BlockBuilder, BlockMacro, BlockMacroOutput, BlockMacroProcessor, DisplayIntent, + DocumentEditor, MacroExecutionContext, MacroInvocation, Registry, TreeProcessor, + TreeProcessorRegistration, + }, +}; + +pub(super) fn registry() -> Result { + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("fixture-display", || Defer))?; + builder.register_tree_processor(TreeProcessorRegistration::new("fixture-display", || { + Display + }))?; + Ok(builder.build()) +} + +struct Defer; + +impl BlockMacroProcessor for Defer { + fn process( + &mut self, + _: &MacroInvocation<'_>, + _: &mut MacroExecutionContext, + ) -> Result { + Ok(BlockMacroOutput::Deferred) + } +} + +struct Display; + +impl TreeProcessor for Display { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let requests: Vec<_> = editor + .deferred_blocks() + .iter() + .map(|request| { + ( + request.target().clone(), + request.invocation.target.to_string(), + request.invocation.location.clone(), + ) + }) + .collect(); + // Capture the full membership before constructing output or editing targets. + let mut selected = Vec::new(); + for (output, id, origin) in requests { + let target = editor + .query() + .blocks() + .find(|view| view.output_id() == Some(id.as_str())) + .map(|view| view.target().clone()) + .ok_or_else(|| { + Error::Extension( + Box::new(origin.clone()), + format!("fixture display target {id} is absent"), + ) + })?; + selected.push((output, target.clone(), editor.capture(&target)?)); + } + for (output, _, target) in &selected { + editor.replace_placeholder( + output, + BlockBuilder::unordered_list([ + vec![target.display(DisplayIntent::Caption)], + vec![target.display(DisplayIntent::Title)], + vec![target.display(DisplayIntent::CaptionAndTitle)], + ]), + )?; + } + // The frozen titles keep their formatting and original attribute context; + // caption requests observe this later edit and the renamed output ID. + for (_, target, _) in selected { + if editor + .query() + .get(&target) + .is_some_and(|view| view.output_id() == Some("edited")) + { + editor.replace_block( + &target, + BlockBuilder::listing("changed").with_attributes( + "id=renamed,title='Changed *later*',caption='*Updated* <&> '", + ), + )?; + } + if editor + .query() + .get(&target) + .is_some_and(|view| view.output_id() == Some("removed")) + { + editor.remove_section(&target)?; + } + } + Ok(()) + } +} diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index f08df3dae..dc3e9b213 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Extension-generated caption and captured-title links now use explicit labels, + preserving title formatting and source attributes while following final captions + and renamed targets. Repeated conversion preserves the shared parsed document. + - Highlighted source blocks with a line longer than 16 KiB render as plain source, with one structured warning per document. Text, callouts, line numbers, and selected-line backgrounds are preserved. This acdc limit avoids diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index c6ad3b8e3..4bfa7ee5f 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -280,7 +280,8 @@ impl<'a> Converter<'a> { options: &RenderOptions, diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Error> { - let document = doc; + let prepared = acdc_converters_core::display::prepare(doc)?; + let document = prepared.document(); let converter = Converter { toc_entries: document.toc_entries().map(TocEntry::from).collect(), references: document.references().into(), diff --git a/converters/html/tests/extension_displays.rs b/converters/html/tests/extension_displays.rs new file mode 100644 index 000000000..19b85c5b0 --- /dev/null +++ b/converters/html/tests/extension_displays.rs @@ -0,0 +1,39 @@ +use std::{error::Error, path::Path}; + +use acdc_converters_core::Options; +use acdc_converters_dev::fixtures::parse_fixture_with_options; +use acdc_converters_html::{Converter, HtmlVariant, RenderOptions}; +use acdc_parser::{CompatibilityMode, Document, Options as ParserOptions}; + +#[test] +fn extension_displays_repeat_without_refreshing_titles_or_mutating_shared_document() +-> Result<(), Box> { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/source/html/embedded/extension_displays.adoc"); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = ParserOptions::builder() + .with_compatibility_mode(mode) + .build()?; + let parsed = parse_fixture_with_options(&path, &options)?; + let original = Document::from(parsed.document()); + for variant in [HtmlVariant::Standard, HtmlVariant::Semantic] { + let converter = + Converter::new_with_variant(Options::default(), ParserOptions::builder(), variant)?; + let render = RenderOptions { + embedded: true, + ..RenderOptions::default() + }; + let first = converter.convert_to_string(parsed.document(), &render)?; + let second = converter.convert_to_string(parsed.document(), &render)?; + assert_eq!(first, second); + assert!( + first.contains("href=\"#renamed\">Dot Early <&>") + ); + assert!(first.contains("href=\"#renamed\">Updated <&> Dot Early")); + assert!(!first.contains("Custom reference")); + assert!(!first.contains("&lt;")); + assert_eq!(Document::from(parsed.document()), original); + } + } + Ok(()) +} diff --git a/converters/html/tests/fixtures/expected/html/embedded/extension_display_removal.html b/converters/html/tests/fixtures/expected/html/embedded/extension_display_removal.html new file mode 100644 index 000000000..8cc0a151c --- /dev/null +++ b/converters/html/tests/fixtures/expected/html/embedded/extension_display_removal.html @@ -0,0 +1,26 @@ +
+

NAME

+
+
+

extension-display-removal - unresolved generated references

+
+
+
+
+

DESCRIPTION

+
+
+ +
+
+
diff --git a/converters/html/tests/fixtures/expected/html/embedded/extension_displays.html b/converters/html/tests/fixtures/expected/html/embedded/extension_displays.html new file mode 100644 index 000000000..d228aed6e --- /dev/null +++ b/converters/html/tests/fixtures/expected/html/embedded/extension_displays.html @@ -0,0 +1,108 @@ +
+

NAME

+
+
+

extension-displays - captured titles and deferred captions

+
+
+
+
+

DESCRIPTION

+
+
+
Updated <&> Changed later
+
+
changed
+
+
+
+
Code 2. Attribute Early <&>
+
+
attribute
+
+
+
+
*Literal* <&> Literal caption
+
+
literal
+
+
+
+
Empty caption
+
+
empty
+
+
+
+
Disabled caption
+
+
disabled
+
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
diff --git a/converters/html/tests/fixtures/expected/html5s/embedded/extension_display_removal.html b/converters/html/tests/fixtures/expected/html5s/embedded/extension_display_removal.html new file mode 100644 index 000000000..b7bac8baa --- /dev/null +++ b/converters/html/tests/fixtures/expected/html5s/embedded/extension_display_removal.html @@ -0,0 +1,17 @@ +
+

NAME

+

extension-display-removal - unresolved generated references

+
+
+

DESCRIPTION

+
+ +
+
diff --git a/converters/html/tests/fixtures/expected/html5s/embedded/extension_displays.html b/converters/html/tests/fixtures/expected/html5s/embedded/extension_displays.html new file mode 100644 index 000000000..e5d0e39da --- /dev/null +++ b/converters/html/tests/fixtures/expected/html5s/embedded/extension_displays.html @@ -0,0 +1,77 @@ +
+

NAME

+

extension-displays - captured titles and deferred captions

+
+
+

DESCRIPTION

+
+
Updated <&> Changed later
+
changed
+
+
+
Code 2. Attribute Early <&>
+
attribute
+
+
+
*Literal* <&> Literal caption
+
literal
+
+
+
Empty caption
+
empty
+
+
+
Disabled caption
+
disabled
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
diff --git a/converters/html/tests/fixtures/source/html/embedded/extension_display_removal.adoc b/converters/html/tests/fixtures/source/html/embedded/extension_display_removal.adoc new file mode 100644 index 000000000..6334e3e8a --- /dev/null +++ b/converters/html/tests/fixtures/source/html/embedded/extension_display_removal.adoc @@ -0,0 +1,18 @@ += extension-display-removal(1) +:doctype: manpage +:docdate: 2026-11-15 +:revdate: 2026-11-15 +:reproducible: + +== NAME + +extension-display-removal - unresolved generated references + +[#removed] +== Original *title* + +Removed content. + +== DESCRIPTION + +fixture-display::removed[] diff --git a/converters/html/tests/fixtures/source/html/embedded/extension_displays.adoc b/converters/html/tests/fixtures/source/html/embedded/extension_displays.adoc new file mode 100644 index 000000000..2cb1f6140 --- /dev/null +++ b/converters/html/tests/fixtures/source/html/embedded/extension_displays.adoc @@ -0,0 +1,58 @@ += extension-displays(1) +:doctype: manpage +:docdate: 2026-11-15 +:revdate: 2026-11-15 +:mansource: acdc +:manmanual: Extension displays +:listing-caption: Code +:label: Early +:reproducible: + +== NAME + +extension-displays - captured titles and deferred captions + +== DESCRIPTION + +.Dot *{label}* <&> +[#edited,reftext='Custom *reference*'] +---- +original +---- + +[#attribute,title='Attribute _{label}_ <&>'] +---- +attribute +---- + +.Literal caption +[#literal,caption="*Literal* <&> "] +---- +literal +---- + +.Empty caption +[#empty,caption=''] +---- +empty +---- + +:listing-caption!: + +.Disabled *caption* +[#disabled] +---- +disabled +---- + +:label: Late + +fixture-display::edited[] + +fixture-display::attribute[] + +fixture-display::literal[] + +fixture-display::empty[] + +fixture-display::disabled[] diff --git a/converters/html/tests/fixtures/source/html5s/embedded/extension_display_removal.adoc b/converters/html/tests/fixtures/source/html5s/embedded/extension_display_removal.adoc new file mode 120000 index 000000000..ddf388eb6 --- /dev/null +++ b/converters/html/tests/fixtures/source/html5s/embedded/extension_display_removal.adoc @@ -0,0 +1 @@ +../../html/embedded/extension_display_removal.adoc \ No newline at end of file diff --git a/converters/html/tests/fixtures/source/html5s/embedded/extension_displays.adoc b/converters/html/tests/fixtures/source/html5s/embedded/extension_displays.adoc new file mode 120000 index 000000000..e54f66441 --- /dev/null +++ b/converters/html/tests/fixtures/source/html5s/embedded/extension_displays.adoc @@ -0,0 +1 @@ +../../html/embedded/extension_displays.adoc \ No newline at end of file diff --git a/converters/manpage/CHANGELOG.md b/converters/manpage/CHANGELOG.md index c22c4801f..8c1445241 100644 --- a/converters/manpage/CHANGELOG.md +++ b/converters/manpage/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Extension-generated caption and captured-title links now use explicit labels, + preserving title formatting and source attributes while following final captions + and renamed targets. Repeated conversion preserves the shared parsed document. + - **Breaking:** construct and render manpages through `Converter`, renamed from `Processor`. Conversion behavior is unchanged. Import the shared `acdc_converters_core::Converter` trait as `_` when diff --git a/converters/manpage/src/lib.rs b/converters/manpage/src/lib.rs index 3317cc506..4ae83e7d3 100644 --- a/converters/manpage/src/lib.rs +++ b/converters/manpage/src/lib.rs @@ -119,14 +119,15 @@ impl Converter<'_> { _source_file: Option<&Path>, diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Error> { - let document = doc; + let prepared = acdc_converters_core::display::prepare(doc)?; + let document = prepared.document(); let attrs: DocumentAttributes<'_> = document.attributes().into(); // This converter borrows from `doc`; its lifetime is independent of `self`. let converter: Converter<'_> = Converter { options: self.options.clone(), parser_options: ParserOptions::default().with_document_attributes(attrs), - references: Rc::new(doc.references().into()), + references: Rc::new(document.references().into()), xref_guard: XrefGuard::default(), top_level_section_ids: Rc::new( document diff --git a/converters/manpage/tests/fixtures/expected/extension_display_removal.man b/converters/manpage/tests/fixtures/expected/extension_display_removal.man new file mode 100644 index 000000000..da64262f9 --- /dev/null +++ b/converters/manpage/tests/fixtures/expected/extension_display_removal.man @@ -0,0 +1,39 @@ +'\" t +.\" Title: extension-display-removal +.\" Author: [see the "AUTHOR(S)" section] +.\" Generator: acdc 0.1.0 +.\" Manual: \ \& +.\" Source: \ \& +.\" Language: English +.\" +.TH "EXTENSION\-DISPLAY\-REMOVAL" "1" "" "\ \&" "\ \&" +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.ss \n[.ss] 0 +.nh +.ad l +.de URL +\fI\\$2\fP <\\$1>\\$3 +.. +.als MTO URL +.if \n[.g] \{\ +. mso www.tmac +. am URL +. ad l +. . +. am MTO +. ad l +. . +. LINKSTYLE blue R < > +.\} +.SH "NAME" +extension\-display\-removal \- unresolved generated references +.SH "DESCRIPTION" +.RS 0 +.IP \(bu 2 +[removed] +.IP \(bu 2 +[removed] +.IP \(bu 2 +[removed] Original \fBtitle\fR +.RE diff --git a/converters/manpage/tests/fixtures/expected/extension_displays.man b/converters/manpage/tests/fixtures/expected/extension_displays.man new file mode 100644 index 000000000..b413f1d1b --- /dev/null +++ b/converters/manpage/tests/fixtures/expected/extension_displays.man @@ -0,0 +1,101 @@ +'\" t +.\" Title: extension-displays +.\" Author: [see the "AUTHOR(S)" section] +.\" Generator: acdc 0.1.0 +.\" Manual: Extension displays +.\" Source: acdc +.\" Language: English +.\" +.TH "EXTENSION\-DISPLAYS" "1" "" "acdc" "Extension displays" +.ie \n(.g .ds Aq \(aq +.el .ds Aq ' +.ss \n[.ss] 0 +.nh +.ad l +.de URL +\fI\\$2\fP <\\$1>\\$3 +.. +.als MTO URL +.if \n[.g] \{\ +. mso www.tmac +. am URL +. ad l +. . +. am MTO +. ad l +. . +. LINKSTYLE blue R < > +.\} +.SH "NAME" +extension\-displays \- captured titles and deferred captions +.SH "DESCRIPTION" +.sp +\fB\fBUpdated\fB <&> Changed \fBlater\fB\fR +.br +.EX +changed +.EE +.sp +\fBCode 2. Attribute \fIEarly\fB <&>\fR +.br +.EX +attribute +.EE +.sp +\fB*Literal* <&> Literal caption\fR +.br +.EX +literal +.EE +.sp +\fBEmpty caption\fR +.br +.EX +empty +.EE +.sp +\fBDisabled \fBcaption\fB\fR +.br +.EX +disabled +.EE +.RS 0 +.IP \(bu 2 +\fBUpdated\fR <&> +.IP \(bu 2 +Dot \fBEarly\fR <&> +.IP \(bu 2 +\fBUpdated\fR <&> Dot \fBEarly\fR <&> +.RE +.RS 0 +.IP \(bu 2 +Code 2. +.IP \(bu 2 +Attribute \fIEarly\fR <&> +.IP \(bu 2 +Code 2. Attribute \fIEarly\fR <&> +.RE +.RS 0 +.IP \(bu 2 +*Literal* <&> +.IP \(bu 2 +Literal caption +.IP \(bu 2 +*Literal* <&> Literal caption +.RE +.RS 0 +.IP \(bu 2 + +.IP \(bu 2 +Empty caption +.IP \(bu 2 + Empty caption +.RE +.RS 0 +.IP \(bu 2 +[disabled] +.IP \(bu 2 +Disabled \fBcaption\fR +.IP \(bu 2 +[disabled] Disabled \fBcaption\fR +.RE diff --git a/converters/manpage/tests/fixtures/source/extension_display_removal.adoc b/converters/manpage/tests/fixtures/source/extension_display_removal.adoc new file mode 120000 index 000000000..b770e1f11 --- /dev/null +++ b/converters/manpage/tests/fixtures/source/extension_display_removal.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_display_removal.adoc \ No newline at end of file diff --git a/converters/manpage/tests/fixtures/source/extension_displays.adoc b/converters/manpage/tests/fixtures/source/extension_displays.adoc new file mode 120000 index 000000000..ccaf2e8e5 --- /dev/null +++ b/converters/manpage/tests/fixtures/source/extension_displays.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_displays.adoc \ No newline at end of file diff --git a/converters/markdown/CHANGELOG.md b/converters/markdown/CHANGELOG.md index 0e9835a5f..2aa9bdc89 100644 --- a/converters/markdown/CHANGELOG.md +++ b/converters/markdown/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Extension-generated caption and captured-title links now use explicit labels, + preserving title formatting and source attributes while following final captions + and renamed targets. Repeated conversion preserves the shared parsed document. + - **Breaking:** construct and render Markdown through `Converter`, renamed from `Processor`. Variant selection and output behavior are unchanged. Import the shared `acdc_converters_core::Converter` trait as `_` when diff --git a/converters/markdown/src/lib.rs b/converters/markdown/src/lib.rs index 50ac67a4f..e73683053 100644 --- a/converters/markdown/src/lib.rs +++ b/converters/markdown/src/lib.rs @@ -353,6 +353,8 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { _output_path: Option<&Path>, diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Self::Error> { + let prepared = acdc_converters_core::display::prepare(doc)?; + let doc = prepared.document(); // This converter borrows from `doc`; its lifetime is independent of `self`. let converter = Converter { options: self.options.clone(), diff --git a/converters/markdown/tests/fixtures/expected/commonmark_extension_displays.md b/converters/markdown/tests/fixtures/expected/commonmark_extension_displays.md new file mode 100644 index 000000000..182c915d2 --- /dev/null +++ b/converters/markdown/tests/fixtures/expected/commonmark_extension_displays.md @@ -0,0 +1,66 @@ +# extension-displays(1) + +2026-11-15 + + +## NAME + +extension-displays - captured titles and deferred captions + + +## DESCRIPTION + + +**Updated** \<&\> Changed **later** + +``` +changed +``` + + +Code 2. Attribute *Early* \<&\> + +``` +attribute +``` + + +\*Literal\* <&> Literal caption + +``` +literal +``` + + +Empty caption + +``` +empty +``` + + +Disabled **caption** + +``` +disabled +``` + +- [**Updated** \<&\>](#renamed) +- [Dot **Early** \<&\>](#renamed) +- [**Updated** \<&\>](#renamed) Dot **Early** \<&\> + +- [Code 2.](#attribute) +- [Attribute *Early* \<&\>](#attribute) +- [Code 2.](#attribute) Attribute *Early* \<&\> + +- [\*Literal\* <&>](#literal) +- [Literal caption](#literal) +- [\*Literal\* <&>](#literal) Literal caption + +- [](#empty) +- [Empty caption](#empty) +- [](#empty) Empty caption + +- [\[disabled\]](#disabled) +- [Disabled **caption**](#disabled) +- [\[disabled\]](#disabled) Disabled **caption** diff --git a/converters/markdown/tests/fixtures/expected/extension_display_removal.md b/converters/markdown/tests/fixtures/expected/extension_display_removal.md new file mode 100644 index 000000000..87f72e84a --- /dev/null +++ b/converters/markdown/tests/fixtures/expected/extension_display_removal.md @@ -0,0 +1,15 @@ +# extension-display-removal(1) + +2026-11-15 + + +## NAME + +extension-display-removal - unresolved generated references + + +## DESCRIPTION + +- [\[removed\]](#_acdc_missing_4) +- [\[removed\]](#_acdc_missing_4) +- [\[removed\]](#_acdc_missing_4) Original **title** diff --git a/converters/markdown/tests/fixtures/expected/extension_displays.md b/converters/markdown/tests/fixtures/expected/extension_displays.md new file mode 100644 index 000000000..182c915d2 --- /dev/null +++ b/converters/markdown/tests/fixtures/expected/extension_displays.md @@ -0,0 +1,66 @@ +# extension-displays(1) + +2026-11-15 + + +## NAME + +extension-displays - captured titles and deferred captions + + +## DESCRIPTION + + +**Updated** \<&\> Changed **later** + +``` +changed +``` + + +Code 2. Attribute *Early* \<&\> + +``` +attribute +``` + + +\*Literal\* <&> Literal caption + +``` +literal +``` + + +Empty caption + +``` +empty +``` + + +Disabled **caption** + +``` +disabled +``` + +- [**Updated** \<&\>](#renamed) +- [Dot **Early** \<&\>](#renamed) +- [**Updated** \<&\>](#renamed) Dot **Early** \<&\> + +- [Code 2.](#attribute) +- [Attribute *Early* \<&\>](#attribute) +- [Code 2.](#attribute) Attribute *Early* \<&\> + +- [\*Literal\* <&>](#literal) +- [Literal caption](#literal) +- [\*Literal\* <&>](#literal) Literal caption + +- [](#empty) +- [Empty caption](#empty) +- [](#empty) Empty caption + +- [\[disabled\]](#disabled) +- [Disabled **caption**](#disabled) +- [\[disabled\]](#disabled) Disabled **caption** diff --git a/converters/markdown/tests/fixtures/source/commonmark_extension_displays.adoc b/converters/markdown/tests/fixtures/source/commonmark_extension_displays.adoc new file mode 120000 index 000000000..ccaf2e8e5 --- /dev/null +++ b/converters/markdown/tests/fixtures/source/commonmark_extension_displays.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_displays.adoc \ No newline at end of file diff --git a/converters/markdown/tests/fixtures/source/extension_display_removal.adoc b/converters/markdown/tests/fixtures/source/extension_display_removal.adoc new file mode 120000 index 000000000..b770e1f11 --- /dev/null +++ b/converters/markdown/tests/fixtures/source/extension_display_removal.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_display_removal.adoc \ No newline at end of file diff --git a/converters/markdown/tests/fixtures/source/extension_displays.adoc b/converters/markdown/tests/fixtures/source/extension_displays.adoc new file mode 120000 index 000000000..ccaf2e8e5 --- /dev/null +++ b/converters/markdown/tests/fixtures/source/extension_displays.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_displays.adoc \ No newline at end of file diff --git a/converters/pdf/CHANGELOG.md b/converters/pdf/CHANGELOG.md index 8046bb0b3..b9276cc0b 100644 --- a/converters/pdf/CHANGELOG.md +++ b/converters/pdf/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Extension-generated caption and captured-title links now use explicit labels, + preserving title formatting and source attributes while following final captions + and renamed targets. Repeated conversion preserves the shared parsed document. + - **Breaking:** use `Converter` in place of `Processor` and `PageOrientation` in place of `PageLayout`. PDF settings and output are unchanged. Import the shared `acdc_converters_core::Converter` trait as `_` when diff --git a/converters/pdf/src/lib.rs b/converters/pdf/src/lib.rs index afa474073..4c4fcaf8f 100644 --- a/converters/pdf/src/lib.rs +++ b/converters/pdf/src/lib.rs @@ -358,6 +358,8 @@ impl Converter<'_> { doc: DocumentRef<'_>, diagnostics: &mut Diagnostics<'_>, ) -> Result { + let prepared = acdc_converters_core::display::prepare(doc)?; + let doc = prepared.document(); let loaded = self.load_theme(diagnostics)?; let theme = &loaded.theme; let page_numbering = self.page_numbering_plan(doc, theme); @@ -392,6 +394,8 @@ impl Converter<'_> { source_file: Option<&Path>, diagnostics: &mut Diagnostics<'_>, ) -> Result { + let prepared = acdc_converters_core::display::prepare(doc)?; + let doc = prepared.document(); self.validate_theme_config_paths(source_file, None)?; let loaded = self.load_theme(diagnostics)?; let theme = &loaded.theme; diff --git a/converters/pdf/tests/extension_displays.rs b/converters/pdf/tests/extension_displays.rs new file mode 100644 index 000000000..975d64900 --- /dev/null +++ b/converters/pdf/tests/extension_displays.rs @@ -0,0 +1,88 @@ +use std::{error::Error as StdError, fs}; + +use acdc_converters_core::{Converter as _, Diagnostics, Options, WarningSource}; +use acdc_converters_pdf::{Converter, PdfOptions}; +use acdc_parser::{ + Error, Options as ParserOptions, SafeMode, + extensions::{ + BlockBuilder, DisplayIntent, DocumentEditor, Registry, TreeProcessor, + TreeProcessorRegistration, + }, +}; + +struct Snapshot; + +impl TreeProcessor for Snapshot { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let targets: Vec<_> = editor + .query() + .blocks() + .map(|view| view.target().clone()) + .collect(); + if let (Some(target), Some(output)) = (targets.first(), targets.get(1)) { + let title = editor.capture(target)?; + editor.replace_block( + target, + BlockBuilder::paragraph("Changed.").with_attributes("title=Changed"), + )?; + editor.replace_block( + output, + BlockBuilder::paragraph_inlines([title.display(DisplayIntent::Title)]), + )?; + } + Ok(()) + } +} + +#[test] +fn extension_displays_prepare_captured_title_assets_before_pdf_resolution() +-> Result<(), Box> { + let directory = tempfile::tempdir()?; + fs::write( + directory.path().join("mark.svg"), + r#""#, + )?; + let source = directory.path().join("display.adoc"); + fs::write( + &source, + ".Original image:mark.svg[Mark]\nParagraph.\n\nOutput.", + )?; + let mut builder = Registry::builder(); + builder.register_tree_processor(TreeProcessorRegistration::new("snapshot", || Snapshot))?; + let parsed = builder + .build() + .parse_file(&source, &ParserOptions::default())? + .finish()?; + let typst_path = directory.path().join("display.typ"); + let converter = Converter::new( + Options::builder().safe_mode(SafeMode::Unsafe).build(), + ParserOptions::builder(), + )? + .with_pdf_options(PdfOptions { + emit_typst: Some(typst_path.clone()), + ..PdfOptions::default() + }); + let warning_source = WarningSource::new("pdf"); + let mut warnings = Vec::new(); + let mut output = Vec::new(); + converter.write_to( + parsed.document(), + &mut output, + Some(&source), + None, + &mut Diagnostics::new(&warning_source, &mut warnings), + )?; + assert!(output.starts_with(b"%PDF")); + let typst = fs::read_to_string(typst_path)?; + assert!( + typst.contains("#box(image(\"/images/"), + "captured image was not resolved: {typst}" + ); + assert!( + !warnings + .iter() + .any(|warning| warning.message.contains("mark.svg")), + "{warnings:?}" + ); + Ok(()) +} diff --git a/converters/pdf/tests/fixtures/expected/extension_display_removal.typ b/converters/pdf/tests/fixtures/expected/extension_display_removal.typ new file mode 100644 index 000000000..6732c6b41 --- /dev/null +++ b/converters/pdf/tests/fixtures/expected/extension_display_removal.typ @@ -0,0 +1,90 @@ +#set document( + title: "extension-display-removal(1)", +) +#set page(paper: "a4", margin: (x: 2.5cm, y: 2.5cm), fill: rgb("#ffffff"), header: context if counter(page).get().first() > 1 { align(left + horizon)[#text(fill: rgb("#374151"), weight: 500, size: 11pt)[extension-display-removal(1)]] }, footer: text(fill: rgb("#9ca3af"), size: 9pt)[#grid(columns: (1fr, 1fr, 1fr), align(left)[], align(center)[#context counter(page).display()], align(right)[])]) +#set text(font: ("IBM Plex Serif", "Noto Color Emoji"), size: 11pt, weight: 400, fill: rgb("#111111"), tracking: 0em, lang: "en") +#set par(leading: 0.65em, spacing: 19.15pt, justify: false) +#set block(spacing: 19.15pt) +#set smartquote(enabled: false) +#show regex("[`´]"): set text(features: ("mark": 0)) +#show heading: set text(font: ("IBM Plex Serif", "Noto Color Emoji"), weight: 700, fill: rgb("#000000")) +#show heading.where(level: 1): set text(size: 24pt) +#show heading.where(level: 2): set text(size: 18pt) +#show heading.where(level: 3): set text(size: 14pt) +#show heading.where(level: 4): set text(size: 12pt) +#show heading.where(level: 5): set text(size: 11pt) +#show heading.where(level: 6): set text(size: 10pt) +#show link: set text(fill: rgb("#2563eb")) +#show strong: set text(fill: rgb("#000000"), weight: 700) +#show raw: set text(font: ("IBM Plex Mono", "Noto Color Emoji")) +#set raw(theme: "/assets/highlight.tmTheme") +#show raw.where(block: false): set text(fill: rgb("#000000")) +#let tablemonospace(body) = text(font: ("IBM Plex Mono", "Noto Color Emoji"), fill: rgb("#000000"), body) +#show raw.where(block: true): it => block(width: 100%, fill: rgb("#1e1e1e"), radius: 4pt, inset: 10pt, text(fill: rgb("#d4d4d4"), it)) +#let captiontext(body) = { + show strong: set text(fill: rgb("#333333"), weight: 700, style: "normal") + show emph: it => text(style: "italic", it.body) + text(size: 0.91em, weight: 400, style: "italic", fill: rgb("#333333"), body) +} +#let blocktitle(body) = { + block(width: 100%, above: 19.15pt, below: 0pt, align(left, captiontext(body))) + block(height: 8pt, above: 0pt, below: 0pt) +} +#let imagecaption(body) = { + block(height: 8pt, above: 0pt, below: 0pt) + block(width: 100%, above: 0pt, below: 19.15pt, align(left, captiontext(body))) +} +#let admonitiontitle(body) = { + block(width: 100%, above: 0pt, below: 0pt, align(left, captiontext(body))) + block(height: 8pt, above: 0pt, below: 0pt) +} +#let abstract(body) = block(width: 100%, text(size: 13.75pt, style: "italic", fill: rgb("#4b5563"), body)) +#let abstracttitle(body) = block(width: 100%, below: 0.5em, align(center, text(size: 12pt, weight: 700, fill: rgb("#000000"), body))) +#let blockquote(body) = block(width: 100%, inset: (left: 12pt), stroke: (left: 3pt + rgb("#d1d5db")), text(style: "italic", fill: rgb("#4b5563"), body)) +#let examplebox(body) = block(width: 100%, fill: rgb("#f3f4f6"), radius: 4pt, inset: (x: 12pt, y: 10pt), body) +#let sidebarbox(body) = block(width: 100%, fill: rgb("#f3f4f6"), stroke: 0.75pt + rgb("#e5e7eb"), radius: 4pt, inset: (x: 12pt, y: 10pt), body) +#let sidebartitle(body) = align(center, text(weight: "bold", body)) +#let verse(body) = block(inset: (left: 12pt), text(fill: rgb("#4b5563"), body)) +#let attribution(body) = block(inset: (left: 12pt), above: 0.6em, text(size: 0.9em, fill: rgb("#4b5563"))[— #body]) +#let callout(kind, body) = pad(left: 0pt, block(width: 100%, inset: (x: 12pt, y: 4pt), grid(columns: (auto, 1fr), column-gutter: 12pt, align: (x, _) => if x == 0 { center + horizon } else { left + top }, text(fill: rgb("#111111"), weight: 700, upper(kind)), grid.cell(stroke: (left: 0.75pt + rgb("#e5e7eb")), inset: (left: 12pt), body)))) +#let checkbox(checked) = box(height: 0.85em, width: 0.85em, baseline: 0.15em, radius: 2pt, stroke: 0.75pt + rgb("#9ca3af"), fill: if checked { rgb("#374151") } else { white }) +#let hr() = block(above: 1.2em, below: 1.2em, line(length: 100%, stroke: 0.75pt + rgb("#e5e7eb"))) +#let docimage(path, alt: none, width: none, ratio: none, destination: none) = block(width: 100%, radius: 4pt, clip: true, layout(size => { + let resolved-width = if ratio != none { ratio * size.width } else if width != none { calc.min(width, size.width) } else { auto } + let content = image(path, alt: alt, width: resolved-width) + if destination == none { content } else { link(destination, content) } +})) +#set list(marker: (box(baseline: -0.2em, circle(radius: 0.14em, fill: rgb("#6b7280"))), box(baseline: -0.2em, circle(radius: 0.13em, stroke: 0.6pt + rgb("#6b7280"))), box(baseline: -0.2em, rect(width: 0.24em, height: 0.24em, fill: rgb("#6b7280"))))) +#set enum(numbering: (..n) => text(fill: rgb("#9ca3af"))[#numbering("1.", ..n.pos())]) +#set table(stroke: (_, y) => (bottom: 0.75pt + rgb("#e5e7eb")), inset: (x: 0.6em, y: 0.45em)) +#let tableemphasis(body) = { + show strong: set text(style: "normal") + text(style: "italic", body) +} +#let tablestrong(body) = { + show emph: set text(weight: 400) + text(weight: 700, body) +} +#let tableheader(body) = { + show emph: set text(weight: 400) + text(weight: 700, body) +} + +#let _acdc_arabic_page_start = none +#set page(numbering: "i") +#set page(numbering: "1") +#counter(page).update(1) +#align(center)[ +#text(size: 22pt, weight: "bold")[#text("extension-display-removal(1)")] +] +#v(1em) + +#heading(level: 1)[#text("NAME")] + +#text("extension-display-removal - unresolved generated references") + +#heading(level: 1)[#text("DESCRIPTION")] + + - #text("[removed]") + - #text("[removed]") + - #text("[removed]")#text(" ")#text("Original ")#strong[#text("title")] diff --git a/converters/pdf/tests/fixtures/expected/extension_displays.typ b/converters/pdf/tests/fixtures/expected/extension_displays.typ new file mode 100644 index 000000000..8a27cca21 --- /dev/null +++ b/converters/pdf/tests/fixtures/expected/extension_displays.typ @@ -0,0 +1,126 @@ +#set document( + title: "extension-displays(1)", +) +#set page(paper: "a4", margin: (x: 2.5cm, y: 2.5cm), fill: rgb("#ffffff"), header: context if counter(page).get().first() > 1 { align(left + horizon)[#text(fill: rgb("#374151"), weight: 500, size: 11pt)[extension-displays(1)]] }, footer: text(fill: rgb("#9ca3af"), size: 9pt)[#grid(columns: (1fr, 1fr, 1fr), align(left)[], align(center)[#context counter(page).display()], align(right)[])]) +#set text(font: ("IBM Plex Serif", "Noto Color Emoji"), size: 11pt, weight: 400, fill: rgb("#111111"), tracking: 0em, lang: "en") +#set par(leading: 0.65em, spacing: 19.15pt, justify: false) +#set block(spacing: 19.15pt) +#set smartquote(enabled: false) +#show regex("[`´]"): set text(features: ("mark": 0)) +#show heading: set text(font: ("IBM Plex Serif", "Noto Color Emoji"), weight: 700, fill: rgb("#000000")) +#show heading.where(level: 1): set text(size: 24pt) +#show heading.where(level: 2): set text(size: 18pt) +#show heading.where(level: 3): set text(size: 14pt) +#show heading.where(level: 4): set text(size: 12pt) +#show heading.where(level: 5): set text(size: 11pt) +#show heading.where(level: 6): set text(size: 10pt) +#show link: set text(fill: rgb("#2563eb")) +#show strong: set text(fill: rgb("#000000"), weight: 700) +#show raw: set text(font: ("IBM Plex Mono", "Noto Color Emoji")) +#set raw(theme: "/assets/highlight.tmTheme") +#show raw.where(block: false): set text(fill: rgb("#000000")) +#let tablemonospace(body) = text(font: ("IBM Plex Mono", "Noto Color Emoji"), fill: rgb("#000000"), body) +#show raw.where(block: true): it => block(width: 100%, fill: rgb("#1e1e1e"), radius: 4pt, inset: 10pt, text(fill: rgb("#d4d4d4"), it)) +#let captiontext(body) = { + show strong: set text(fill: rgb("#333333"), weight: 700, style: "normal") + show emph: it => text(style: "italic", it.body) + text(size: 0.91em, weight: 400, style: "italic", fill: rgb("#333333"), body) +} +#let blocktitle(body) = { + block(width: 100%, above: 19.15pt, below: 0pt, align(left, captiontext(body))) + block(height: 8pt, above: 0pt, below: 0pt) +} +#let imagecaption(body) = { + block(height: 8pt, above: 0pt, below: 0pt) + block(width: 100%, above: 0pt, below: 19.15pt, align(left, captiontext(body))) +} +#let admonitiontitle(body) = { + block(width: 100%, above: 0pt, below: 0pt, align(left, captiontext(body))) + block(height: 8pt, above: 0pt, below: 0pt) +} +#let abstract(body) = block(width: 100%, text(size: 13.75pt, style: "italic", fill: rgb("#4b5563"), body)) +#let abstracttitle(body) = block(width: 100%, below: 0.5em, align(center, text(size: 12pt, weight: 700, fill: rgb("#000000"), body))) +#let blockquote(body) = block(width: 100%, inset: (left: 12pt), stroke: (left: 3pt + rgb("#d1d5db")), text(style: "italic", fill: rgb("#4b5563"), body)) +#let examplebox(body) = block(width: 100%, fill: rgb("#f3f4f6"), radius: 4pt, inset: (x: 12pt, y: 10pt), body) +#let sidebarbox(body) = block(width: 100%, fill: rgb("#f3f4f6"), stroke: 0.75pt + rgb("#e5e7eb"), radius: 4pt, inset: (x: 12pt, y: 10pt), body) +#let sidebartitle(body) = align(center, text(weight: "bold", body)) +#let verse(body) = block(inset: (left: 12pt), text(fill: rgb("#4b5563"), body)) +#let attribution(body) = block(inset: (left: 12pt), above: 0.6em, text(size: 0.9em, fill: rgb("#4b5563"))[— #body]) +#let callout(kind, body) = pad(left: 0pt, block(width: 100%, inset: (x: 12pt, y: 4pt), grid(columns: (auto, 1fr), column-gutter: 12pt, align: (x, _) => if x == 0 { center + horizon } else { left + top }, text(fill: rgb("#111111"), weight: 700, upper(kind)), grid.cell(stroke: (left: 0.75pt + rgb("#e5e7eb")), inset: (left: 12pt), body)))) +#let checkbox(checked) = box(height: 0.85em, width: 0.85em, baseline: 0.15em, radius: 2pt, stroke: 0.75pt + rgb("#9ca3af"), fill: if checked { rgb("#374151") } else { white }) +#let hr() = block(above: 1.2em, below: 1.2em, line(length: 100%, stroke: 0.75pt + rgb("#e5e7eb"))) +#let docimage(path, alt: none, width: none, ratio: none, destination: none) = block(width: 100%, radius: 4pt, clip: true, layout(size => { + let resolved-width = if ratio != none { ratio * size.width } else if width != none { calc.min(width, size.width) } else { auto } + let content = image(path, alt: alt, width: resolved-width) + if destination == none { content } else { link(destination, content) } +})) +#set list(marker: (box(baseline: -0.2em, circle(radius: 0.14em, fill: rgb("#6b7280"))), box(baseline: -0.2em, circle(radius: 0.13em, stroke: 0.6pt + rgb("#6b7280"))), box(baseline: -0.2em, rect(width: 0.24em, height: 0.24em, fill: rgb("#6b7280"))))) +#set enum(numbering: (..n) => text(fill: rgb("#9ca3af"))[#numbering("1.", ..n.pos())]) +#set table(stroke: (_, y) => (bottom: 0.75pt + rgb("#e5e7eb")), inset: (x: 0.6em, y: 0.45em)) +#let tableemphasis(body) = { + show strong: set text(style: "normal") + text(style: "italic", body) +} +#let tablestrong(body) = { + show emph: set text(weight: 400) + text(weight: 700, body) +} +#let tableheader(body) = { + show emph: set text(weight: 400) + text(weight: 700, body) +} + +#let _acdc_arabic_page_start = none +#set page(numbering: "i") +#set page(numbering: "1") +#counter(page).update(1) +#align(center)[ +#text(size: 22pt, weight: "bold")[#text("extension-displays(1)")] +] +#v(1em) + +#heading(level: 1)[#text("NAME")] + +#text("extension-displays - captured titles and deferred captions") + +#heading(level: 1)[#text("DESCRIPTION")] + +#metadata(none) +#blocktitle[#strong[#text("Updated")]#text(" <&> ")#text("Changed ")#strong[#text("later")]] +#raw(block: true, "changed") + +#metadata(none) +#blocktitle[#text("Code 2. ")#text("Attribute ")#emph[#text("Early")]#text(" <&>")] +#raw(block: true, "attribute") + +#metadata(none) +#blocktitle[#text("*Literal* <&> ")#text("Literal caption")] +#raw(block: true, "literal") + +#metadata(none) +#blocktitle[#text("Empty caption")] +#raw(block: true, "empty") + +#metadata(none) +#blocktitle[#text("Disabled ")#strong[#text("caption")]] +#raw(block: true, "disabled") + + - #context link(query().first().location())[#strong[#text("Updated")]#text(" <&>")] + - #context link(query().first().location())[#text("Dot ")#strong[#text("Early")]#text(" <&>")] + - #context link(query().first().location())[#strong[#text("Updated")]#text(" <&>")]#text(" ")#text("Dot ")#strong[#text("Early")]#text(" <&>") + + - #context link(query().first().location())[#text("Code 2.")] + - #context link(query().first().location())[#text("Attribute ")#emph[#text("Early")]#text(" <&>")] + - #context link(query().first().location())[#text("Code 2.")]#text(" ")#text("Attribute ")#emph[#text("Early")]#text(" <&>") + + - #context link(query().first().location())[#text("*Literal* <&>")] + - #context link(query().first().location())[#text("Literal caption")] + - #context link(query().first().location())[#text("*Literal* <&>")]#text(" ")#text("Literal caption") + + - #context link(query().first().location())[#text("")] + - #context link(query().first().location())[#text("Empty caption")] + - #context link(query().first().location())[#text("")]#text(" ")#text("Empty caption") + + - #context link(query().first().location())[#text("[disabled]")] + - #context link(query().first().location())[#text("Disabled ")#strong[#text("caption")]] + - #context link(query().first().location())[#text("[disabled]")]#text(" ")#text("Disabled ")#strong[#text("caption")] diff --git a/converters/pdf/tests/fixtures/source/extension_display_removal.adoc b/converters/pdf/tests/fixtures/source/extension_display_removal.adoc new file mode 120000 index 000000000..b770e1f11 --- /dev/null +++ b/converters/pdf/tests/fixtures/source/extension_display_removal.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_display_removal.adoc \ No newline at end of file diff --git a/converters/pdf/tests/fixtures/source/extension_displays.adoc b/converters/pdf/tests/fixtures/source/extension_displays.adoc new file mode 120000 index 000000000..ccaf2e8e5 --- /dev/null +++ b/converters/pdf/tests/fixtures/source/extension_displays.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_displays.adoc \ No newline at end of file diff --git a/converters/pdf/tests/support/mod.rs b/converters/pdf/tests/support/mod.rs index ad3c8e97c..44b984fb4 100644 --- a/converters/pdf/tests/support/mod.rs +++ b/converters/pdf/tests/support/mod.rs @@ -5,11 +5,10 @@ use std::{ }; use acdc_converters_core::{Converter as _, Diagnostics, Options, WarningSource}; -use acdc_converters_dev::fixtures::FixtureOutput; +use acdc_converters_dev::fixtures::{FixtureOutput, parse_fixture_with_options}; use acdc_converters_pdf::{Converter, PdfOptions}; use acdc_parser::{ DocumentAttributes, Options as ParserOptions, OptionsBuilder, SafeMode, ast::DocumentRef, - parse_file, }; pub(crate) fn converter(builder: OptionsBuilder<'_>) -> Result, Box> { @@ -33,7 +32,7 @@ fn fixture_theme(doc: DocumentRef<'_>) -> Option { pub(crate) fn render(path: &Path) -> Result<(FixtureOutput, String), Box> { let bootstrap = converter(ParserOptions::builder())?; - let parsed = parse_file(path, bootstrap.parser_options())?; + let parsed = parse_fixture_with_options(path, bootstrap.parser_options())?; let doc = parsed.document(); let directory = tempfile::tempdir()?; let typst_path = directory.path().join("fixture.typ"); diff --git a/converters/terminal/CHANGELOG.md b/converters/terminal/CHANGELOG.md index 00116e935..ee90e26af 100644 --- a/converters/terminal/CHANGELOG.md +++ b/converters/terminal/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Extension-generated caption and captured-title links now use explicit labels, + preserving title formatting and source attributes while following final captions + and renamed targets. Repeated conversion preserves the shared parsed document. + - Source blocks with a line longer than 16 KiB render as plain source, preserving their text and returning one structured warning per document. This acdc limit avoids excessive highlighting time on long lines. HTML terminal previews diff --git a/converters/terminal/src/lib.rs b/converters/terminal/src/lib.rs index 627bda062..23e8b3630 100644 --- a/converters/terminal/src/lib.rs +++ b/converters/terminal/src/lib.rs @@ -180,7 +180,8 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Self::Error> { // This converter borrows from `doc`; its lifetime is independent of `self`. - let document = doc; + let prepared = acdc_converters_core::display::prepare(doc)?; + let document = prepared.document(); let converter = Converter { parser_options: ParserOptions::default() .with_document_attributes(document.attributes().into()), diff --git a/converters/terminal/tests/fixtures/catalog.rs b/converters/terminal/tests/fixtures/catalog.rs index f262398f5..e49ded87a 100644 --- a/converters/terminal/tests/fixtures/catalog.rs +++ b/converters/terminal/tests/fixtures/catalog.rs @@ -1,5 +1,7 @@ // (fixture_name, has_osc8_variant [, requires: ]) terminal_fixture_catalog!([ + (extension_displays, true), + (extension_display_removal, true), (description_shared_definitions, true), (subs_attributed_passthroughs, true), (subs_character_references, true), diff --git a/converters/terminal/tests/fixtures/expected/extension_display_removal.osc8.txt b/converters/terminal/tests/fixtures/expected/extension_display_removal.osc8.txt new file mode 100644 index 000000000..1adfbc38c --- /dev/null +++ b/converters/terminal/tests/fixtures/expected/extension_display_removal.osc8.txt @@ -0,0 +1,15 @@ +extension-display-removal(1)2026-11-15 + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +NAME +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +extension-display-removal - unresolved generated references + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +DESCRIPTION +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +• [removed] +• [removed] +• [removed] Original title diff --git a/converters/terminal/tests/fixtures/expected/extension_display_removal.txt b/converters/terminal/tests/fixtures/expected/extension_display_removal.txt new file mode 100644 index 000000000..1adfbc38c --- /dev/null +++ b/converters/terminal/tests/fixtures/expected/extension_display_removal.txt @@ -0,0 +1,15 @@ +extension-display-removal(1)2026-11-15 + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +NAME +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +extension-display-removal - unresolved generated references + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +DESCRIPTION +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +• [removed] +• [removed] +• [removed] Original title diff --git a/converters/terminal/tests/fixtures/expected/extension_displays.osc8.txt b/converters/terminal/tests/fixtures/expected/extension_displays.osc8.txt new file mode 100644 index 000000000..79253d893 --- /dev/null +++ b/converters/terminal/tests/fixtures/expected/extension_displays.osc8.txt @@ -0,0 +1,56 @@ +extension-displays(1)2026-11-15 + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +NAME +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +extension-displays - captured titles and deferred captions + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +DESCRIPTION +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Updated <&> Changed later +──────────────────────────────────────────────────────────────────────────────── +changed +──────────────────────────────────────────────────────────────────────────────── + +Code 2. Attribute Early <&> +──────────────────────────────────────────────────────────────────────────────── +attribute +──────────────────────────────────────────────────────────────────────────────── + +*Literal* <&> Literal caption +──────────────────────────────────────────────────────────────────────────────── +literal +──────────────────────────────────────────────────────────────────────────────── + +Empty caption +──────────────────────────────────────────────────────────────────────────────── +empty +──────────────────────────────────────────────────────────────────────────────── + +Disabled caption +──────────────────────────────────────────────────────────────────────────────── +disabled +──────────────────────────────────────────────────────────────────────────────── + +• Updated <&> +• Dot Early <&> +• Updated <&> Dot Early <&> + +• Code 2. +• Attribute Early <&> +• Code 2. Attribute Early <&> + +• *Literal* <&> +• Literal caption +• *Literal* <&> Literal caption + +•  +• Empty caption +•  Empty caption + +• [disabled] +• Disabled caption +• [disabled] Disabled caption diff --git a/converters/terminal/tests/fixtures/expected/extension_displays.txt b/converters/terminal/tests/fixtures/expected/extension_displays.txt new file mode 100644 index 000000000..79253d893 --- /dev/null +++ b/converters/terminal/tests/fixtures/expected/extension_displays.txt @@ -0,0 +1,56 @@ +extension-displays(1)2026-11-15 + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +NAME +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +extension-displays - captured titles and deferred captions + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +DESCRIPTION +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Updated <&> Changed later +──────────────────────────────────────────────────────────────────────────────── +changed +──────────────────────────────────────────────────────────────────────────────── + +Code 2. Attribute Early <&> +──────────────────────────────────────────────────────────────────────────────── +attribute +──────────────────────────────────────────────────────────────────────────────── + +*Literal* <&> Literal caption +──────────────────────────────────────────────────────────────────────────────── +literal +──────────────────────────────────────────────────────────────────────────────── + +Empty caption +──────────────────────────────────────────────────────────────────────────────── +empty +──────────────────────────────────────────────────────────────────────────────── + +Disabled caption +──────────────────────────────────────────────────────────────────────────────── +disabled +──────────────────────────────────────────────────────────────────────────────── + +• Updated <&> +• Dot Early <&> +• Updated <&> Dot Early <&> + +• Code 2. +• Attribute Early <&> +• Code 2. Attribute Early <&> + +• *Literal* <&> +• Literal caption +• *Literal* <&> Literal caption + +•  +• Empty caption +•  Empty caption + +• [disabled] +• Disabled caption +• [disabled] Disabled caption diff --git a/converters/terminal/tests/fixtures/source/extension_display_removal.adoc b/converters/terminal/tests/fixtures/source/extension_display_removal.adoc new file mode 120000 index 000000000..b770e1f11 --- /dev/null +++ b/converters/terminal/tests/fixtures/source/extension_display_removal.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_display_removal.adoc \ No newline at end of file diff --git a/converters/terminal/tests/fixtures/source/extension_displays.adoc b/converters/terminal/tests/fixtures/source/extension_displays.adoc new file mode 120000 index 000000000..ccaf2e8e5 --- /dev/null +++ b/converters/terminal/tests/fixtures/source/extension_displays.adoc @@ -0,0 +1 @@ +../../../../html/tests/fixtures/source/html/embedded/extension_displays.adoc \ No newline at end of file From 5257a8cf08b0b215f802cbbe96acbe926159071c Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 15 Nov 2026 22:57:50 +0100 Subject: [PATCH 19/55] feat(converters): expose a shared extension pipeline Select backend configuration and named registrations before source processing, then coordinate parser finalization and display preparation for library callers. Add reader sessions and atomic registry composition while preserving the inactive parser path and structured diagnostics. Reset HTML index counters for each conversion so reused converters produce stable output. SC-540 --- Cargo.lock | 2 + acdc-parser/CHANGELOG.md | 4 + acdc-parser/README.adoc | 13 + acdc-parser/README.md | 13 + acdc-parser/src/extensions/registry.rs | 46 +++ acdc-parser/src/lib.rs | 25 ++ converters/README.adoc | 39 ++ converters/core/CHANGELOG.md | 6 + converters/core/Cargo.toml | 4 + converters/core/src/lib.rs | 1 + converters/core/src/pipeline.rs | 150 +++++++ converters/core/src/pipeline/extensions.rs | 96 +++++ converters/core/tests/pipeline.rs | 390 ++++++++++++++++++ converters/html/CHANGELOG.md | 3 + .../html/examples/extension_pipeline.rs | 63 +++ converters/html/src/lib.rs | 4 +- converters/html/tests/pipeline.rs | 46 +++ 17 files changed, 903 insertions(+), 2 deletions(-) create mode 100644 converters/core/src/pipeline.rs create mode 100644 converters/core/src/pipeline/extensions.rs create mode 100644 converters/core/tests/pipeline.rs create mode 100644 converters/html/examples/extension_pipeline.rs create mode 100644 converters/html/tests/pipeline.rs diff --git a/Cargo.lock b/Cargo.lock index 8474210fe..e37dc7008 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -40,6 +40,8 @@ dependencies = [ "percent-encoding", "relative-path 2.0.3", "rustc-hash", + "serde_json", + "tempfile", "thiserror", "tracing", ] diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index b386b21f7..376d426cc 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Registered extensions now support reader input, including source-ordered + callback attribute changes before later conditionals and includes. Applications + can compose registries in order with duplicate-name checks before parsing. + - Tree processors can capture titles with `DocumentEditor::capture()` and build caption, title, or caption-and-title links through `DisplayIntent` and the inline block builders. `BlockBuilder::unordered_list()` accepts both literal strings diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 46ef29312..7b92fb5e8 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2064,6 +2064,11 @@ source location and a read-only attribute snapshot. Both compatibility modes support registrations. Factories are shared; handlers may use document-local, non-`Send` state. Completed callback effects remain if later parsing fails. +`Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. +Reader input preserves ordinary reader attributes and include-origin policy. +`RegistryBuilder::extend` composes immutable registries in order and rejects +duplicate macro or tree-processor names before changing the builder. + Nested source ordering supports compound bodies and pipe/exclamation-delimited AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered preprocessing. Unlike Asciidoctor 2.0.26, callbacks in supported nested bodies can @@ -2174,6 +2179,14 @@ fails; a processor sequence is not a transaction. See the `extensions` module documentation for registration and processor examples. An empty registry uses the ordinary parser path. +For backend-aware parsing through conversion, use converter core's +`pipeline::Pipeline` with an already configured backend. `ExtensionCatalog` +separates named availability from explicit activation and rejects unavailable +selections before parsing. Pipeline parse methods return finalized `ParseResult` +values with structured warnings; conversion prepares fresh display content and +leaves parsed storage unchanged. See the +link:../converters/README.adoc[converter guide] and its runnable library example. + [#parser-fixtures] == Parser fixtures diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 2916d8b29..2f41d8d54 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1708,6 +1708,11 @@ source location and a read-only attribute snapshot. Both compatibility modes support registrations. Factories are shared; handlers may use document-local, non-`Send` state. Completed callback effects remain if later parsing fails. +`Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. +Reader input preserves ordinary reader attributes and include-origin policy. +`RegistryBuilder::extend` composes immutable registries in order and rejects +duplicate macro or tree-processor names before changing the builder. + Nested source ordering supports compound bodies and pipe/exclamation-delimited AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered preprocessing. Unlike Asciidoctor 2.0.26, callbacks in supported nested bodies can @@ -1818,6 +1823,14 @@ fails; a processor sequence is not a transaction. See the `extensions` module documentation for registration and processor examples. An empty registry uses the ordinary parser path. +For backend-aware parsing through conversion, use converter core's +`pipeline::Pipeline` with an already configured backend. `ExtensionCatalog` +separates named availability from explicit activation and rejects unavailable +selections before parsing. Pipeline parse methods return finalized `ParseResult` +values with structured warnings; conversion prepares fresh display content and +leaves parsed storage unchanged. See the +[converter guide](../converters/README.adoc) and its runnable library example. + ## Parser fixtures We use two fixture styles, and they are intentionally different. diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 4c911d760..d593bde50 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -29,6 +29,37 @@ pub struct RegistryBuilder { } impl RegistryBuilder { + /// Append another immutable registry in its registration order. + /// + /// # Errors + /// Rejects duplicate macro or tree-processor names without changing this builder. + pub fn extend(&mut self, registry: &Registry) -> Result<&mut Self, RegistrationError> { + for descriptor in ®istry.0.macros { + if self.names.contains_key(&descriptor.name) { + return Err(RegistrationError::DuplicateName(descriptor.name.clone())); + } + } + for descriptor in ®istry.0.trees { + if self.trees.iter().any(|entry| entry.name == descriptor.name) { + return Err(RegistrationError::DuplicateTreeProcessor( + descriptor.name.clone(), + )); + } + } + let offset = self.macros.len(); + self.names.extend( + registry + .0 + .macros + .iter() + .enumerate() + .map(|(index, entry)| (entry.name.clone(), offset + index)), + ); + self.macros.extend(registry.0.macros.iter().cloned()); + self.trees.extend(registry.0.trees.iter().cloned()); + Ok(self) + } + /// Register a tree processor after the existing tree processors. /// /// Names match `[A-Za-z][A-Za-z0-9_-]*` and are independent of macro names. @@ -171,6 +202,21 @@ impl Registry { }) } + /// Parse a reader with the same session and source-order contract as [`Self::parse`]. + /// Reader input keeps the ordinary reader attribute and include-origin policy. + /// + /// # Errors + /// Returns input, preprocessing, parsing, or processor errors. + pub fn parse_from_reader( + &self, + reader: R, + options: &Options<'_>, + ) -> Result { + self.parse_using(options, |options, session| { + crate::parse_reader_with_session(reader, options, session) + }) + } + fn parse_using( &self, options: &Options<'_>, diff --git a/acdc-parser/src/lib.rs b/acdc-parser/src/lib.rs index bdad8f3a6..712bec434 100644 --- a/acdc-parser/src/lib.rs +++ b/acdc-parser/src/lib.rs @@ -387,6 +387,31 @@ pub fn parse_from_reader( parse_input(result, options, None, warnings_handle) } +fn parse_reader_with_session( + mut reader: R, + options: &Options<'_>, + session: Option<&mut extensions::Session>, +) -> Result { + let Some(session) = session else { + return parse_from_reader(reader, options); + }; + let mut input = String::new(); + reader.read_to_string(&mut input)?; + let options = options + .clone() + .prepare_for_parse(document_attribute::InputKind::Reader); + let warnings: Rc> = Rc::default(); + if options + .extensions + .as_ref() + .is_some_and(|registry| registry.may_execute(&input)) + { + return parse_ordered_source(&input, options, None, warnings, session); + } + let result = Preprocessor::process(&input, &options, Rc::clone(&warnings))?; + parse_input(result, options, None, warnings) +} + /// Parse `AsciiDoc` content from a string. /// /// The default [`SafeMode::Secure`] turns include directives into links without diff --git a/converters/README.adoc b/converters/README.adoc index 674f715b2..9cf8e5277 100644 --- a/converters/README.adoc +++ b/converters/README.adoc @@ -6,6 +6,45 @@ - `link:./pdf[pdf]` - `AsciiDoc` PDF backend backed by the Rust Typst engine - `link:./terminal[terminal]` - `AsciiDoc` terminal printer backend (à la *nix command `cat`) +== Library processing with extensions + +Configure the backend before parsing and wrap it in +`acdc_converters_core::pipeline::Pipeline`. Its `parse`, `parse_file`, and +`parse_from_reader` methods run the selected macros, ordered tree processors, +and structural finalization. `write_to` and `convert` resolve deferred display +labels before handing the finalized document to the backend. + +`ExtensionCatalog` separates named build availability from explicit activation. +Registering a package invokes no factories. `select` validates all names and +registration conflicts before input processing; packages run in selection order, +preserving their own registration order. Repeated selections count once. Attach +the returned registry with `Pipeline::with_extensions`. An empty selection keeps +the ordinary parser path without extension indexes or retained title snapshots. + +The link:./html/examples/extension_pipeline.rs[extension pipeline example] +registers and selects an application macro, configures HTML, parses, and writes +output while retaining both parser and converter warnings: + +[source,console] +---- +cargo run -p acdc-converters-html --example extension_pipeline --all-features +---- + +Use the parser registry directly when you need a working session for checked +edits. Queries observe repairs when issued again; copied selections remain +snapshots. Document-local handles survive insertion and replacement, and removed +handles cannot select another block. Normalization repeats without callbacks or +renumbering. Finishing consumes the session and rejects unresolved requests; +pipeline parse methods return this finalized, ordinary `ParseResult`. + +Each document gets fresh handlers, including when factories are shared across +parallel callers. Each conversion gets fresh counters and display content while +preserving the parsed document. Custom backends must create their render state +per conversion. A processor failure stops processing; earlier successful edits +and external callback effects remain. Structured parser warnings stay on the +parse result, and conversion warnings stay in `Diagnostics` or `ConversionResult` +until the application presents them. + == Development prerequisites Converter tests are run with `cargo nextest run --all-features`. The terminal diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index e6e84ed4f..b4655a4ff 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Added a shared library pipeline for backend-aware parsing, selected extensions, + finalization, and conversion. Named extensions require explicit activation; + unavailable names fail before parsing. Files, readers, and source strings retain + structured diagnostics and support repeated conversion without changing the + parsed document. Inactive pipelines retain ordinary parsing. + - Added `display::prepare()` for custom converters to resolve extension-generated caption and captured-title labels into ordinary explicit cross-references for each conversion, preserving the shared document and overriding generic `reftext`. diff --git a/converters/core/Cargo.toml b/converters/core/Cargo.toml index 3c30e26f8..71f19f9e0 100644 --- a/converters/core/Cargo.toml +++ b/converters/core/Cargo.toml @@ -20,6 +20,10 @@ rustc-hash.workspace = true thiserror.workspace = true tracing.workspace = true +[dev-dependencies] +serde_json.workspace = true +tempfile.workspace = true + [lints.rust] unreachable_pub = "deny" unsafe_code = "forbid" diff --git a/converters/core/src/lib.rs b/converters/core/src/lib.rs index 98eb88c44..e0349f07f 100644 --- a/converters/core/src/lib.rs +++ b/converters/core/src/lib.rs @@ -55,6 +55,7 @@ mod inline_text; pub mod link; pub mod list; pub mod media; +pub mod pipeline; pub mod section; pub mod substitutions; pub mod table; diff --git a/converters/core/src/pipeline.rs b/converters/core/src/pipeline.rs new file mode 100644 index 000000000..cb2df68a7 --- /dev/null +++ b/converters/core/src/pipeline.rs @@ -0,0 +1,150 @@ +//! Shared processing from configured backend and explicit registrations to output. +//! +//! Construct the backend first so its attributes govern preprocessing. A pipeline +//! with no active registrations calls the ordinary parser directly. Each active +//! parse creates fresh handlers, runs ordered tree processors, and finalizes once. +//! Returned parse results retain structured parser warnings and can be converted +//! repeatedly. Every conversion prepares fresh display content without modifying +//! the shared document. Backends own their per-conversion render state. +//! +//! # Lifecycle and ownership +//! +//! [`ExtensionCatalog`] describes build availability; only selected registrations +//! execute. Selection order determines package order, followed by registration +//! order within each package. Duplicate selections are ignored. Macro callbacks +//! run once at committed source boundaries; tree processors run once after parsing. +//! No handler is shared across documents, even when registry factories are shared. +//! +//! [`Registry`] exposes working sessions for callers that need checked tree edits. +//! Borrowed queries end before editing; query again to observe repairs. Copied +//! selections stay snapshots. Document-local target handles survive insertions and +//! replacement, but removed handles never bind to another block. Normalization is +//! idempotent and never replays callbacks. Finishing consumes the working session, +//! rejects unresolved requests, and binds deferred displays to surviving targets. +//! Pipeline parse methods finish this session before returning a [`ParseResult`]. +//! +//! A processor failure stops the sequence. Individual checked edits are atomic; +//! the sequence and external callback effects are not transactions. Parser warnings +//! stay on the parse result; conversion warnings stay in [`Diagnostics`] or +//! [`ConversionResult`]. The application decides how to present them. +//! +//! Each conversion resolves a fresh display overlay and uses fresh backend counters +//! and traversal state. Shared parsed storage is never mutated. Custom backends +//! must honor this same per-conversion state contract in [`Converter::write_to`]. + +use std::{ + io::{Read, Write}, + path::Path, +}; + +use acdc_parser::{Error, ParseResult, ast::DocumentRef, extensions::Registry}; + +use crate::{ConversionResult, Converter, Diagnostics, display}; + +mod extensions; +pub use extensions::{ExtensionCatalog, ExtensionSelectionError}; + +/// A configured backend and the registrations explicitly active for its documents. +#[derive(Debug)] +pub struct Pipeline { + converter: C, + extensions: Option, +} + +impl Pipeline { + /// Use a configured backend without activating any extensions. + pub const fn new(converter: C) -> Self { + Self { + converter, + extensions: None, + } + } + + /// Activate registrations for subsequent parses. Empty registries keep the direct path. + #[must_use] + pub fn with_extensions(mut self, registrations: Registry) -> Self { + self.extensions = (!registrations.is_empty()).then_some(registrations); + self + } + + /// Read the backend configuration selected before parsing. + #[must_use] + pub const fn converter(&self) -> &C { + &self.converter + } +} + +impl<'options, C: Converter<'options>> Pipeline { + /// Parse and structurally finalize a source string with fresh document-local handlers. + /// + /// # Errors + /// Returns located input, processor, or finalization errors. Earlier external + /// callback effects cannot be rolled back when a later stage fails. + pub fn parse(&self, source: &str) -> Result { + let options = self.converter.parser_options(); + match &self.extensions { + Some(registry) => registry.parse(source, options)?.finish(), + None => acdc_parser::parse(source, options), + } + } + + /// Parse and finalize a file, preserving its path, include policy, and diagnostics. + /// + /// # Errors + /// Returns input, processor, or finalization errors. + pub fn parse_file(&self, path: impl AsRef) -> Result { + let options = self.converter.parser_options(); + match &self.extensions { + Some(registry) => registry.parse_file(path, options)?.finish(), + None => acdc_parser::parse_file(path, options), + } + } + + /// Parse and finalize reader input using the same stages as strings and files. + /// + /// # Errors + /// Returns input, processor, or finalization errors. + pub fn parse_from_reader(&self, reader: impl Read) -> Result { + let options = self.converter.parser_options(); + match &self.extensions { + Some(registry) => registry.parse_from_reader(reader, options)?.finish(), + None => acdc_parser::parse_from_reader(reader, options), + } + } + + /// Resolve display content and write one conversion with structured diagnostics. + /// + /// # Errors + /// Returns display, conversion, or output errors. + pub fn write_to( + &self, + document: DocumentRef<'_>, + writer: impl Write, + source_file: Option<&Path>, + output_path: Option<&Path>, + diagnostics: &mut Diagnostics<'_>, + ) -> Result<(), C::Error> { + let prepared = display::prepare(document)?; + self.converter.write_to( + prepared.document(), + writer, + source_file, + output_path, + diagnostics, + ) + } + + /// Resolve displays and use the backend's configured output destination. + /// Parser warnings remain on the parse result; conversion warnings remain in the return value. + /// + /// # Errors + /// Returns display, conversion, or output errors. + pub fn convert( + &self, + document: DocumentRef<'_>, + source_file: Option<&Path>, + ) -> Result { + let prepared = display::prepare(document)?; + self.converter.convert(prepared.document(), source_file) + } +} diff --git a/converters/core/src/pipeline/extensions.rs b/converters/core/src/pipeline/extensions.rs new file mode 100644 index 000000000..feca45659 --- /dev/null +++ b/converters/core/src/pipeline/extensions.rs @@ -0,0 +1,96 @@ +use std::collections::{BTreeMap, HashSet}; + +use acdc_parser::extensions::{RegistrationError, Registry}; + +/// Available extension registrations. Availability does not activate processors. +#[derive(Clone, Debug, Default)] +pub struct ExtensionCatalog { + available: BTreeMap, +} + +/// Configuration rejected before input processing or handler construction. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[non_exhaustive] +pub enum ExtensionSelectionError { + /// A catalog name does not follow the documented identifier syntax. + #[error("invalid extension name: {0}")] + InvalidName(String), + /// The catalog already contains this name. + #[error("extension `{0}` is already available")] + DuplicateName(String), + /// The selected name was not compiled and registered by the application. + #[error("extension `{0}` is not available in this build")] + Unavailable(String), + /// Selected extension packages conflict in the parser registration namespace. + #[error("could not activate extension `{name}`: {source}")] + Conflict { + /// Extension whose registrations conflict with an earlier selection. + name: String, + /// Rejected macro or tree-processor registration. + #[source] + source: RegistrationError, + }, +} + +impl ExtensionCatalog { + /// Make registrations available under an ASCII `[A-Za-z][A-Za-z0-9_-]*` name. + /// Processor factories are retained without being invoked. + /// + /// # Errors + /// Rejects invalid or duplicate catalog names without changing the catalog. + pub fn register( + &mut self, + name: impl Into, + registrations: Registry, + ) -> Result<(), ExtensionSelectionError> { + let name = name.into(); + let mut bytes = name.bytes(); + if !bytes.next().is_some_and(|byte| byte.is_ascii_alphabetic()) + || !bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + { + return Err(ExtensionSelectionError::InvalidName(name)); + } + if self.available.contains_key(&name) { + return Err(ExtensionSelectionError::DuplicateName(name)); + } + self.available.insert(name, registrations); + Ok(()) + } + + /// Available names in sorted order, independently of activation. + pub fn names(&self) -> impl ExactSizeIterator + '_ { + self.available.keys().map(String::as_str) + } + + /// Activate packages in selection order, preserving each package's registration order. + /// Repeated names are ignored after their first occurrence. No active registrations + /// returns `None`, keeping ordinary parsing free of extension sessions and overlays. + /// + /// # Errors + /// Rejects unavailable names and conflicting registrations before parsing starts. + pub fn select( + &self, + names: impl IntoIterator>, + ) -> Result, ExtensionSelectionError> { + let mut selected = HashSet::new(); + let mut builder = Registry::builder(); + let mut active = false; + for name in names { + let (name, registrations) = self + .available + .get_key_value(name.as_ref()) + .ok_or_else(|| ExtensionSelectionError::Unavailable(name.as_ref().into()))?; + if !selected.insert(name.as_str()) { + continue; + } + builder + .extend(registrations) + .map_err(|source| ExtensionSelectionError::Conflict { + name: name.clone(), + source, + })?; + active |= !registrations.is_empty(); + } + Ok(active.then(|| builder.build())) + } +} diff --git a/converters/core/tests/pipeline.rs b/converters/core/tests/pipeline.rs new file mode 100644 index 000000000..51fea962b --- /dev/null +++ b/converters/core/tests/pipeline.rs @@ -0,0 +1,390 @@ +//! Shared pipeline activation, source processing, and document isolation contracts. + +use std::{ + io::{self, Read, Write}, + path::{Path, PathBuf}, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; + +use acdc_converters_core::{ + BackendProfile, Converter, Diagnostics, Options, + pipeline::{ExtensionCatalog, ExtensionSelectionError, Pipeline}, +}; +use acdc_parser::{ + Error as ParserError, Options as ParserOptions, OptionsBuilder, SafeMode, WarningKind, + ast::DocumentRef, + extensions::{ + BlockBuilder, BlockContext, BlockMacro, BlockMacroOutput, BlockMacroProcessor, + DisplayIntent, DocumentEditor, MacroExecutionContext, MacroInvocation, Registry, + TreeProcessor, TreeProcessorRegistration, + }, +}; + +type TestResult = Result<(), Box>; + +#[derive(Debug, thiserror::Error)] +enum Error { + #[error(transparent)] + Parser(#[from] ParserError), + #[error(transparent)] + Io(#[from] io::Error), + #[error(transparent)] + Json(#[from] serde_json::Error), +} + +struct JsonConverter { + options: Options, + parser_options: ParserOptions<'static>, +} + +impl Converter<'static> for JsonConverter { + type Error = Error; + + fn new(options: Options, parser_options: OptionsBuilder<'static>) -> Result { + Ok(Self { + parser_options: BackendProfile::new("probe", "probe", "json", ".json") + .apply(parser_options, options.doctype(), options.embedded()) + .build()?, + options, + }) + } + fn options(&self) -> &Options { + &self.options + } + fn parser_options(&self) -> &ParserOptions<'static> { + &self.parser_options + } + fn derive_output_path(&self, _: &Path, _: DocumentRef<'_>) -> Result, Error> { + Ok(None) + } + fn name(&self) -> &'static str { + "probe" + } + fn write_to( + &self, + document: DocumentRef<'_>, + writer: W, + _: Option<&Path>, + _: Option<&Path>, + diagnostics: &mut Diagnostics<'_>, + ) -> Result<(), Error> { + if document.attributes().get("render-warning").is_some() { + diagnostics.warn("render warning"); + } + serde_json::to_writer(writer, &document)?; + Ok(()) + } +} + +struct Counter { + calls: usize, +} + +impl BlockMacroProcessor for Counter { + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + context: &mut MacroExecutionContext, + ) -> Result { + self.calls += 1; + assert_eq!( + invocation + .document_attributes + .get("backend") + .and_then(acdc_parser::DocumentAttributeValue::as_str), + Some("probe") + ); + context.set_attribute("produced", "yes"); + Ok(BlockMacroOutput::Paragraph(format!( + "{}:{}", + invocation.target, self.calls + ))) + } +} + +fn catalog(created: &Arc) -> Result> { + let mut builder = Registry::builder(); + let created = Arc::clone(created); + builder.register(BlockMacro::new("count", move || { + created.fetch_add(1, Ordering::SeqCst); + Counter { calls: 0 } + }))?; + let mut catalog = ExtensionCatalog::default(); + catalog.register("counter", builder.build())?; + Ok(catalog) +} + +fn pipeline(registry: Option) -> Result, Error> { + let pipeline = Pipeline::new(JsonConverter::new( + Options::default(), + ParserOptions::builder(), + )?); + Ok(match registry { + Some(registry) => pipeline.with_extensions(registry), + None => pipeline, + }) +} + +fn render( + pipeline: &Pipeline, + document: DocumentRef<'_>, +) -> Result<(serde_json::Value, Vec), Error> { + let mut bytes = Vec::new(); + let mut warnings = Vec::new(); + let source = pipeline.converter().warning_source(); + pipeline.write_to( + document, + &mut bytes, + None, + None, + &mut Diagnostics::new(&source, &mut warnings), + )?; + Ok((serde_json::from_slice(&bytes)?, warnings)) +} + +#[test] +fn pipeline_selection_is_explicit_ordered_and_validated_before_input() -> TestResult { + let created = Arc::new(AtomicUsize::new(0)); + let catalog = catalog(&created)?; + assert_eq!(catalog.names().collect::>(), ["counter"]); + assert!(catalog.select([] as [&str; 0])?.is_none()); + assert!( + matches!(catalog.select(["unknown"]), Err(ExtensionSelectionError::Unavailable(name)) if name == "unknown") + ); + assert_eq!(created.load(Ordering::SeqCst), 0); + let inactive = pipeline(None)?; + let ordinary = inactive.parse("count::idle[]")?; + assert!(!ordinary.document().has_deferred_displays()); + assert!(serde_json::to_string(&ordinary.document())?.contains("count::idle[]")); + assert_eq!(created.load(Ordering::SeqCst), 0); + let active = pipeline(catalog.select(["counter", "counter"])?)?; + let parsed = active.parse("count::first[]\n\ncount::second[]")?; + assert!(parsed.warnings().is_empty(), "{:?}", parsed.warnings()); + assert_eq!(created.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[test] +fn pipeline_files_readers_and_strings_observe_backend_and_source_order() -> TestResult { + let created = Arc::new(AtomicUsize::new(0)); + let pipeline = pipeline(catalog(&created)?.select(["counter"])?)?; + let source = "ifdef::backend-probe[]\ncount::one[]\n\nifdef::produced[]\ncount::two[]\nendif::[]\nendif::[]"; + let directory = tempfile::tempdir()?; + let path = directory.path().join("input.adoc"); + std::fs::write(&path, source)?; + for parsed in [ + pipeline.parse(source)?, + pipeline.parse_from_reader(source.as_bytes())?, + pipeline.parse_file(&path)?, + ] { + let (rendered, warnings) = render(&pipeline, parsed.document())?; + let text = rendered.to_string(); + assert!(text.contains("one:1")); + assert!(text.contains("two:2")); + assert!(!text.contains("count::")); + assert!(warnings.is_empty(), "{warnings:?}"); + } + assert_eq!(created.load(Ordering::SeqCst), 3); + Ok(()) +} + +#[test] +fn pipeline_reader_keeps_include_origin_and_reader_attributes() -> TestResult { + let directory = tempfile::tempdir()?; + std::fs::write(directory.path().join("yes.adoc"), "count::included[]")?; + let created = Arc::new(AtomicUsize::new(0)); + let registry = catalog(&created)?.select(["counter"])?.ok_or("registry")?; + let pipeline = Pipeline::new(JsonConverter::new( + Options::default(), + ParserOptions::builder() + .with_base_dir(directory.path()) + .with_safe_mode(SafeMode::Safe), + )?) + .with_extensions(registry); + let parsed = + pipeline.parse_from_reader("count::first[]\n\ninclude::{produced}.adoc[]".as_bytes())?; + let (rendered, warnings) = render(&pipeline, parsed.document())?; + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(parsed.warnings().is_empty(), "{:?}", parsed.warnings()); + let text = rendered.to_string(); + assert!(text.contains("first:1")); + assert!(text.contains("included:2")); + for name in ["docdir", "docfile", "docfilesuffix", "docname"] { + assert!(parsed.document().attributes().get(name).is_none(), "{name}"); + } + assert_eq!(created.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[test] +fn pipeline_independent_and_parallel_documents_keep_handlers_and_warnings_local() -> TestResult { + let created = Arc::new(AtomicUsize::new(0)); + let catalog = catalog(&created)?; + let pipeline = pipeline(catalog.select(["counter"])?)?; + let first = pipeline.parse(":render-warning:\n\ncount::first[]\n\n<>")?; + assert!(first.warnings().iter().any(|warning| matches!(&warning.kind, WarningKind::UnresolvedReference { target } if target == "missing"))); + let before = serde_json::to_value(first.document())?; + let (one, warnings) = render(&pipeline, first.document())?; + let (two, repeated) = render(&pipeline, first.document())?; + assert_eq!(one, two); + assert_eq!(warnings.len(), 1); + assert_eq!(repeated.len(), 1); + assert_eq!(serde_json::to_value(first.document())?, before); + let clean = pipeline.parse("count::next[]")?; + assert!(clean.warnings().is_empty(), "{:?}", clean.warnings()); + let (rendered, warnings) = render(&pipeline, clean.document())?; + assert!(rendered.to_string().contains("next:1")); + assert!(warnings.is_empty(), "{warnings:?}"); + std::thread::scope(|scope| { + let threads: Vec<_> = (0..3) + .map(|_| { + let catalog = &catalog; + scope.spawn(move || -> Result<(), String> { + let pipeline = + self::pipeline(catalog.select(["counter"]).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + let parsed = pipeline + .parse("count::parallel[]") + .map_err(|e| e.to_string())?; + let (rendered, _) = + render(&pipeline, parsed.document()).map_err(|e| e.to_string())?; + assert!(rendered.to_string().contains("parallel:1")); + Ok(()) + }) + }) + .collect(); + for thread in threads { + thread.join().map_err(|_| "thread panicked")??; + } + Ok::<_, Box>(()) + })?; + assert_eq!(created.load(Ordering::SeqCst), 5); + Ok(()) +} + +struct Capture; +impl TreeProcessor for Capture { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), ParserError> { + let target = editor + .query() + .select(BlockContext::Listing) + .next() + .map(|view| view.target().clone()); + if let Some(target) = target { + let captured = editor.capture(&target)?; + editor.insert_before( + &target, + BlockBuilder::unordered_list([captured.display(DisplayIntent::CaptionAndTitle)]), + )?; + } + Ok(()) + } +} + +#[test] +fn pipeline_finalizes_once_and_prepares_explicit_labels_for_custom_backends() -> TestResult { + let mut builder = Registry::builder(); + builder.register_tree_processor(TreeProcessorRegistration::new("capture", || Capture))?; + let registry = builder.build(); + let pipeline = pipeline(Some(registry.clone()))?; + let mut working = registry.parse( + ":listing-caption: Code\n\n.A *title*\n[#code,reftext=Other]\n----\nbody\n----", + pipeline.converter().parser_options(), + )?; + working.normalize()?; + working.normalize()?; + let parsed = working.finish()?; + assert!(parsed.document().has_deferred_displays()); + let before = serde_json::to_value(parsed.document())?; + let (first, _) = render(&pipeline, parsed.document())?; + let (second, _) = render(&pipeline, parsed.document())?; + assert_eq!(first, second); + assert!(!first.to_string().contains("generated_display")); + assert!(first.to_string().contains("Code 1.")); + assert_eq!(serde_json::to_value(parsed.document())?, before); + Ok(()) +} + +#[test] +fn pipeline_empty_registries_keep_the_direct_path_and_reader_errors() -> TestResult { + struct Broken; + impl Read for Broken { + fn read(&mut self, _: &mut [u8]) -> io::Result { + Err(io::Error::other("reader failed")) + } + } + let pipeline = pipeline(Some(Registry::default()))?; + let parsed = pipeline.parse("Paragraph.")?; + assert!(serde_json::to_string(&parsed.document())?.contains("Paragraph.")); + assert!(pipeline.parse_from_reader(Broken).is_err()); + Ok(()) +} + +#[test] +fn pipeline_registry_composition_rejects_conflicts_atomically() -> TestResult { + let created = Arc::new(AtomicUsize::new(0)); + let mut catalog = catalog(&created)?; + assert!(matches!( + catalog.register("counter", Registry::default()), + Err(ExtensionSelectionError::DuplicateName(_)) + )); + assert!(matches!( + catalog.register("invalid name", Registry::default()), + Err(ExtensionSelectionError::InvalidName(_)) + )); + let original = catalog.select(["counter"])?.ok_or("active registry")?; + let mut incoming = Registry::builder(); + incoming.register(BlockMacro::new("fresh", || Counter { calls: 0 }))?; + incoming.extend(&original)?; + let incoming = incoming.build(); + catalog.register("conflict", incoming.clone())?; + assert!(matches!( + catalog.select(["counter", "conflict"]), + Err(ExtensionSelectionError::Conflict { .. }) + )); + assert_eq!(created.load(Ordering::SeqCst), 0); + let mut builder = Registry::builder(); + builder.extend(&original)?; + assert!(builder.extend(&incoming).is_err()); + let pipeline = pipeline(Some(builder.build()))?; + let parsed = pipeline.parse("count::one[]\n\nfresh::idle[]")?; + let rendered = render(&pipeline, parsed.document())?.0.to_string(); + assert!(rendered.contains("one:1")); + assert!(rendered.contains("fresh::idle[]")); + Ok(()) +} + +struct Replace(&'static str); +impl TreeProcessor for Replace { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), ParserError> { + let target = editor + .query() + .blocks() + .next() + .map(|view| view.target().clone()); + if let Some(target) = target { + editor.replace_block(&target, BlockBuilder::paragraph(self.0))?; + } + Ok(()) + } +} + +#[test] +fn pipeline_selection_order_controls_processor_order() -> TestResult { + let mut catalog = ExtensionCatalog::default(); + for name in ["first", "second"] { + let mut builder = Registry::builder(); + builder + .register_tree_processor(TreeProcessorRegistration::new(name, move || Replace(name)))?; + catalog.register(name, builder.build())?; + } + let pipeline = pipeline(catalog.select(["second", "first"])?)?; + let parsed = pipeline.parse("Original.")?; + let text = render(&pipeline, parsed.document())?.0.to_string(); + assert!(text.contains("first")); + assert!(!text.contains("second")); + Ok(()) +} diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index dc3e9b213..300dd5aab 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Reusing a converter for the same document or independent documents now produces + stable index anchors and catalog links, with numbering restarted per conversion. + - Extension-generated caption and captured-title links now use explicit labels, preserving title formatting and source attributes while following final captions and renamed targets. Repeated conversion preserves the shared parsed document. diff --git a/converters/html/examples/extension_pipeline.rs b/converters/html/examples/extension_pipeline.rs new file mode 100644 index 000000000..86b9f972f --- /dev/null +++ b/converters/html/examples/extension_pipeline.rs @@ -0,0 +1,63 @@ +//! An application makes registrations available, selects them, then parses and converts. + +use std::error::Error; + +use acdc_converters_core::{ + Converter as _, Diagnostics, Options, + pipeline::{ExtensionCatalog, Pipeline}, +}; +use acdc_converters_html::Converter; +use acdc_parser::{ + Options as ParserOptions, + extensions::{ + BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroExecutionContext, MacroInvocation, + Registry, + }, +}; + +struct Greeting; + +impl BlockMacroProcessor for Greeting { + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + _: &mut MacroExecutionContext, + ) -> Result { + Ok(BlockMacroOutput::Paragraph(format!( + "Hello, {}!", + invocation.target + ))) + } +} + +fn main() -> Result<(), Box> { + let mut registrations = Registry::builder(); + registrations.register(BlockMacro::new("greet", || Greeting))?; + let mut available = ExtensionCatalog::default(); + available.register("greetings", registrations.build())?; + + // Availability alone does not activate a package or invoke its factories. + let selected = available.select(["greetings"])?.ok_or("empty selection")?; + let pipeline = Pipeline::new(Converter::new( + Options::builder().embedded(true).build(), + ParserOptions::builder(), + )?) + .with_extensions(selected); + let parsed = pipeline.parse("ifdef::backend-html5[]\ngreet::World[]\nendif::[]")?; + for warning in parsed.warnings() { + eprintln!("{warning}"); + } + let source = pipeline.converter().warning_source(); + let mut warnings = Vec::new(); + pipeline.write_to( + parsed.document(), + std::io::stdout().lock(), + None, + None, + &mut Diagnostics::new(&source, &mut warnings), + )?; + for warning in warnings { + eprintln!("{warning}"); + } + Ok(()) +} diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index 4bfa7ee5f..d254917d0 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -303,8 +303,8 @@ impl<'a> Converter<'a> { listing_counter: Rc::new(Cell::new( document.highest_caption_number(CaptionKind::Listing), )), - index_term_counter: self.index_term_counter.clone(), - index_catalog_counter: self.index_catalog_counter.clone(), + index_term_counter: Rc::new(Cell::new(0)), + index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(RefCell::new(Vec::new())), variant: self.variant, }; diff --git a/converters/html/tests/pipeline.rs b/converters/html/tests/pipeline.rs new file mode 100644 index 000000000..47ed798c2 --- /dev/null +++ b/converters/html/tests/pipeline.rs @@ -0,0 +1,46 @@ +//! A reusable backend starts each pipeline conversion with fresh render state. + +use acdc_converters_core::{Converter as _, Diagnostics, Options, pipeline::Pipeline}; +use acdc_converters_html::{Converter, HtmlVariant}; +use acdc_parser::{Document, Options as ParserOptions}; + +#[test] +fn pipeline_repeated_html_conversions_start_fresh_index_counters() +-> Result<(), Box> { + for variant in [HtmlVariant::Standard, HtmlVariant::Semantic] { + let pipeline = Pipeline::new(Converter::new_with_variant( + Options::builder().embedded(true).build(), + ParserOptions::builder(), + variant, + )?); + let source = "= Document\n:acdc-index:\n\n((Term)). indexterm:[Alias,see=Term]\n\n[index]\n== Index\n\n[index]\n== Another Index"; + let parsed = pipeline.parse(source)?; + let original = Document::from(parsed.document()); + let mut outputs = Vec::new(); + for document in [ + parsed.document(), + parsed.document(), + pipeline.parse(source)?.document(), + ] { + let mut output = Vec::new(); + let mut warnings = Vec::new(); + let warning_source = pipeline.converter().warning_source(); + pipeline.write_to( + document, + &mut output, + None, + None, + &mut Diagnostics::new(&warning_source, &mut warnings), + )?; + assert!(warnings.is_empty(), "{warnings:?}"); + outputs.push(String::from_utf8(output)?); + } + let first = outputs.first().ok_or("missing output")?; + assert!(first.contains("id=\"_indexterm_0\"")); + for output in &outputs { + assert_eq!(first, output); + } + assert_eq!(Document::from(parsed.document()), original); + } + Ok(()) +} From 4b0ee7fbed4a6ece46d8da6aff84681543238026 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 15 Nov 2026 22:58:08 +0100 Subject: [PATCH 20/55] feat(cli): use the shared extension pipeline for conversion Select named extension packages explicitly and reject unavailable names before reading input. Route files, stdin, batches, terminal output, and pagers through the backend-aware library pipeline while preserving warning presentation and output options. Use injected registrations for route and isolation tests, keeping the production catalog empty until an extension package is available. SC-540 --- ARCHITECTURE.adoc | 37 ++- acdc-cli/CHANGELOG.md | 5 + acdc-cli/README.adoc | 15 ++ acdc-cli/src/subcommands/convert.rs | 174 +++++++++---- .../src/subcommands/convert/pipeline_tests.rs | 236 ++++++++++++++++++ 5 files changed, 418 insertions(+), 49 deletions(-) create mode 100644 acdc-cli/src/subcommands/convert/pipeline_tests.rs diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc index 1558ebfe4..dc6ac1d35 100644 --- a/ARCHITECTURE.adoc +++ b/ARCHITECTURE.adoc @@ -90,8 +90,9 @@ It handles document structure (header, sections, blocks), block-level elements ( The parser owns an optional registry of block-macro descriptors and factories. Recognition records invocations and their source-position attributes without -calling extension code. Once the complete document is accepted, the host runs -macros once in document order, then repairs prepared captions and catalogs. +calling extension code during speculative grammar matching. The host runs macros +once at committed block boundaries in source order, applying requested attribute +changes before later conditionals and includes, then repairs captions and catalogs. Tree processors run once in registration order through a scoped editor. Queries return the same typed views as ordinary parser consumers, plus stable @@ -102,8 +103,36 @@ generated text; builders do not reparse it or store backend markup. The working session retains deferred requests and document-local processors. Its checked `finish()` operation rejects unresolved requests and returns the ordinary `ParseResult` for conversion. Registrations are explicit, and an empty -registry retains the ordinary parsing path. Callbacks cannot change source -processing, includes, or conditionals. +registry retains the ordinary parsing path. Callback attribute changes follow +the same assignment, locking, and nested-document policies as authored content. + +`acdc-converters-core::pipeline` provides the shared library and CLI orchestration. +The backend is configured before parsing so its attributes govern source +processing. An `ExtensionCatalog` lists packages available in the application; +explicit selection activates them and rejects unavailable names before reading +input. Selected packages preserve selection order and their registration order. +The production CLI registers no extension packages yet. + +`Pipeline` coordinates parser-owned source processing, committed callbacks, +tree processors, and finalization for strings, files, and readers. Conversion +prepares deferred display content through the shared display service before +calling the backend. CLI batches, stdin, terminal output, and pagers use these +same entry points. Inactive pipelines call the ordinary parser directly. + +Working sessions permit checked edits through document-local handles. Borrowed +queries end before edits; fresh queries observe repaired catalogs and copied +selections remain snapshots. Surviving handles retain identity across insertions +and replacement; removed handles never bind to another block. `normalize()` is +idempotent without callbacks. `finish()` consumes the session, binds displays to +surviving targets, and rejects unresolved requests. Pipeline parsing returns only +the finalized `ParseResult`. + +Factories may be shared; mutable handlers belong to each document. Each render +creates fresh counters, traversal state, and display overlays without mutating +parsed storage. Parser and converter warnings remain structured until presented +by the caller. Processor errors stop later work. Checked edits are atomic, but +earlier successful edits and external callback effects cannot be rolled back as +a sequence. ==== Inline preprocessing diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index e19eb051c..de1412ec4 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Conversion accepts repeatable `--extension NAME` selections and rejects + unavailable packages before reading input. All input and output routes share + the backend-aware library pipeline. No extension packages ship in the current + binary, and ordinary conversion keeps its existing defaults. + - Conversion continues after recoverable parser errors and reports structured warnings, including non-conforming manpage titles. `convert --fail-on-warnings` retains successful output, processes the remaining selected inputs, and exits diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index 174fc9708..ee290a0b5 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -121,6 +121,21 @@ Supported backends depend on the features used to build the binary: `--backend html5s` remains an alias for `--backend html --variant semantic`. +==== Extension selection + +`--extension NAME` explicitly selects a named extension package registered by the +application. Repeat the option to select multiple packages in execution order; +duplicate selections count once. Compiling or registering a package does not +activate it. Unknown or unavailable names fail before input is read or parsed. +The current production binary registers no extension packages, so every name is +unavailable until a package is added. + +Files, stdin, batches, terminal output, and pager output use the same pipeline. +The selected backend supplies attributes before preprocessing, and every document +gets fresh extension handlers. Library callers use +`acdc_converters_core::pipeline::Pipeline` and `ExtensionCatalog` for the same +behavior; see link:../converters/README.adoc[the converter guide]. + ==== Input and output Without `--out-file`, file input produces a backend-specific path next to each input. diff --git a/acdc-cli/src/subcommands/convert.rs b/acdc-cli/src/subcommands/convert.rs index 876c6f42d..49e7d7135 100644 --- a/acdc-cli/src/subcommands/convert.rs +++ b/acdc-cli/src/subcommands/convert.rs @@ -8,8 +8,17 @@ use std::{ time::{Duration, Instant}, }; +#[cfg(any( + test, + feature = "manpage", + feature = "markdown", + feature = "pdf", + feature = "terminal" +))] +use acdc_converters_core::Converter as _; use acdc_converters_core::{ - ConversionResult, Converter as _, Doctype, GeneratorMetadata, Options, OutputDestination, + ConversionResult, Doctype, GeneratorMetadata, Options, OutputDestination, + pipeline::{ExtensionCatalog, Pipeline}, }; #[cfg(feature = "html")] use acdc_converters_html::HtmlVariant; @@ -21,7 +30,7 @@ use acdc_converters_pdf::{PageOrientation, PageSize, PdfOptions, ThemeFormat}; use acdc_converters_terminal::Error as TerminalError; use acdc_parser::{ AttributeValue, Options as ParserOptions, OptionsBuilder, ParseResult, SafeMode, Warning, - parse_file, + extensions::Registry, }; use clap::{ArgAction, Args as ClapArgs, ValueEnum}; @@ -34,6 +43,10 @@ use crate::{ type RawAttributes<'a> = std::collections::HashMap, AttributeValue<'a>>; +#[cfg(test)] +#[path = "convert/pipeline_tests.rs"] +mod pipeline_tests; + /// Convert `AsciiDoc` documents to various output formats #[derive(ClapArgs, Debug)] #[cfg_attr(feature = "pdf", command(group(clap::ArgGroup::new("theme_or_export").args(["theme", "emit_theme_config"]).multiple(true))))] @@ -59,6 +72,10 @@ pub(crate) struct Args { #[arg(conflicts_with = "stdin", required_unless_present = "stdin")] files: Vec, + /// Enable a compiled extension for each document (repeatable) + #[arg(long = "extension", value_name = "NAME", action = ArgAction::Append)] + extensions: Vec, + /// Backend output format /// /// `html` is the default when its feature is compiled in; otherwise @@ -275,11 +292,19 @@ impl Args { } pub(crate) fn run(args: &Args) -> MietteResult<()> { + run_with_extensions(args, &ExtensionCatalog::default()) +} + +fn run_with_extensions(args: &Args, available: &ExtensionCatalog) -> MietteResult<()> { #[cfg(any(feature = "html", feature = "markdown"))] let backend = args.backend.resolve(args.variant)?; #[cfg(not(any(feature = "html", feature = "markdown")))] let backend = args.backend.resolve(); + let extensions = available + .select(&args.extensions) + .map_err(|error| error::display(&error))?; + #[cfg(feature = "pdf")] validate_pdf_options(args, backend)?; @@ -310,6 +335,7 @@ pub(crate) fn run(args: &Args) -> MietteResult<()> { args, &options, document_attributes, + extensions.as_ref(), move |opts, attrs| { acdc_converters_html::Converter::new_with_variant(opts, attrs, variant) }, @@ -318,7 +344,7 @@ pub(crate) fn run(args: &Args) -> MietteResult<()> { #[cfg(feature = "terminal")] Backend::Terminal => { // Terminal outputs to stdout with optional pager support - run_terminal_with_pager(args, &options, document_attributes) + run_terminal_with_pager(args, &options, document_attributes, extensions.as_ref()) .map_err(|e| error::display(&e)) } @@ -327,6 +353,7 @@ pub(crate) fn run(args: &Args) -> MietteResult<()> { args, &options, document_attributes, + extensions.as_ref(), acdc_converters_manpage::Converter::new, ), @@ -335,6 +362,7 @@ pub(crate) fn run(args: &Args) -> MietteResult<()> { args, &options, document_attributes, + extensions.as_ref(), move |opts, attrs| { acdc_converters_markdown::Converter::new(opts, attrs) .map(|converter| converter.with_variant(variant)) @@ -348,6 +376,7 @@ pub(crate) fn run(args: &Args) -> MietteResult<()> { args, &options, document_attributes, + extensions.as_ref(), move |opts, attrs| { acdc_converters_pdf::Converter::new(opts, attrs) .map(|converter| converter.with_pdf_options(pdf_options.clone())) @@ -505,6 +534,14 @@ fn selected_input_files(args: &Args) -> &[PathBuf] { } } +fn configure_pipeline

(converter: P, extensions: Option<&Registry>) -> Pipeline

{ + let pipeline = Pipeline::new(converter); + match extensions { + Some(registrations) => pipeline.with_extensions(registrations.clone()), + None => pipeline, + } +} + /// Run a converter against the inputs. The factory supplies backend-specific /// settings, such as HTML or Markdown variants. #[tracing::instrument(skip(base_options, document_attributes, make_converter))] @@ -512,6 +549,7 @@ fn run_converter( args: &Args, base_options: &Options, document_attributes: OptionsBuilder<'static>, + extensions: Option<&Registry>, make_converter: F, ) -> MietteResult where @@ -521,22 +559,14 @@ where { // Handle stdin separately (no parallelization) if args.stdin { - let converter = make_converter(base_options.clone(), document_attributes) - .map_err(|e| error::display(&e))?; - let parser_options = converter.parser_options(); + let converter = configure_pipeline( + make_converter(base_options.clone(), document_attributes) + .map_err(|e| error::display(&e))?, + extensions, + ); let stdin = std::io::stdin(); let mut reader = BufReader::new(stdin.lock()); - let parsed = acdc_parser::parse_from_reader(&mut reader, parser_options) - .map_err(|error| error::display(&error))?; - let mut summary = ConversionSummary { - warning_count: parsed.warnings().render(WarningRenderContext::new()), - ..ConversionSummary::default() - }; - let result = converter - .convert(parsed.document(), None) - .map_err(|error| error::display(&error))?; - summary.record(result, WarningRenderContext::new()); - return Ok(summary); + return convert_reader(&converter, &mut reader); } // When --out-file is specified with multiple files, only process the first file @@ -545,12 +575,14 @@ where // Single-file fast path: skip rayon thread pool overhead entirely if let [file] = files_to_process { - let converter = make_converter(base_options.clone(), document_attributes) - .map_err(|e| error::display(&e))?; - let parser_options = converter.parser_options(); + let converter = configure_pipeline( + make_converter(base_options.clone(), document_attributes) + .map_err(|e| error::display(&e))?, + extensions, + ); let parse_result = if base_options.timings() { let now = Instant::now(); - let result = parse_file(file, parser_options); + let result = converter.parse_file(file); let elapsed = now.elapsed(); if result.is_ok() { use acdc_converters_core::PrettyDuration; @@ -558,7 +590,7 @@ where } result } else { - parse_file(file, parser_options) + converter.parse_file(file) }; let mut parser_warning_count = 0; let parse_result = parse_result.map(|mut parsed| { @@ -581,14 +613,38 @@ where base_options, &document_attributes, files_to_process, + extensions, make_converter, ) } +fn convert_reader

( + converter: &Pipeline

, + reader: impl std::io::Read, +) -> MietteResult +where + P: acdc_converters_core::Converter<'static>, + P::Error: 'static, +{ + let parsed = converter + .parse_from_reader(reader) + .map_err(|error| error::display(&error))?; + let mut summary = ConversionSummary { + warning_count: parsed.warnings().render(WarningRenderContext::new()), + ..ConversionSummary::default() + }; + let result = converter + .convert(parsed.document(), None) + .map_err(|error| error::display(&error))?; + summary.record(result, WarningRenderContext::new()); + Ok(summary) +} + fn run_multi_file( base_options: &Options, document_attributes: &OptionsBuilder<'static>, files_to_process: &[PathBuf], + extensions: Option<&Registry>, make_converter: F, ) -> MietteResult where @@ -621,14 +677,16 @@ where let file_results: Vec> = files_to_process .par_iter() .map(|file| -> Result<_, P::Error> { - let converter = make_converter(converter_options.clone(), document_attributes.clone())?; - let parser_options = converter.parser_options(); + let converter = configure_pipeline( + make_converter(converter_options.clone(), document_attributes.clone())?, + extensions, + ); let entry = if show_timings { let now = Instant::now(); - let result = parse_file(file, parser_options); + let result = converter.parse_file(file); (file.clone(), result, Some(now.elapsed())) } else { - let result = parse_file(file, parser_options); + let result = converter.parse_file(file); (file.clone(), result, None) }; Ok(convert_parse_result(entry, &converter, show_timings)) @@ -650,7 +708,7 @@ where fn convert_parse_result

( (file, parse_result, parse_dur): TimedParseResult, - converter: &P, + converter: &Pipeline

, show_timings: bool, ) -> FileResult where @@ -1043,8 +1101,10 @@ mod tests { .safe_mode(SafeMode::Unsafe) .output_destination(OutputDestination::Stdout) .build(); - let converter = - acdc_converters_terminal::Converter::new(options.clone(), ParserOptions::builder())?; + let converter = Pipeline::new(acdc_converters_terminal::Converter::new( + options.clone(), + ParserOptions::builder(), + )?); let pager = Command::new("/bin/sh") .args([ "-c", @@ -1236,12 +1296,12 @@ fn spawn_pager(no_pager: bool) -> Option { #[cfg(feature = "terminal")] fn parse_terminal_file( base_options: &Options, - parser_options: &ParserOptions<'static>, + converter: &Pipeline>, file: &Path, ) -> Result { if base_options.timings() { let now = Instant::now(); - let result = parse_file(file, parser_options); + let result = converter.parse_file(file); if result.is_ok() { use acdc_converters_core::PrettyDuration; eprintln!( @@ -1252,7 +1312,7 @@ fn parse_terminal_file( } result } else { - parse_file(file, parser_options) + converter.parse_file(file) } } @@ -1262,28 +1322,42 @@ fn run_terminal_stdin( args: &Args, base_options: &Options, document_attributes: OptionsBuilder<'static>, + extensions: Option<&Registry>, output_to_file: bool, ) -> Result { - use std::io::BufWriter; - use acdc_converters_terminal::Converter; - let converter = Converter::new(base_options.clone(), document_attributes)?; - let parser_options = converter.parser_options(); + let converter = configure_pipeline( + Converter::new(base_options.clone(), document_attributes)?, + extensions, + ); let stdin = std::io::stdin(); let mut reader = BufReader::new(stdin.lock()); - let parsed = acdc_parser::parse_from_reader(&mut reader, parser_options)?; + run_terminal_reader(&converter, &mut reader, || { + spawn_pager(args.no_pager || output_to_file) + }) +} + +#[cfg(feature = "terminal")] +fn run_terminal_reader( + converter: &Pipeline>, + reader: impl std::io::Read, + pager: impl FnOnce() -> Option, +) -> Result { + use std::io::BufWriter; + + let parsed = converter.parse_from_reader(reader)?; // Try pager. The pager's screen takeover would visually bury anything we // eprintln! before it exits, so we drain warnings up front and print them // after pager.wait(). - if let Some(mut pager) = spawn_pager(args.no_pager || output_to_file) { + if let Some(mut pager) = pager() { let mut parsed = parsed; let parser_warnings = parsed.take_warnings(); let mut converter_warnings = Vec::new(); if let Some(pager_stdin) = pager.stdin.take() { let writer = BufWriter::new(pager_stdin); - let source = converter.warning_source(); + let source = converter.converter().warning_source(); let mut diagnostics = acdc_converters_core::Diagnostics::new(&source, &mut converter_warnings); converter.write_to(parsed.document(), writer, None, None, &mut diagnostics)?; @@ -1313,7 +1387,7 @@ fn run_terminal_stdin( /// so they remain visible. #[cfg(feature = "terminal")] fn run_terminal_through_pager( - converter: &acdc_converters_terminal::Converter<'static>, + converter: &Pipeline>, base_options: &Options, files: &[PathBuf], mut pager: std::process::Child, @@ -1324,11 +1398,11 @@ fn run_terminal_through_pager( let mut converter_warnings = Vec::new(); if let Some(pager_stdin) = pager.stdin.take() { let mut writer = BufWriter::new(pager_stdin); - let source = converter.warning_source(); + let source = converter.converter().warning_source(); let mut diagnostics = acdc_converters_core::Diagnostics::new(&source, &mut converter_warnings); for file in files { - let mut parsed = parse_terminal_file(base_options, converter.parser_options(), file)?; + let mut parsed = parse_terminal_file(base_options, converter, file)?; let parser_warnings = parsed.take_warnings(); converter.write_to(parsed.document(), &mut writer, None, None, &mut diagnostics)?; // `parsed` drops here — output is already buffered into `writer`. @@ -1351,6 +1425,7 @@ fn run_terminal_with_pager( args: &Args, base_options: &Options, document_attributes: OptionsBuilder<'static>, + extensions: Option<&Registry>, ) -> Result { use acdc_converters_terminal::Converter; @@ -1362,11 +1437,20 @@ fn run_terminal_with_pager( ); if args.stdin { - return run_terminal_stdin(args, base_options, document_attributes, output_to_file); + return run_terminal_stdin( + args, + base_options, + document_attributes, + extensions, + output_to_file, + ); } let files_to_process = selected_input_files(args); - let converter = Converter::new(base_options.clone(), document_attributes)?; + let converter = configure_pipeline( + Converter::new(base_options.clone(), document_attributes)?, + extensions, + ); let mut summary = ConversionSummary::default(); // Try to spawn pager. @@ -1375,7 +1459,7 @@ fn run_terminal_with_pager( run_terminal_through_pager(&converter, base_options, files_to_process, pager)?; } else { for file in files_to_process { - let parsed = parse_terminal_file(base_options, converter.parser_options(), file)?; + let parsed = parse_terminal_file(base_options, &converter, file)?; summary.warning_count += parsed .warnings() .render(WarningRenderContext::new().with_file(file)); diff --git a/acdc-cli/src/subcommands/convert/pipeline_tests.rs b/acdc-cli/src/subcommands/convert/pipeline_tests.rs new file mode 100644 index 000000000..e2c6fbadf --- /dev/null +++ b/acdc-cli/src/subcommands/convert/pipeline_tests.rs @@ -0,0 +1,236 @@ +use std::{ + cell::Cell, + error::Error, + ffi::OsString, + rc::Rc, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; + +use acdc_parser::extensions::{ + BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroExecutionContext, MacroInvocation, +}; +use clap::{Parser, ValueEnum}; + +use super::*; + +type TestResult = Result<(), Box>; + +#[derive(Parser)] +struct TestArgs { + #[command(flatten)] + args: Args, +} + +fn args(values: impl IntoIterator) -> Result { + TestArgs::try_parse_from(std::iter::once(OsString::from("convert")).chain(values)) + .map(|parsed| parsed.args) +} + +struct Probe { + calls: Rc>, +} + +impl BlockMacroProcessor for Probe { + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + context: &mut MacroExecutionContext, + ) -> Result { + let backend = invocation + .document_attributes + .get("backend") + .and_then(acdc_parser::DocumentAttributeValue::as_str) + .ok_or("backend was not selected before processing")?; + self.calls.set(self.calls.get() + 1); + context.set_attribute("ready", "yes"); + Ok(BlockMacroOutput::Paragraph(format!( + "{backend}:{}:{}", + invocation.target, + self.calls.get() + ))) + } +} + +fn available(created: &Arc) -> Result> { + let created = Arc::clone(created); + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("probe", move || { + created.fetch_add(1, Ordering::SeqCst); + Probe { + calls: Rc::new(Cell::new(0)), + } + }))?; + let mut catalog = ExtensionCatalog::default(); + catalog.register("probe", builder.build())?; + Ok(catalog) +} + +#[test] +fn pipeline_cli_rejects_unavailable_selections_before_files_or_stdin() -> TestResult { + let backend = BackendArg::value_variants() + .first() + .and_then(ValueEnum::to_possible_value) + .ok_or("backend")?; + let created = Arc::new(AtomicUsize::new(0)); + let available = available(&created)?; + for input in ["--stdin", "missing-input.adoc"] { + let args = args( + [ + "--backend", + backend.get_name(), + "--extension", + "probe", + "--extension", + "missing", + input, + ] + .map(OsString::from), + )?; + let error = run_with_extensions(&args, &available) + .err() + .ok_or("unavailable selection")?; + assert!( + error + .to_string() + .contains("extension `missing` is not available") + ); + } + assert_eq!(created.load(Ordering::SeqCst), 0); + Ok(()) +} + +#[cfg(feature = "html")] +#[test] +fn pipeline_cli_files_and_batches_require_explicit_activation() -> TestResult { + let directory = tempfile::tempdir()?; + let first = directory.path().join("first.adoc"); + let second = directory.path().join("second.adoc"); + std::fs::write( + &first, + "ifdef::backend-html5[]\nprobe::first[]\n\nifdef::ready[]\nprobe::later[]\nendif::[]\nendif::[]", + )?; + std::fs::write(&second, "probe::second[]")?; + let created = Arc::new(AtomicUsize::new(0)); + let available = available(&created)?; + let inactive = args([ + OsString::from("--backend"), + OsString::from("html"), + first.as_os_str().to_owned(), + ])?; + run_with_extensions(&inactive, &available).map_err(|error| error.to_string())?; + assert_eq!(created.load(Ordering::SeqCst), 0); + assert!(std::fs::read_to_string(first.with_extension("html"))?.contains("probe::first[]")); + let active = args([ + OsString::from("--backend"), + OsString::from("html"), + OsString::from("--extension"), + OsString::from("probe"), + first.as_os_str().to_owned(), + second.as_os_str().to_owned(), + ])?; + run_with_extensions(&active, &available).map_err(|error| error.to_string())?; + assert_eq!(created.load(Ordering::SeqCst), 2); + let rendered = std::fs::read_to_string(first.with_extension("html"))?; + assert!(rendered.contains("html5:first:1")); + assert!(rendered.contains("html5:later:2")); + assert!(std::fs::read_to_string(second.with_extension("html"))?.contains("html5:second:1")); + Ok(()) +} + +#[cfg(feature = "html")] +#[test] +fn pipeline_cli_reader_uses_selected_registrations_and_backend_options() -> TestResult { + let directory = tempfile::tempdir()?; + let output = directory.path().join("reader.html"); + let created = Arc::new(AtomicUsize::new(0)); + let available = available(&created)?; + let selected = available.select(["probe"])?; + let converter = configure_pipeline( + acdc_converters_html::Converter::new( + Options::builder() + .embedded(true) + .output_destination(OutputDestination::File(output.clone())) + .build(), + ParserOptions::builder(), + )?, + selected.as_ref(), + ); + let summary = convert_reader( + &converter, + "probe::reader[]\n\nifdef::ready[]\nprobe::later[]\nendif::[]".as_bytes(), + ) + .map_err(|error| error.to_string())?; + assert_eq!(summary.warning_count, 0); + let rendered = std::fs::read_to_string(output)?; + assert!(rendered.contains("html5:reader:1")); + assert!(rendered.contains("html5:later:2")); + assert!(!rendered.contains(" std::io::Result { + use std::process::{Command, Stdio}; + Command::new("/bin/sh") + .args(["-c", "cat > \"$1\"", "pager"]) + .arg(path) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .spawn() +} + +#[cfg(all(feature = "terminal", unix))] +#[test] +fn pipeline_cli_terminal_reader_files_and_pager_share_processing() -> TestResult { + let directory = tempfile::tempdir()?; + let input = directory.path().join("input.adoc"); + let file_output = directory.path().join("file.txt"); + let reader_output = directory.path().join("reader.txt"); + let pager_output = directory.path().join("pager.txt"); + std::fs::write(&input, "probe::file[]")?; + let created = Arc::new(AtomicUsize::new(0)); + let available = available(&created)?; + let selection = available.select(["probe"])?; + let args = args([ + OsString::from("--backend"), + OsString::from("terminal"), + OsString::from("--no-pager"), + OsString::from("--extension"), + OsString::from("probe"), + OsString::from("-o"), + file_output.as_os_str().to_owned(), + input.as_os_str().to_owned(), + ])?; + run_with_extensions(&args, &available).map_err(|error| error.to_string())?; + assert!(std::fs::read_to_string(file_output)?.contains("file:1")); + let options = Options::builder() + .output_destination(OutputDestination::File(reader_output.clone())) + .build(); + let converter = configure_pipeline( + acdc_converters_terminal::Converter::new(options.clone(), ParserOptions::builder())?, + selection.as_ref(), + ); + let summary = run_terminal_reader(&converter, "probe::reader[]".as_bytes(), || None)?; + assert_eq!(summary.warning_count, 0); + assert!(std::fs::read_to_string(reader_output)?.contains("reader:1")); + let child = pager(&pager_output)?; + let summary = run_terminal_reader( + &converter, + "probe::pager[]\n\n<>".as_bytes(), + || Some(child), + )?; + assert_eq!(summary.warning_count, 1); + assert!(std::fs::read_to_string(&pager_output)?.contains("pager:1")); + let child = pager(&pager_output)?; + assert_eq!( + run_terminal_through_pager(&converter, &options, &[input], child)?, + 0 + ); + assert!(std::fs::read_to_string(pager_output)?.contains("file:1")); + assert_eq!(created.load(Ordering::SeqCst), 4); + Ok(()) +} From cf83169bc3b40352616fedeb7898487fb4388bb4 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Mon, 16 Nov 2026 11:16:43 +0100 Subject: [PATCH 21/55] feat(converters): register native block renderer sessions Combine parser and renderer registrations in explicit extension selections. Add backend-filtered factories, conversion-local sessions, and rendering host contracts. Carry selected registrations through the generic converter pipeline and adapt CLI types while preserving existing rendering defaults. SC-541 --- acdc-cli/src/subcommands/convert.rs | 13 +- .../src/subcommands/convert/pipeline_tests.rs | 1 + acdc-parser/README.adoc | 5 +- acdc-parser/README.md | 5 +- converters/README.adoc | 3 +- converters/core/CHANGELOG.md | 7 + converters/core/src/lib.rs | 18 +++ converters/core/src/pipeline.rs | 80 ++++++++-- converters/core/src/pipeline/extensions.rs | 34 +++-- converters/core/src/pipeline/registrations.rs | 54 +++++++ converters/core/src/render.rs | 142 ++++++++++++++++++ converters/core/tests/pipeline.rs | 59 +++++++- 12 files changed, 379 insertions(+), 42 deletions(-) create mode 100644 converters/core/src/pipeline/registrations.rs create mode 100644 converters/core/src/render.rs diff --git a/acdc-cli/src/subcommands/convert.rs b/acdc-cli/src/subcommands/convert.rs index 49e7d7135..b75020fff 100644 --- a/acdc-cli/src/subcommands/convert.rs +++ b/acdc-cli/src/subcommands/convert.rs @@ -18,7 +18,7 @@ use std::{ use acdc_converters_core::Converter as _; use acdc_converters_core::{ ConversionResult, Doctype, GeneratorMetadata, Options, OutputDestination, - pipeline::{ExtensionCatalog, Pipeline}, + pipeline::{ExtensionCatalog, Extensions, Pipeline}, }; #[cfg(feature = "html")] use acdc_converters_html::HtmlVariant; @@ -30,7 +30,6 @@ use acdc_converters_pdf::{PageOrientation, PageSize, PdfOptions, ThemeFormat}; use acdc_converters_terminal::Error as TerminalError; use acdc_parser::{ AttributeValue, Options as ParserOptions, OptionsBuilder, ParseResult, SafeMode, Warning, - extensions::Registry, }; use clap::{ArgAction, Args as ClapArgs, ValueEnum}; @@ -534,7 +533,7 @@ fn selected_input_files(args: &Args) -> &[PathBuf] { } } -fn configure_pipeline

(converter: P, extensions: Option<&Registry>) -> Pipeline

{ +fn configure_pipeline

(converter: P, extensions: Option<&Extensions>) -> Pipeline

{ let pipeline = Pipeline::new(converter); match extensions { Some(registrations) => pipeline.with_extensions(registrations.clone()), @@ -549,7 +548,7 @@ fn run_converter( args: &Args, base_options: &Options, document_attributes: OptionsBuilder<'static>, - extensions: Option<&Registry>, + extensions: Option<&Extensions>, make_converter: F, ) -> MietteResult where @@ -644,7 +643,7 @@ fn run_multi_file( base_options: &Options, document_attributes: &OptionsBuilder<'static>, files_to_process: &[PathBuf], - extensions: Option<&Registry>, + extensions: Option<&Extensions>, make_converter: F, ) -> MietteResult where @@ -1322,7 +1321,7 @@ fn run_terminal_stdin( args: &Args, base_options: &Options, document_attributes: OptionsBuilder<'static>, - extensions: Option<&Registry>, + extensions: Option<&Extensions>, output_to_file: bool, ) -> Result { use acdc_converters_terminal::Converter; @@ -1425,7 +1424,7 @@ fn run_terminal_with_pager( args: &Args, base_options: &Options, document_attributes: OptionsBuilder<'static>, - extensions: Option<&Registry>, + extensions: Option<&Extensions>, ) -> Result { use acdc_converters_terminal::Converter; diff --git a/acdc-cli/src/subcommands/convert/pipeline_tests.rs b/acdc-cli/src/subcommands/convert/pipeline_tests.rs index e2c6fbadf..97bada8b0 100644 --- a/acdc-cli/src/subcommands/convert/pipeline_tests.rs +++ b/acdc-cli/src/subcommands/convert/pipeline_tests.rs @@ -11,6 +11,7 @@ use std::{ use acdc_parser::extensions::{ BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroExecutionContext, MacroInvocation, + Registry, }; use clap::{Parser, ValueEnum}; diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 7b92fb5e8..a1e4429f1 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2182,7 +2182,10 @@ ordinary parser path. For backend-aware parsing through conversion, use converter core's `pipeline::Pipeline` with an already configured backend. `ExtensionCatalog` separates named availability from explicit activation and rejects unavailable -selections before parsing. Pipeline parse methods return finalized `ParseResult` +selections before parsing. Selected `Extensions` can contain parser and native +renderer registrations; `parser_registry()` exposes parser registrations when a +working session is needed. Renderer-only selections retain ordinary parsing. +Pipeline parse methods return finalized `ParseResult` values with structured warnings; conversion prepares fresh display content and leaves parsed storage unchanged. See the link:../converters/README.adoc[converter guide] and its runnable library example. diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 2f41d8d54..be4e2fc1a 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1826,7 +1826,10 @@ ordinary parser path. For backend-aware parsing through conversion, use converter core's `pipeline::Pipeline` with an already configured backend. `ExtensionCatalog` separates named availability from explicit activation and rejects unavailable -selections before parsing. Pipeline parse methods return finalized `ParseResult` +selections before parsing. Selected `Extensions` can contain parser and native +renderer registrations; `parser_registry()` exposes parser registrations when a +working session is needed. Renderer-only selections retain ordinary parsing. +Pipeline parse methods return finalized `ParseResult` values with structured warnings; conversion prepares fresh display content and leaves parsed storage unchanged. See the [converter guide](../converters/README.adoc) and its runnable library example. diff --git a/converters/README.adoc b/converters/README.adoc index 9cf8e5277..f2782a9de 100644 --- a/converters/README.adoc +++ b/converters/README.adoc @@ -18,7 +18,8 @@ labels before handing the finalized document to the backend. Registering a package invokes no factories. `select` validates all names and registration conflicts before input processing; packages run in selection order, preserving their own registration order. Repeated selections count once. Attach -the returned registry with `Pipeline::with_extensions`. An empty selection keeps +the returned `Extensions` with `Pipeline::with_extensions`. Parser registries are +also accepted directly. An empty selection keeps the ordinary parser path without extension indexes or retained title snapshots. The link:./html/examples/extension_pipeline.rs[extension pipeline example] diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index b4655a4ff..908dbb120 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Native extensions can register backend-specific block renderers alongside + parser processors. Selection creates fresh render handlers for every conversion, + retains structured warnings, and lets the backend render titles and metadata. + `ExtensionCatalog::select()` now returns an `Extensions` selection; use + `parser_registry()` when a parser-only working session is needed. Existing parser + registries can still be attached directly to a pipeline. + - Added a shared library pipeline for backend-aware parsing, selected extensions, finalization, and conversion. Named extensions require explicit activation; unavailable names fail before parsing. Files, readers, and source strings retain diff --git a/converters/core/src/lib.rs b/converters/core/src/lib.rs index e0349f07f..81c122eb7 100644 --- a/converters/core/src/lib.rs +++ b/converters/core/src/lib.rs @@ -56,6 +56,7 @@ pub mod link; pub mod list; pub mod media; pub mod pipeline; +pub mod render; pub mod section; pub mod substitutions; pub mod table; @@ -626,6 +627,23 @@ pub trait Converter<'a>: Sized { diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Self::Error>; + /// Write with explicitly selected native rendering extensions. + /// Backends without rendering hooks retain their ordinary output. + /// + /// # Errors + /// Returns processor, conversion, or output errors. + fn write_to_with_extensions( + &self, + doc: DocumentRef<'_>, + writer: W, + source_file: Option<&Path>, + output_path: Option<&Path>, + _extensions: &pipeline::Extensions, + diagnostics: &mut Diagnostics<'_>, + ) -> Result<(), Self::Error> { + self.write_to(doc, writer, source_file, output_path, diagnostics) + } + /// Returns the converter's display name (e.g. `"html"`, `"html5s"`, /// `"manpage"`, `"markdown"`, `"terminal"`). /// diff --git a/converters/core/src/pipeline.rs b/converters/core/src/pipeline.rs index cb2df68a7..c1b632251 100644 --- a/converters/core/src/pipeline.rs +++ b/converters/core/src/pipeline.rs @@ -15,7 +15,7 @@ //! run once at committed source boundaries; tree processors run once after parsing. //! No handler is shared across documents, even when registry factories are shared. //! -//! [`Registry`] exposes working sessions for callers that need checked tree edits. +//! [`acdc_parser::extensions::Registry`] exposes working sessions for callers that need checked tree edits. //! Borrowed queries end before editing; query again to observe repairs. Copied //! selections stay snapshots. Document-local target handles survive insertions and //! replacement, but removed handles never bind to another block. Normalization is @@ -37,18 +37,20 @@ use std::{ path::Path, }; -use acdc_parser::{Error, ParseResult, ast::DocumentRef, extensions::Registry}; +use acdc_parser::{Error, ParseResult, ast::DocumentRef}; use crate::{ConversionResult, Converter, Diagnostics, display}; mod extensions; +mod registrations; pub use extensions::{ExtensionCatalog, ExtensionSelectionError}; +pub use registrations::Extensions; /// A configured backend and the registrations explicitly active for its documents. #[derive(Debug)] pub struct Pipeline { converter: C, - extensions: Option, + extensions: Extensions, } impl Pipeline { @@ -56,14 +58,17 @@ impl Pipeline { pub const fn new(converter: C) -> Self { Self { converter, - extensions: None, + extensions: Extensions { + parser: None, + renderers: Vec::new(), + }, } } /// Activate registrations for subsequent parses. Empty registries keep the direct path. #[must_use] - pub fn with_extensions(mut self, registrations: Registry) -> Self { - self.extensions = (!registrations.is_empty()).then_some(registrations); + pub fn with_extensions(mut self, registrations: impl Into) -> Self { + self.extensions = registrations.into(); self } @@ -82,7 +87,7 @@ impl<'options, C: Converter<'options>> Pipeline { /// callback effects cannot be rolled back when a later stage fails. pub fn parse(&self, source: &str) -> Result { let options = self.converter.parser_options(); - match &self.extensions { + match self.extensions.parser_registry() { Some(registry) => registry.parse(source, options)?.finish(), None => acdc_parser::parse(source, options), } @@ -94,7 +99,7 @@ impl<'options, C: Converter<'options>> Pipeline { /// Returns input, processor, or finalization errors. pub fn parse_file(&self, path: impl AsRef) -> Result { let options = self.converter.parser_options(); - match &self.extensions { + match self.extensions.parser_registry() { Some(registry) => registry.parse_file(path, options)?.finish(), None => acdc_parser::parse_file(path, options), } @@ -106,7 +111,7 @@ impl<'options, C: Converter<'options>> Pipeline { /// Returns input, processor, or finalization errors. pub fn parse_from_reader(&self, reader: impl Read) -> Result { let options = self.converter.parser_options(); - match &self.extensions { + match self.extensions.parser_registry() { Some(registry) => registry.parse_from_reader(reader, options)?.finish(), None => acdc_parser::parse_from_reader(reader, options), } @@ -125,11 +130,12 @@ impl<'options, C: Converter<'options>> Pipeline { diagnostics: &mut Diagnostics<'_>, ) -> Result<(), C::Error> { let prepared = display::prepare(document)?; - self.converter.write_to( + self.converter.write_to_with_extensions( prepared.document(), writer, source_file, output_path, + &self.extensions, diagnostics, ) } @@ -144,7 +150,57 @@ impl<'options, C: Converter<'options>> Pipeline { document: DocumentRef<'_>, source_file: Option<&Path>, ) -> Result { - let prepared = display::prepare(document)?; - self.converter.convert(prepared.document(), source_file) + if self.extensions.renderers.is_empty() { + let prepared = display::prepare(document)?; + self.converter.convert(prepared.document(), source_file) + } else { + >::convert(self, document, source_file) + } + } +} + +impl<'options, C: Converter<'options>> Converter<'options> for Pipeline { + type Error = C::Error; + + fn document_attributes_defaults() + -> &'static [(&'static str, acdc_parser::AttributeValue<'static>)] { + C::document_attributes_defaults() + } + + fn new( + options: crate::Options, + parser: acdc_parser::OptionsBuilder<'options>, + ) -> Result { + Ok(Self::new(C::new(options, parser)?)) + } + + fn options(&self) -> &crate::Options { + self.converter.options() + } + fn parser_options(&self) -> &acdc_parser::Options<'options> { + self.converter.parser_options() + } + fn name(&self) -> &'static str { + self.converter.name() + } + fn warning_source(&self) -> crate::WarningSource { + self.converter.warning_source() + } + fn derive_output_path( + &self, + input: &Path, + document: DocumentRef<'_>, + ) -> Result, Self::Error> { + self.converter.derive_output_path(input, document) + } + fn write_to( + &self, + document: DocumentRef<'_>, + writer: W, + source: Option<&Path>, + output: Option<&Path>, + diagnostics: &mut Diagnostics<'_>, + ) -> Result<(), Self::Error> { + Self::write_to(self, document, writer, source, output, diagnostics) } } diff --git a/converters/core/src/pipeline/extensions.rs b/converters/core/src/pipeline/extensions.rs index feca45659..85cdf5a90 100644 --- a/converters/core/src/pipeline/extensions.rs +++ b/converters/core/src/pipeline/extensions.rs @@ -2,10 +2,12 @@ use std::collections::{BTreeMap, HashSet}; use acdc_parser::extensions::{RegistrationError, Registry}; +use super::Extensions; + /// Available extension registrations. Availability does not activate processors. #[derive(Clone, Debug, Default)] pub struct ExtensionCatalog { - available: BTreeMap, + available: BTreeMap, } /// Configuration rejected before input processing or handler construction. @@ -41,7 +43,7 @@ impl ExtensionCatalog { pub fn register( &mut self, name: impl Into, - registrations: Registry, + registrations: impl Into, ) -> Result<(), ExtensionSelectionError> { let name = name.into(); let mut bytes = name.bytes(); @@ -53,7 +55,7 @@ impl ExtensionCatalog { if self.available.contains_key(&name) { return Err(ExtensionSelectionError::DuplicateName(name)); } - self.available.insert(name, registrations); + self.available.insert(name, registrations.into()); Ok(()) } @@ -71,10 +73,11 @@ impl ExtensionCatalog { pub fn select( &self, names: impl IntoIterator>, - ) -> Result, ExtensionSelectionError> { + ) -> Result, ExtensionSelectionError> { let mut selected = HashSet::new(); let mut builder = Registry::builder(); let mut active = false; + let mut renderers = Vec::new(); for name in names { let (name, registrations) = self .available @@ -83,14 +86,21 @@ impl ExtensionCatalog { if !selected.insert(name.as_str()) { continue; } - builder - .extend(registrations) - .map_err(|source| ExtensionSelectionError::Conflict { - name: name.clone(), - source, - })?; - active |= !registrations.is_empty(); + if let Some(parser) = registrations.parser_registry() { + builder + .extend(parser) + .map_err(|source| ExtensionSelectionError::Conflict { + name: name.clone(), + source, + })?; + active = true; + } + renderers.extend(registrations.renderers.iter().cloned()); } - Ok(active.then(|| builder.build())) + let extensions = Extensions { + parser: active.then(|| builder.build()), + renderers, + }; + Ok((!extensions.is_empty()).then_some(extensions)) } } diff --git a/converters/core/src/pipeline/registrations.rs b/converters/core/src/pipeline/registrations.rs new file mode 100644 index 000000000..8ffe6f8ec --- /dev/null +++ b/converters/core/src/pipeline/registrations.rs @@ -0,0 +1,54 @@ +use acdc_parser::extensions::Registry; + +use crate::render::{BlockRenderer, RenderSession}; + +/// Immutable parser and renderer registrations, available or explicitly selected. +/// Cloning shares factories; every parse and conversion gets fresh mutable processors. +#[derive(Clone, Debug, Default)] +pub struct Extensions { + pub(super) parser: Option, + pub(super) renderers: Vec, +} + +impl From for Extensions { + fn from(registry: Registry) -> Self { + Self { + parser: (!registry.is_empty()).then_some(registry), + renderers: Vec::new(), + } + } +} + +impl Extensions { + /// Append a renderer without constructing or executing it. + #[must_use] + pub fn with_renderer(mut self, registration: BlockRenderer) -> Self { + self.renderers.push(registration); + self + } + + /// Parser registrations, for callers that need a working edit session. + #[must_use] + pub fn parser_registry(&self) -> Option<&Registry> { + self.parser.as_ref() + } + + /// Whether this collection has no parser or rendering capabilities. + #[must_use] + pub fn is_empty(&self) -> bool { + self.parser.is_none() && self.renderers.is_empty() + } + + /// Construct document-local renderers for a backend family, in registration order. + /// Other backends invoke no factories. Empty selections allocate no session. + #[must_use] + pub fn render_session(&self, backend: &str) -> Option { + let processors: Vec<_> = self + .renderers + .iter() + .filter(|registration| registration.backend == backend) + .map(|registration| (registration.factory)()) + .collect(); + (!processors.is_empty()).then_some(RenderSession { processors }) + } +} diff --git a/converters/core/src/render.rs b/converters/core/src/render.rs new file mode 100644 index 000000000..8d9ace8d7 --- /dev/null +++ b/converters/core/src/render.rs @@ -0,0 +1,142 @@ +//! Native block rendering with fresh processors for each conversion. + +use std::{fmt, io::Write, sync::Arc}; + +use acdc_parser::{DocumentAttributes, ast::BlockRef}; + +use crate::{Diagnostics, Options}; + +/// A native renderer or host-service failure, preserving its original source. +pub type RenderError = Box; + +/// A backend-specific renderer factory. Constructing it executes no processor. +#[derive(Clone)] +pub struct BlockRenderer { + pub(crate) backend: &'static str, + pub(crate) factory: Arc Box + Send + Sync>, +} + +impl fmt::Debug for BlockRenderer { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BlockRenderer") + .field("backend", &self.backend) + .finish_non_exhaustive() + } +} + +impl BlockRenderer { + /// Register a factory for a backend family such as `html`. + /// Processors may contain non-`Send` state; factories must be shareable. + pub fn new( + backend: &'static str, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Self { + Self { + backend, + factory: Arc::new(move || Box::new(factory())), + } + } +} + +/// A mutable processor belonging to one conversion, including its nested blocks. +pub trait BlockRenderProcessor { + /// Render a block or decline it so the next renderer or backend can handle it. + /// A declined block must not write output; structured fallback warnings are allowed. + /// + /// # Errors + /// Stops conversion on processor, host, or output failure. Earlier writes and + /// external effects cannot be rolled back. + fn render( + &mut self, + block: BlockRef<'_>, + host: &mut dyn RenderHost, + ) -> Result; + + /// Inline script hashes required by this selected renderer, for the host's CSP. + fn script_hashes(&self) -> &'static [&'static str] { + &[] + } +} + +/// Backend services for a native renderer. Titles and metadata retain host semantics. +pub trait RenderHost { + /// Current backend variant, such as `html5` or `html5s`. + fn variant(&self) -> &str; + /// Backend document attributes with parsed values and assignment metadata. + fn document_attributes(&self) -> &DocumentAttributes<'_>; + /// Validated application options, including safe mode. + fn options(&self) -> &Options; + /// Open a backend element with the block's ID, roles, and default classes. + /// Native renderers supply trusted target markup; the host escapes document metadata. + /// + /// # Errors + /// Returns output or metadata errors. + fn open_block( + &mut self, + block: BlockRef<'_>, + element: &str, + classes: &str, + ) -> Result<(), RenderError>; + /// Render the block's caption and title between target-specific wrappers. + /// + /// # Errors + /// Returns title-rendering or output errors. + fn title(&mut self, block: BlockRef<'_>, prefix: &str, suffix: &str) + -> Result<(), RenderError>; + /// Borrow output and its structured diagnostics together, without buffering. + /// + /// # Errors + /// Preserves failures returned by the operation. + fn output( + &mut self, + operation: &mut dyn FnMut(&mut dyn Write, &mut Diagnostics<'_>) -> Result<(), RenderError>, + ) -> Result<(), RenderError>; + /// Write trusted backend output. + /// + /// # Errors + /// Returns output errors. + fn write(&mut self, bytes: &[u8]) -> Result<(), RenderError> { + self.output(&mut |writer, _| Ok(writer.write_all(bytes)?)) + } +} + +/// Selected processors instantiated once for a conversion. Dispatch follows registration order. +pub struct RenderSession { + pub(crate) processors: Vec>, +} + +impl fmt::Debug for RenderSession { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("RenderSession") + .field("processors", &self.processors.len()) + .finish() + } +} + +impl RenderSession { + /// Dispatch until a processor handles the block, otherwise use ordinary rendering. + /// + /// # Errors + /// Stops at the first processor failure without retrying it. + pub fn render( + &mut self, + block: BlockRef<'_>, + host: &mut dyn RenderHost, + ) -> Result { + for processor in &mut self.processors { + if processor.render(block, host)? { + return Ok(true); + } + } + Ok(false) + } + + /// CSP hashes belonging to selected processors for this backend. + pub fn script_hashes(&self) -> impl Iterator + '_ { + self.processors + .iter() + .flat_map(|processor| processor.script_hashes().iter().copied()) + } +} diff --git a/converters/core/tests/pipeline.rs b/converters/core/tests/pipeline.rs index 51fea962b..f5dccd62c 100644 --- a/converters/core/tests/pipeline.rs +++ b/converters/core/tests/pipeline.rs @@ -11,7 +11,7 @@ use std::{ use acdc_converters_core::{ BackendProfile, Converter, Diagnostics, Options, - pipeline::{ExtensionCatalog, ExtensionSelectionError, Pipeline}, + pipeline::{ExtensionCatalog, ExtensionSelectionError, Extensions, Pipeline}, }; use acdc_parser::{ Error as ParserError, Options as ParserOptions, OptionsBuilder, SafeMode, WarningKind, @@ -117,7 +117,7 @@ fn catalog(created: &Arc) -> Result) -> Result, Error> { +fn pipeline(registry: Option) -> Result, Error> { let pipeline = Pipeline::new(JsonConverter::new( Options::default(), ParserOptions::builder(), @@ -289,7 +289,7 @@ fn pipeline_finalizes_once_and_prepares_explicit_labels_for_custom_backends() -> let mut builder = Registry::builder(); builder.register_tree_processor(TreeProcessorRegistration::new("capture", || Capture))?; let registry = builder.build(); - let pipeline = pipeline(Some(registry.clone()))?; + let pipeline = pipeline(Some(registry.clone().into()))?; let mut working = registry.parse( ":listing-caption: Code\n\n.A *title*\n[#code,reftext=Other]\n----\nbody\n----", pipeline.converter().parser_options(), @@ -316,7 +316,7 @@ fn pipeline_empty_registries_keep_the_direct_path_and_reader_errors() -> TestRes Err(io::Error::other("reader failed")) } } - let pipeline = pipeline(Some(Registry::default()))?; + let pipeline = pipeline(Some(Registry::default().into()))?; let parsed = pipeline.parse("Paragraph.")?; assert!(serde_json::to_string(&parsed.document())?.contains("Paragraph.")); assert!(pipeline.parse_from_reader(Broken).is_err()); @@ -335,10 +335,11 @@ fn pipeline_registry_composition_rejects_conflicts_atomically() -> TestResult { catalog.register("invalid name", Registry::default()), Err(ExtensionSelectionError::InvalidName(_)) )); - let original = catalog.select(["counter"])?.ok_or("active registry")?; + let selected = catalog.select(["counter"])?.ok_or("active registry")?; + let original = selected.parser_registry().ok_or("parser registry")?; let mut incoming = Registry::builder(); incoming.register(BlockMacro::new("fresh", || Counter { calls: 0 }))?; - incoming.extend(&original)?; + incoming.extend(original)?; let incoming = incoming.build(); catalog.register("conflict", incoming.clone())?; assert!(matches!( @@ -347,9 +348,9 @@ fn pipeline_registry_composition_rejects_conflicts_atomically() -> TestResult { )); assert_eq!(created.load(Ordering::SeqCst), 0); let mut builder = Registry::builder(); - builder.extend(&original)?; + builder.extend(original)?; assert!(builder.extend(&incoming).is_err()); - let pipeline = pipeline(Some(builder.build()))?; + let pipeline = pipeline(Some(builder.build().into()))?; let parsed = pipeline.parse("count::one[]\n\nfresh::idle[]")?; let rendered = render(&pipeline, parsed.document())?.0.to_string(); assert!(rendered.contains("one:1")); @@ -388,3 +389,45 @@ fn pipeline_selection_order_controls_processor_order() -> TestResult { assert!(!text.contains("second")); Ok(()) } + +#[test] +fn pipeline_renderer_factories_wait_for_matching_backend_sessions() -> TestResult { + use acdc_converters_core::render::{ + BlockRenderProcessor, BlockRenderer, RenderError, RenderHost, + }; + + struct Decline; + impl BlockRenderProcessor for Decline { + fn render( + &mut self, + _: acdc_parser::ast::BlockRef<'_>, + _: &mut dyn RenderHost, + ) -> Result { + Ok(false) + } + } + + let created = Arc::new(AtomicUsize::new(0)); + let factory_created = Arc::clone(&created); + let registrations = + Extensions::default().with_renderer(BlockRenderer::new("html", move || { + factory_created.fetch_add(1, Ordering::SeqCst); + Decline + })); + let mut available = ExtensionCatalog::default(); + available.register("renderer", registrations)?; + assert_eq!(created.load(Ordering::SeqCst), 0); + assert!(available.select([] as [&str; 0])?.is_none()); + assert!(available.select(["unknown"]).is_err()); + let selected = available + .select(["renderer", "renderer"])? + .ok_or("selected renderer")?; + assert!(selected.parser_registry().is_none()); + assert!(selected.render_session("markdown").is_none()); + assert_eq!(created.load(Ordering::SeqCst), 0); + let first = selected.render_session("html").ok_or("first session")?; + let second = selected.render_session("html").ok_or("second session")?; + assert_eq!(created.load(Ordering::SeqCst), 2); + drop((first, second)); + Ok(()) +} From 27fd755d8b04ba258d7c7135a801bf1ecb1832bd Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Mon, 16 Nov 2026 11:20:39 +0100 Subject: [PATCH 22/55] feat(html): host native block renderer sessions Expose HTML host services and dispatch explicitly selected renderers per conversion. SC-541 --- ARCHITECTURE.adoc | 9 +- acdc-cli/CHANGELOG.md | 3 +- acdc-cli/README.adoc | 2 - converters/README.adoc | 4 + converters/html/CHANGELOG.md | 6 + converters/html/README.adoc | 7 +- converters/html/src/csp.rs | 20 +- converters/html/src/delimited.rs | 5 +- converters/html/src/error.rs | 3 + converters/html/src/extensions.rs | 96 +++++++++ converters/html/src/html_visitor.rs | 11 +- converters/html/src/lib.rs | 56 ++++- converters/html/tests/render_extensions.rs | 228 +++++++++++++++++++++ 13 files changed, 426 insertions(+), 24 deletions(-) create mode 100644 converters/html/src/extensions.rs create mode 100644 converters/html/tests/render_extensions.rs diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc index dc6ac1d35..47ccb5ec7 100644 --- a/ARCHITECTURE.adoc +++ b/ARCHITECTURE.adoc @@ -111,7 +111,6 @@ The backend is configured before parsing so its attributes govern source processing. An `ExtensionCatalog` lists packages available in the application; explicit selection activates them and rejects unavailable names before reading input. Selected packages preserve selection order and their registration order. -The production CLI registers no extension packages yet. `Pipeline` coordinates parser-owned source processing, committed callbacks, tree processors, and finalization for strings, files, and readers. Conversion @@ -134,6 +133,14 @@ by the caller. Processor errors stop later work. Checked edits are atomic, but earlier successful edits and external callback effects cannot be rolled back as a sequence. +Native block renderers are also immutable registrations with fresh mutable +handlers per conversion. `Extensions` combines parser and renderer capabilities; +renderer-only selections retain ordinary parsing. Backends dispatch selected +renderers in order and use ordinary rendering when every handler declines. +HTML supplies streaming output, diagnostics, metadata escaping, and caption/title +services. Selected renderers supply their CSP script hashes. No handler can edit +the shared parsed document through this rendering interface. + ==== Inline preprocessing Inline content needs special handling, as specified in https://gitlab.eclipse.org/eclipse/asciidoc-lang/asciidoc-lang/-/blob/main/spec/sdrs/sdr-005-formal-grammar-for-inline-syntax.adoc[SDR-005: Formal Grammar for Inline Syntax]. diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index de1412ec4..bdeac16a8 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -9,8 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Conversion accepts repeatable `--extension NAME` selections and rejects unavailable packages before reading input. All input and output routes share - the backend-aware library pipeline. No extension packages ship in the current - binary, and ordinary conversion keeps its existing defaults. + the backend-aware library pipeline. - Conversion continues after recoverable parser errors and reports structured warnings, including non-conforming manpage titles. `convert --fail-on-warnings` diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index ee290a0b5..d558dc300 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -127,8 +127,6 @@ Supported backends depend on the features used to build the binary: application. Repeat the option to select multiple packages in execution order; duplicate selections count once. Compiling or registering a package does not activate it. Unknown or unavailable names fail before input is read or parsed. -The current production binary registers no extension packages, so every name is -unavailable until a package is added. Files, stdin, batches, terminal output, and pager output use the same pipeline. The selected backend supplies attributes before preprocessing, and every document diff --git a/converters/README.adoc b/converters/README.adoc index f2782a9de..bb75f9555 100644 --- a/converters/README.adoc +++ b/converters/README.adoc @@ -46,6 +46,10 @@ and external callback effects remain. Structured parser warnings stay on the parse result, and conversion warnings stay in `Diagnostics` or `ConversionResult` until the application presents them. +Native block renderers use the same selection. They receive a fresh handler for +each conversion and can use the backend's streaming output, title/caption, and +metadata services. Declined blocks use ordinary rendering. + == Development prerequisites Converter tests are run with `cargo nextest run --all-features`. The terminal diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index 300dd5aab..6f8f1304d 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- HTML callers can select native block renderers. Their CSP script hashes are + included in the document policy. Native renderer failures are + exposed through `Error::Extension` with their original error source. + Callers using HTML-specific `RenderOptions` can select registrations through + `convert_to_writer_with_extensions()`. + - Reusing a converter for the same document or independent documents now produces stable index anchors and catalog links, with numbering restarted per conversion. diff --git a/converters/html/README.adoc b/converters/html/README.adoc index 01b467ffd..6ad1c996d 100644 --- a/converters/html/README.adoc +++ b/converters/html/README.adoc @@ -378,11 +378,8 @@ This is an acdc-only extension; Asciidoctor does not provide a `:acdc-terminal:` attribute, the `[terminal]` or `[terminal%replay]` block styles, or any equivalent built-in terminal preview or replay feature. -NOTE: Terminal rendering is built directly into the HTML converter, the -`terminal` Cargo feature of `acdc-converters-html`, backed by the -`acdc-converters-terminal` crate, rather than being loaded as a plug-in. If -acdc grows a first-class extension mechanism, this functionality may migrate to -an extension instead of being compiled into the converter. +The HTML converter implements terminal rendering with its optional dependency on +`acdc-converters-terminal`. Use `:acdc-terminal:` when existing source blocks should look like terminal examples: diff --git a/converters/html/src/csp.rs b/converters/html/src/csp.rs index c224d6ae4..a7f29a8c4 100644 --- a/converters/html/src/csp.rs +++ b/converters/html/src/csp.rs @@ -12,11 +12,7 @@ //! so arbitrary document content keeps loading. /// Features and script hashes used to build a document's Content Security Policy. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -#[expect( - clippy::struct_excessive_bools, - reason = "independent on/off feature flags for selecting CSP sources" -)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct CspFeatures { /// `:stem:` is set, so the inline `MathJax` config and the `MathJax` CDN loader are /// emitted. @@ -28,9 +24,8 @@ pub(crate) struct CspFeatures { /// `icons=font` is set, so the Font Awesome stylesheet (and its fonts) are loaded /// from the CDN. pub icons_font: bool, - /// A terminal replay player may be present, so its inline script is allow-listed. - /// Ignored unless the `terminal` feature is compiled in. - pub replay: bool, + /// Hashes required by explicitly selected native renderers. + pub extension_script_hashes: Vec<&'static str>, } impl CspFeatures { @@ -48,11 +43,16 @@ impl CspFeatures { pub(crate) fn content_security_policy(self) -> String { let mut script_src = String::from("script-src 'self'"); #[cfg(feature = "terminal")] - if self.replay { + { script_src.push_str(" '"); script_src.push_str(crate::REPLAY_PLAYER_SCRIPT_CSP_HASH); script_src.push('\''); } + for hash in self.extension_script_hashes { + script_src.push_str(" '"); + script_src.push_str(hash); + script_src.push('\''); + } if self.stem { script_src.push_str(" '"); script_src.push_str(crate::MATHJAX_CONFIG_CSP_HASH); @@ -146,7 +146,7 @@ mod tests { #[test] fn replay_adds_player_hash() { let policy = CspFeatures { - replay: true, + extension_script_hashes: Vec::new(), ..CspFeatures::default() } .content_security_policy(); diff --git a/converters/html/src/delimited.rs b/converters/html/src/delimited.rs index 0e021a265..8ee6c0152 100644 --- a/converters/html/src/delimited.rs +++ b/converters/html/src/delimited.rs @@ -28,7 +28,7 @@ fn block_class(base: &str, attributes: Option>) -> String { } /// Write the opening `

` tag with optional ID and class attributes. -fn write_block_div_open( +pub(crate) fn write_block_div_open( w: &mut W, attributes: Option>, base_class: &str, @@ -44,7 +44,7 @@ fn write_block_div_open( } /// Write an opening tag with optional ID and class for semantic mode. -fn write_semantic_tag_open( +pub(crate) fn write_semantic_tag_open( w: &mut W, tag: &str, attributes: Option>, @@ -1151,6 +1151,7 @@ mod tests { index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(std::cell::RefCell::new(Vec::new())), generate_index: false, + render_session: None, variant: crate::HtmlVariant::Standard, } } diff --git a/converters/html/src/error.rs b/converters/html/src/error.rs index 349ed8580..e297c6650 100644 --- a/converters/html/src/error.rs +++ b/converters/html/src/error.rs @@ -28,6 +28,9 @@ pub enum Error { #[error(transparent)] TerminalReplay(#[from] acdc_converters_terminal::replay::Error), + #[error(transparent)] + Extension(#[from] acdc_converters_core::render::RenderError), + #[error("input file and output file cannot be the same: {0}")] OutputPathSameAsInput(std::path::PathBuf), diff --git a/converters/html/src/extensions.rs b/converters/html/src/extensions.rs new file mode 100644 index 000000000..b2edbd545 --- /dev/null +++ b/converters/html/src/extensions.rs @@ -0,0 +1,96 @@ +//! Host services for explicitly selected native block renderers. + +use std::io::Write; + +use acdc_converters_core::{ + Diagnostics, Options, TraversalContext, + render::{RenderError, RenderHost}, +}; +use acdc_parser::{CaptionKind, DocumentAttributes, ast::BlockRef}; + +use crate::{ + Error, HtmlVariant, HtmlVisitor, + delimited::{write_block_div_open, write_semantic_tag_open}, +}; + +impl<'doc, W: Write> HtmlVisitor<'doc, '_, W> { + pub(super) fn render_extension( + &mut self, + traversal: &mut TraversalContext<'doc>, + block: BlockRef<'doc>, + ) -> Result { + let Some(session) = self.converter.render_session.clone() else { + return Ok(false); + }; + let mut session = session.try_borrow_mut().map_err(|_| { + Error::Extension(std::io::Error::other("recursive block renderer dispatch").into()) + })?; + Ok(session.render( + block, + &mut Host { + visitor: self, + traversal, + }, + )?) + } +} + +struct Host<'host, 'doc, 'diagnostics, W: Write> { + visitor: &'host mut HtmlVisitor<'doc, 'diagnostics, W>, + traversal: &'host mut TraversalContext<'doc>, +} + +impl RenderHost for Host<'_, '_, '_, W> { + fn variant(&self) -> &str { + self.visitor.converter.variant.backend_profile().backend() + } + fn document_attributes(&self) -> &DocumentAttributes<'_> { + self.visitor.converter.document_attributes() + } + fn options(&self) -> &Options { + &self.visitor.converter.options + } + + fn open_block( + &mut self, + block: BlockRef<'_>, + element: &str, + classes: &str, + ) -> Result<(), RenderError> { + if self.visitor.converter.variant == HtmlVariant::Semantic || element != "div" { + write_semantic_tag_open( + &mut self.visitor.writer, + element, + block.attributes(), + classes, + )?; + } else { + write_block_div_open(&mut self.visitor.writer, block.attributes(), classes)?; + } + Ok(()) + } + + fn title( + &mut self, + block: BlockRef<'_>, + prefix: &str, + suffix: &str, + ) -> Result<(), RenderError> { + self.visitor.render_captioned_title_with_wrapper( + self.traversal, + block.title(), + block.attributes(), + CaptionKind::for_block(block), + prefix, + suffix, + )?; + Ok(()) + } + + fn output( + &mut self, + operation: &mut dyn FnMut(&mut dyn Write, &mut Diagnostics<'_>) -> Result<(), RenderError>, + ) -> Result<(), RenderError> { + operation(&mut self.visitor.writer, &mut self.visitor.diagnostics) + } +} diff --git a/converters/html/src/html_visitor.rs b/converters/html/src/html_visitor.rs index bcc14de48..61063332d 100644 --- a/converters/html/src/html_visitor.rs +++ b/converters/html/src/html_visitor.rs @@ -539,7 +539,13 @@ impl<'a, 'd, W: Write> HtmlVisitor<'a, 'd, W> { webfonts: !(stylesheet_disabled || !attrs.contains("webfonts") && attrs.is_explicit("webfonts")), icons_font: font_icons, - replay: cfg!(feature = "terminal"), + extension_script_hashes: self + .converter + .render_session + .as_ref() + .map_or_else(Vec::new, |session| { + session.borrow().script_hashes().collect() + }), } } @@ -735,6 +741,9 @@ impl<'a, W: Write> BlockVisitor<'a> for HtmlVisitor<'a, '_, W> { context: &mut TraversalContext<'a>, block: BlockRef<'a>, ) -> Result<(), Self::Error> { + if self.render_extension(context, block)? { + return Ok(()); + } match block.kind() { BlockKind::Section(section) => self.visit_section_ref(context, section), BlockKind::Paragraph(paragraph) => self.visit_paragraph_ref(context, paragraph), diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index d254917d0..5400ae486 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -38,6 +38,7 @@ mod delimited; mod docinfo; mod document; mod error; +mod extensions; mod html_visitor; mod icon; mod image; @@ -177,6 +178,7 @@ pub struct Converter<'a> { index_entries: Rc>>, /// Whether the header opts into a catalog and the section hierarchy has a seed. generate_index: bool, + render_session: Option>>, /// HTML output variant (Standard or Semantic). variant: HtmlVariant, } @@ -279,6 +281,29 @@ impl<'a> Converter<'a> { writer: W, options: &RenderOptions, diagnostics: &mut Diagnostics<'_>, + ) -> Result<(), Error> { + self.convert_to_writer_with_extensions( + doc, + writer, + options, + &acdc_converters_core::pipeline::Extensions::default(), + diagnostics, + ) + } + + /// Convert with explicit native renderers and HTML-specific render options. + /// Use a pipeline for source parsing and configured file/stdout routing. + /// Each call starts fresh render handlers and leaves parsed storage unchanged. + /// + /// # Errors + /// Returns display, native renderer, conversion, or output errors. + pub fn convert_to_writer_with_extensions( + &self, + doc: DocumentRef<'_>, + writer: W, + options: &RenderOptions, + extensions: &acdc_converters_core::pipeline::Extensions, + diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Error> { let prepared = acdc_converters_core::display::prepare(doc)?; let document = prepared.document(); @@ -306,6 +331,9 @@ impl<'a> Converter<'a> { index_term_counter: Rc::new(Cell::new(0)), index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(RefCell::new(Vec::new())), + render_session: extensions + .render_session("html") + .map(|session| Rc::new(RefCell::new(session))), variant: self.variant, }; let mut traversal = TraversalContext::new(document.attributes()); @@ -515,6 +543,25 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { source_file: Option<&Path>, output_path: Option<&Path>, diagnostics: &mut Diagnostics<'_>, + ) -> Result<(), Self::Error> { + self.write_to_with_extensions( + doc, + writer, + source_file, + output_path, + &acdc_converters_core::pipeline::Extensions::default(), + diagnostics, + ) + } + + fn write_to_with_extensions( + &self, + doc: DocumentRef<'_>, + writer: W, + source_file: Option<&Path>, + output_path: Option<&Path>, + extensions: &acdc_converters_core::pipeline::Extensions, + diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Self::Error> { let render_options = RenderOptions { last_updated: source_file.and_then(|f| { @@ -531,7 +578,13 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { .map(String::from), ..RenderOptions::default() }; - self.convert_to_writer(doc, writer, &render_options, diagnostics)?; + self.convert_to_writer_with_extensions( + doc, + writer, + &render_options, + extensions, + diagnostics, + )?; // Embedded fragments have no to link companion stylesheets from. if let Some(output_path) = output_path @@ -595,6 +648,7 @@ impl<'a> Converter<'a> { index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(RefCell::new(Vec::new())), generate_index: false, + render_session: None, variant, }) } diff --git a/converters/html/tests/render_extensions.rs b/converters/html/tests/render_extensions.rs new file mode 100644 index 000000000..3db443480 --- /dev/null +++ b/converters/html/tests/render_extensions.rs @@ -0,0 +1,228 @@ +//! Native renderer activation, dispatch, failures, and conversion-local state. + +use std::{ + cell::Cell, + rc::Rc, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, +}; + +use acdc_converters_core::{ + Converter as _, Diagnostics, Options, + pipeline::{ExtensionCatalog, Extensions, Pipeline}, + render::{BlockRenderProcessor, BlockRenderer, RenderError, RenderHost}, +}; +use acdc_converters_html::Converter; +use acdc_parser::{ + Options as ParserOptions, + ast::{BlockKind, BlockRef}, +}; + +type TestResult = Result<(), Box>; + +struct Counter { + calls: Rc>, +} + +impl BlockRenderProcessor for Counter { + fn render( + &mut self, + block: BlockRef<'_>, + host: &mut dyn RenderHost, + ) -> Result { + if !matches!(block.kind(), BlockKind::Paragraph(_)) { + return Ok(false); + } + self.calls.set(self.calls.get() + 1); + host.write(format!("

native:{}

\n", self.calls.get()).as_bytes())?; + Ok(true) + } +} + +fn available(created: &Arc) -> Result> { + let created = Arc::clone(created); + let mut catalog = ExtensionCatalog::default(); + catalog.register( + "counter", + Extensions::default().with_renderer(BlockRenderer::new("html", move || { + created.fetch_add(1, Ordering::SeqCst); + Counter { + calls: Rc::new(Cell::new(0)), + } + })), + )?; + Ok(catalog) +} + +fn pipeline( + selection: Option, +) -> Result>, acdc_converters_html::Error> { + let pipeline = Pipeline::new(Converter::new( + Options::builder().embedded(true).build(), + ParserOptions::builder(), + )?); + Ok(match selection { + Some(selection) => pipeline.with_extensions(selection), + None => pipeline, + }) +} + +fn render( + pipeline: &Pipeline>, + source: &str, +) -> Result> { + let parsed = pipeline.parse(source)?; + let mut output = Vec::new(); + let mut warnings = Vec::new(); + let warning_source = pipeline.converter().warning_source(); + pipeline.write_to( + parsed.document(), + &mut output, + None, + None, + &mut Diagnostics::new(&warning_source, &mut warnings), + )?; + assert!(warnings.is_empty(), "{warnings:?}"); + Ok(String::from_utf8(output)?) +} + +#[test] +fn native_renderers_are_explicit_and_fresh_across_nested_and_parallel_conversions() -> TestResult { + let created = Arc::new(AtomicUsize::new(0)); + let available = available(&created)?; + assert_eq!(created.load(Ordering::SeqCst), 0); + let inactive = pipeline(None)?; + assert!(render(&inactive, "ordinary")?.contains("ordinary")); + assert_eq!(created.load(Ordering::SeqCst), 0); + let selected = available + .select(["counter", "counter"])? + .ok_or("selection")?; + assert!(selected.parser_registry().is_none()); + let active = pipeline(Some(selected))?; + assert_eq!(created.load(Ordering::SeqCst), 0); + let source = "one\n\n====\ntwo\n====\n\n[cols=a]\n|===\n|three\n|==="; + let first = render(&active, source)?; + assert!(first.contains("native:1")); + assert!(first.contains("native:2")); + assert!(first.contains("native:3")); + assert!(!first.contains("native:4")); + assert_eq!(first, render(&active, source)?); + assert_eq!(created.load(Ordering::SeqCst), 2); + std::thread::scope(|scope| { + let handles: Vec<_> = (0..3) + .map(|_| { + let available = &available; + scope.spawn(move || -> Result<(), String> { + let pipeline = pipeline( + available + .select(["counter"]) + .map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + let output = + render(&pipeline, "parallel").map_err(|error| error.to_string())?; + assert!(output.contains("native:1")); + Ok(()) + }) + }) + .collect(); + for handle in handles { + handle.join().map_err(|_| "thread failure")??; + } + Ok::<_, Box>(()) + })?; + assert_eq!(created.load(Ordering::SeqCst), 5); + Ok(()) +} + +struct Fail(Arc); +impl BlockRenderProcessor for Fail { + fn render(&mut self, _: BlockRef<'_>, _: &mut dyn RenderHost) -> Result { + self.0.fetch_add(1, Ordering::SeqCst); + Err(std::io::Error::other("native failure").into()) + } +} + +#[test] +fn native_renderer_errors_stop_once_and_other_backend_factories_stay_inactive() -> TestResult { + let created = Arc::new(AtomicUsize::new(0)); + let other = Arc::clone(&created); + let registrations = + Extensions::default().with_renderer(BlockRenderer::new("markdown", move || { + other.fetch_add(1, Ordering::SeqCst); + Counter { + calls: Rc::new(Cell::new(0)), + } + })); + assert!(render(&pipeline(Some(registrations))?, "ordinary")?.contains("ordinary")); + assert_eq!(created.load(Ordering::SeqCst), 0); + let calls = Arc::new(AtomicUsize::new(0)); + let factory_calls = Arc::clone(&calls); + let registrations = Extensions::default() + .with_renderer(BlockRenderer::new("html", move || { + Fail(Arc::clone(&factory_calls)) + })); + let pipeline = pipeline(Some(registrations))?; + let error = render(&pipeline, "one\n\ntwo") + .err() + .ok_or("expected failure")?; + assert!(error.to_string().contains("native failure")); + assert_eq!(calls.load(Ordering::SeqCst), 1); + Ok(()) +} + +struct Decision { + label: &'static str, + handled: bool, + trace: Arc>>, +} + +impl BlockRenderProcessor for Decision { + fn render( + &mut self, + block: BlockRef<'_>, + host: &mut dyn RenderHost, + ) -> Result { + if !matches!(block.kind(), BlockKind::Paragraph(_)) { + return Ok(false); + } + self.trace + .lock() + .map_err(|_| "trace lock poisoned")? + .push(self.label); + if self.handled { + host.write(self.label.as_bytes())?; + } + Ok(self.handled) + } +} + +#[test] +fn native_renderer_dispatch_follows_selection_order_and_stops_when_handled() -> TestResult { + let trace = Arc::new(Mutex::new(Vec::new())); + let mut available = ExtensionCatalog::default(); + for (label, handled) in [("decline", false), ("second", true), ("third", true)] { + let trace = Arc::clone(&trace); + available.register( + label, + Extensions::default().with_renderer(BlockRenderer::new("html", move || Decision { + label, + handled, + trace: Arc::clone(&trace), + })), + )?; + } + let active = pipeline(available.select(["decline", "second", "third"])?)?; + assert_eq!(render(&active, "source")?, "second"); + assert_eq!( + *trace.lock().map_err(|_| "trace lock poisoned")?, + ["decline", "second"] + ); + trace.lock().map_err(|_| "trace lock poisoned")?.clear(); + let active = pipeline(available.select(["third", "second", "decline"])?)?; + assert_eq!(render(&active, "source")?, "third"); + assert_eq!(*trace.lock().map_err(|_| "trace lock poisoned")?, ["third"]); + Ok(()) +} From 3c90f68446c13d1adad0914a7ce77adeaa59234e Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Mon, 16 Nov 2026 20:40:07 +0100 Subject: [PATCH 23/55] feat(extensions): compose generated content with typed inline inputs Replace the unreleased InlineBuilder wrapper with InlineSpec text, break, display, and sequence shapes. Keep captured displays opaque and lower all inputs through the host's checked construction path. Preserve literal escaping, grouped list-item boundaries, frozen captures, and atomic rejection of foreign targets. Update both parser READMEs and exercise nested groups and the public input conversions. SC-542 --- acdc-parser/CHANGELOG.md | 4 + acdc-parser/README.adoc | 21 ++- acdc-parser/README.md | 21 ++- acdc-parser/src/extensions/builder.rs | 35 ++--- acdc-parser/src/extensions/display.rs | 120 +++------------- acdc-parser/src/extensions/inline.rs | 132 ++++++++++++++++++ acdc-parser/src/extensions/mod.rs | 7 +- .../src/extensions/tests/construction.rs | 105 +++++++++++++- acdc-parser/src/extensions/tests/display.rs | 26 ++-- 9 files changed, 331 insertions(+), 140 deletions(-) create mode 100644 acdc-parser/src/extensions/inline.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 376d426cc..d8a2c6ebb 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Native extensions can compose literal text, hard breaks, captured target links, + and grouped fragments through `InlineSpec` in generated paragraphs and list + items. + - Registered extensions now support reader input, including source-ordered callback attribute changes before later conditionals and includes. Applications can compose registries in order with duplicate-name checks before parsing. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index a1e4429f1..00cf750fa 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2116,13 +2116,20 @@ Use `DocumentEditor::capture()` to freeze a target's title, including its raw source, substitution order, formatting, and source-position attributes. A `CapturedTarget` belongs to one working document and remains a snapshot across later edits. Its `display()` method accepts `DisplayIntent::Caption`, `Title`, or -`CaptionAndTitle`; pass these requests and `InlineBuilder::text()` values to -`BlockBuilder::paragraph_inlines()` or `unordered_list()`. The list constructor -still accepts string items; arrays or vectors of `InlineBuilder` values combine -fragments into one item. Use `InlineBuilder::from()` to mix literal and structured -items in the same list. `CaptionAndTitle` places the captured title outside the -caption link. Explicit display labels take precedence over `reftext`, including -an explicitly empty caption. +`CaptionAndTitle` and returns an `InlineSpec` with an opaque `DisplayRequest`. +The host validates the captured document identity when applying an edit. + +Compose generated content with `InlineSpec::Text`, `LineBreak`, `Display`, and +`Sequence`, then pass it to `BlockBuilder::paragraph_inlines()` or +`unordered_list()`. Strings convert to literal text. Arrays and vectors of +`InlineSpec`, and `FromIterator` over specifications, compose sequences. Nested +and empty sequences add no spacing or breaks. A sequence supplied as one list +item remains one item, including when empty. `InlineSpec::LineBreak` inserts an explicit hard line break. Construction +never interprets text as markup or exposes document storage. + +`CaptionAndTitle` places the captured title outside the caption link. Explicit +display labels take precedence over `reftext`, including an explicitly empty +caption. Choose `Title` when a target has no caption; an explicit caption request without a prefix uses `[id]` rather than the target's generic reference label. diff --git a/acdc-parser/README.md b/acdc-parser/README.md index be4e2fc1a..9dec05e9c 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1760,13 +1760,20 @@ Use `DocumentEditor::capture()` to freeze a target's title, including its raw source, substitution order, formatting, and source-position attributes. A `CapturedTarget` belongs to one working document and remains a snapshot across later edits. Its `display()` method accepts `DisplayIntent::Caption`, `Title`, or -`CaptionAndTitle`; pass these requests and `InlineBuilder::text()` values to -`BlockBuilder::paragraph_inlines()` or `unordered_list()`. The list constructor -still accepts string items; arrays or vectors of `InlineBuilder` values combine -fragments into one item. Use `InlineBuilder::from()` to mix literal and structured -items in the same list. `CaptionAndTitle` places the captured title outside the -caption link. Explicit display labels take precedence over `reftext`, including -an explicitly empty caption. +`CaptionAndTitle` and returns an `InlineSpec` with an opaque `DisplayRequest`. +The host validates the captured document identity when applying an edit. + +Compose generated content with `InlineSpec::Text`, `LineBreak`, `Display`, and +`Sequence`, then pass it to `BlockBuilder::paragraph_inlines()` or +`unordered_list()`. Strings convert to literal text. Arrays and vectors of +`InlineSpec`, and `FromIterator` over specifications, compose sequences. Nested +and empty sequences add no spacing or breaks. A sequence supplied as one list +item remains one item, including when empty. `InlineSpec::LineBreak` inserts an explicit hard line break. Construction +never interprets text as markup or exposes document storage. + +`CaptionAndTitle` places the captured title outside the caption link. Explicit +display labels take precedence over `reftext`, including an explicitly empty +caption. Choose `Title` when a target has no caption; an explicit caption request without a prefix uses `[id]` rather than the target's generic reference label. diff --git a/acdc-parser/src/extensions/builder.rs b/acdc-parser/src/extensions/builder.rs index 25f4154c8..d37670d93 100644 --- a/acdc-parser/src/extensions/builder.rs +++ b/acdc-parser/src/extensions/builder.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use super::InlineBuilder; +use super::InlineSpec; use bumpalo::Bump; use crate::{ @@ -46,8 +46,8 @@ pub struct BlockBuilder { #[derive(Clone, Debug)] pub(crate) enum Content { Paragraph(String), - UnorderedList(Vec), - ParagraphInlines(Vec), + UnorderedList(Vec), + ParagraphInlines(Vec), Image(String), Literal(String), Listing(String), @@ -96,39 +96,42 @@ impl BlockBuilder { /// Build an unordered list with literal text or structured inline content. /// - /// Strings remain literal. Arrays and vectors of [`InlineBuilder`] group - /// fragments into one item; an individual builder can also be an item. + /// Strings remain literal. Arrays and vectors of [`InlineSpec`] group + /// fragments into one item; an individual specification can also be an item. /// /// ``` - /// use acdc_parser::extensions::{BlockBuilder, InlineBuilder}; + /// use acdc_parser::extensions::{BlockBuilder, InlineSpec}; /// /// let literal = BlockBuilder::unordered_list(["One", "Two"]); /// let owned = BlockBuilder::unordered_list(vec![String::from("Owned")]); /// let structured = BlockBuilder::unordered_list([ - /// InlineBuilder::text("Literal *markup*"), - /// InlineBuilder::from([ - /// InlineBuilder::text("Several "), - /// InlineBuilder::text("fragments"), + /// InlineSpec::from("Literal *markup*"), + /// InlineSpec::from([ + /// InlineSpec::from("Several "), + /// InlineSpec::from("fragments"), /// ]), /// ]); /// ``` #[must_use] - pub fn unordered_list(items: impl IntoIterator>) -> Self { + pub fn unordered_list(items: impl IntoIterator>) -> Self { Self::new(Content::UnorderedList( items.into_iter().map(Into::into).collect(), )) } - /// Build a paragraph from literal text and captured display requests. + /// Build a paragraph from literal text, hard breaks, groups, and captured displays. + /// Sequences preserve fragment order without adding spacing or breaks. #[must_use] - pub fn paragraph_inlines(content: impl IntoIterator) -> Self { - Self::new(Content::ParagraphInlines(content.into_iter().collect())) + pub fn paragraph_inlines(content: impl IntoIterator>) -> Self { + Self::new(Content::ParagraphInlines( + content.into_iter().map(Into::into).collect(), + )) } pub(super) fn has_displays(&self) -> bool { match &self.content { Content::ParagraphInlines(content) | Content::UnorderedList(content) => { - content.iter().any(InlineBuilder::has_displays) + content.iter().any(InlineSpec::has_displays) } Content::Paragraph(_) | Content::Image(_) @@ -198,7 +201,7 @@ impl BlockBuilder { location: Location, mut metadata: BlockMetadata<'a>, title: Title<'a>, - mut inline: impl FnMut(InlineBuilder) -> Result>, crate::Error>, + mut inline: impl FnMut(InlineSpec) -> Result>, crate::Error>, ) -> Result, crate::Error> { if let Some(id) = self.id { metadata.id = Some(Anchor::new(arena.alloc_str(&id), location.clone())); diff --git a/acdc-parser/src/extensions/display.rs b/acdc-parser/src/extensions/display.rs index a7d3b270f..2f5bb7179 100644 --- a/acdc-parser/src/extensions/display.rs +++ b/acdc-parser/src/extensions/display.rs @@ -8,14 +8,14 @@ use std::{ use bumpalo::Bump; use crate::{ - Caption, CrossReference, Document, Error, InlineMacro, InlineNode, Plain, SourceLocation, - Title, + Caption, CrossReference, Document, Error, InlineMacro, InlineNode, SourceLocation, Title, ast::{CaptionRef, ContentRef}, grammar::walk_document_inline_nodes_mut, }; use super::{ - DocumentEditor, ExtensionParseResult, TargetId, TitleSource, target::DocumentIdentity, + DocumentEditor, ExtensionParseResult, InlineSpec, TargetId, TitleSource, inline::plain, + target::DocumentIdentity, }; mod prepared; @@ -43,100 +43,34 @@ pub struct CapturedTarget { impl CapturedTarget { /// Describe an inline reference without allocating document storage. #[must_use] - pub fn display(&self, intent: DisplayIntent) -> InlineBuilder { - InlineBuilder(vec![InlineContent::Display(self.clone(), intent)]) + pub fn display(&self, intent: DisplayIntent) -> InlineSpec { + InlineSpec::Display(DisplayRequest { + target: self.clone(), + intent, + }) } } -/// Inline content composed of literal text and symbolic display requests. +/// An opaque captured-target display request for generated inline content. /// -/// Strings become literal text. Arrays and vectors of builders group fragments -/// into one content value without interpreting markup or invoking processors. +/// Create requests through [`CapturedTarget::display`]. The host checks their +/// document identity when applying an edit. Titles remain captured snapshots; +/// captions and output IDs follow surviving targets during finalization. #[derive(Clone, Debug)] -pub struct InlineBuilder(Vec); - -#[derive(Clone, Debug)] -enum InlineContent { - Text(String), - Display(CapturedTarget, DisplayIntent), -} - -impl InlineBuilder { - /// Literal text, escaped by the ordinary converter pipeline. - #[must_use] - pub fn text(text: impl Into) -> Self { - Self(vec![InlineContent::Text(text.into())]) - } - - pub(super) fn has_displays(&self) -> bool { - self.0 - .iter() - .any(|content| matches!(content, InlineContent::Display(..))) - } - - pub(super) fn build<'a>( - self, - arena: &'a Bump, - document: &Document<'a>, - identity: &DocumentIdentity, - origin: &SourceLocation, - ) -> Result>, Error> { - let mut nodes = Vec::new(); - for content in self.0 { - nodes.extend(content.build(arena, document, identity, origin)?); - } - Ok(nodes) - } -} - -impl From for InlineBuilder { - fn from(text: String) -> Self { - Self::text(text) - } -} - -impl From<&str> for InlineBuilder { - fn from(text: &str) -> Self { - Self::text(text) - } -} - -impl From<&String> for InlineBuilder { - fn from(text: &String) -> Self { - Self::text(text) - } -} - -impl FromIterator for InlineBuilder { - fn from_iter>(content: T) -> Self { - Self(content.into_iter().flat_map(|inline| inline.0).collect()) - } -} - -impl From> for InlineBuilder { - fn from(content: Vec) -> Self { - content.into_iter().collect() - } -} - -impl From<[InlineBuilder; N]> for InlineBuilder { - fn from(content: [InlineBuilder; N]) -> Self { - content.into_iter().collect() - } +pub struct DisplayRequest { + target: CapturedTarget, + intent: DisplayIntent, } -impl InlineContent { - fn build<'a>( +impl DisplayRequest { + pub(super) fn build_into<'a>( self, - arena: &'a Bump, document: &Document<'a>, identity: &DocumentIdentity, origin: &SourceLocation, - ) -> Result>, Error> { - let (target, intent) = match self { - InlineContent::Text(text) => return Ok(vec![plain(arena.alloc_str(&text), origin)]), - InlineContent::Display(target, intent) => (target, intent), - }; + nodes: &mut Vec>, + ) -> Result<(), Error> { + let Self { target, intent } = self; if target.document != *identity { return Err(failure( origin, @@ -155,25 +89,17 @@ impl InlineContent { origin: origin.clone(), resolved: None, })); - let mut nodes = vec![InlineNode::Macro(InlineMacro::CrossReference(Box::new( + nodes.push(InlineNode::Macro(InlineMacro::CrossReference(Box::new( xref, - )))]; + )))); if intent == DisplayIntent::CaptionAndTitle && selection.title.is_present() { nodes.push(plain(" ", origin)); nodes.extend(selection.title.as_inlines().iter().cloned()); } - Ok(nodes) + Ok(()) } } -fn plain<'a>(text: &'a str, origin: &SourceLocation) -> InlineNode<'a> { - InlineNode::PlainText(Plain { - content: text, - location: origin.location.clone(), - escaped: true, - }) -} - #[derive(Clone, Debug, PartialEq)] struct Selection<'a> { target: usize, diff --git a/acdc-parser/src/extensions/inline.rs b/acdc-parser/src/extensions/inline.rs new file mode 100644 index 000000000..c1c3bc94f --- /dev/null +++ b/acdc-parser/src/extensions/inline.rs @@ -0,0 +1,132 @@ +//! Owned specifications lowered through the host's checked construction path. + +use bumpalo::Bump; + +use crate::{Document, Error, InlineNode, LineBreak, Plain, SourceLocation}; + +use super::{DisplayRequest, target::DocumentIdentity}; + +/// Declarative input for generated inline content. +/// +/// Text is literal. Sequences preserve fragment order without adding spaces or +/// breaks. A sequence supplied as one list item remains one item, even when empty. +/// The document host allocates nodes and validates captured display requests +/// when applying an edit; creating a specification does not interpret markup. +/// +/// ``` +/// use acdc_parser::extensions::{BlockBuilder, InlineSpec}; +/// +/// let paragraph = BlockBuilder::paragraph_inlines([ +/// InlineSpec::Text("Literal *markup*".into()), +/// InlineSpec::LineBreak, +/// InlineSpec::Sequence(vec!["Second ".into(), "line".into()]), +/// ]); +/// let text = BlockBuilder::paragraph_inlines(["Several ", "fragments"]); +/// let list = BlockBuilder::unordered_list([ +/// InlineSpec::from(["One ".into(), "item".into()]), +/// InlineSpec::Sequence(Vec::new()), +/// ]); +/// ``` +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum InlineSpec { + /// Literal text, escaped by the ordinary converter pipeline. + Text(String), + /// An explicit hard break at the containing generated block's location. + LineBreak, + /// A symbolic reference created by [`super::CapturedTarget::display`]. + Display(DisplayRequest), + /// Transparent composition of zero or more inline specifications. + Sequence(Vec), +} + +impl InlineSpec { + pub(super) fn has_displays(&self) -> bool { + match self { + Self::Text(_) | Self::LineBreak => false, + Self::Display(_) => true, + Self::Sequence(content) => content.iter().any(Self::has_displays), + } + } + + pub(super) fn build<'a>( + self, + arena: &'a Bump, + document: &Document<'a>, + identity: &DocumentIdentity, + origin: &SourceLocation, + ) -> Result>, Error> { + let mut nodes = Vec::new(); + self.build_into(arena, document, identity, origin, &mut nodes)?; + Ok(nodes) + } + + fn build_into<'a>( + self, + arena: &'a Bump, + document: &Document<'a>, + identity: &DocumentIdentity, + origin: &SourceLocation, + nodes: &mut Vec>, + ) -> Result<(), Error> { + match self { + Self::Text(text) => nodes.push(plain(arena.alloc_str(&text), origin)), + Self::LineBreak => { + nodes.push(InlineNode::LineBreak(LineBreak::new( + origin.location.clone(), + ))); + } + Self::Display(request) => request.build_into(document, identity, origin, nodes)?, + Self::Sequence(content) => { + for inline in content { + inline.build_into(arena, document, identity, origin, nodes)?; + } + } + } + Ok(()) + } +} + +impl From for InlineSpec { + fn from(text: String) -> Self { + Self::Text(text) + } +} + +impl From<&str> for InlineSpec { + fn from(text: &str) -> Self { + Self::Text(text.to_owned()) + } +} + +impl From<&String> for InlineSpec { + fn from(text: &String) -> Self { + Self::Text(text.clone()) + } +} + +impl FromIterator for InlineSpec { + fn from_iter>(content: T) -> Self { + Self::Sequence(content.into_iter().collect()) + } +} + +impl From> for InlineSpec { + fn from(content: Vec) -> Self { + Self::Sequence(content) + } +} + +impl From<[Self; N]> for InlineSpec { + fn from(content: [Self; N]) -> Self { + content.into_iter().collect() + } +} + +pub(super) fn plain<'a>(text: &'a str, origin: &SourceLocation) -> InlineNode<'a> { + InlineNode::PlainText(Plain { + content: text, + location: origin.location.clone(), + escaped: true, + }) +} diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 526a809c2..b4ae8ec2e 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -86,7 +86,8 @@ //! //! [`DocumentEditor::capture`] freezes a title and its source context. Use //! [`CapturedTarget::display`] with [`BlockBuilder::paragraph_inlines`] or -//! [`BlockBuilder::unordered_list`] for explicit caption/title links. +//! [`BlockBuilder::unordered_list`] for explicit caption/title links. Compose +//! these requests with literal text, hard breaks, and groups through [`InlineSpec`]. //! Finalization follows surviving handles and their latest caption data, without //! refreshing captured titles. Converter core prepares a fresh ordinary document //! through [`PreparedDocument`] before traversal; the shared parse stays unchanged. @@ -160,6 +161,7 @@ mod deferred; mod display; mod editor; pub(crate) mod finalization; +mod inline; mod query; mod recognition; mod registry; @@ -178,11 +180,12 @@ pub use builder::BlockBuilder; pub(crate) use builder::SourceContext; pub use deferred::{DeferredBlock, ExtensionBlock, PlaceholderId}; pub use display::{ - CapturedTarget, DisplayIntent, DisplayLabel, GeneratedDisplayRef, InlineBuilder, + CapturedTarget, DisplayIntent, DisplayLabel, DisplayRequest, GeneratedDisplayRef, PreparedDocument, }; pub(crate) use display::{DisplayState, GeneratedDisplay}; pub use editor::DocumentEditor; +pub use inline::InlineSpec; pub use query::{BlockContext, BlockView, DocumentQuery}; pub use registry::{RegistrationError, Registry, RegistryBuilder}; pub use session::ExtensionParseResult; diff --git a/acdc-parser/src/extensions/tests/construction.rs b/acdc-parser/src/extensions/tests/construction.rs index fc49ac1be..e64af74cc 100644 --- a/acdc-parser/src/extensions/tests/construction.rs +++ b/acdc-parser/src/extensions/tests/construction.rs @@ -2,9 +2,112 @@ use super::{TestResult, support}; use acdc_parser::{ CaptionKind, CompatibilityMode, Options, WarningKind, ast::{BlockKind, CaptionRef, InlineKind}, - extensions::{BlockBuilder, BlockContext, DocumentEditor}, + extensions::{BlockBuilder, BlockContext, DocumentEditor, InlineSpec}, }; +#[test] +fn extensions_generated_paragraph_has_explicit_located_line_breaks() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse("Before.\n\nReplace me.", &options)?; + let target = result + .query() + .blocks() + .last() + .ok_or("target")? + .target() + .clone(); + let origin = result + .query() + .get(&target) + .ok_or("target")? + .source_location(); + DocumentEditor::new(&mut result).replace_block( + &target, + BlockBuilder::paragraph_inlines([ + InlineSpec::Text("*literal* <&>".into()), + InlineSpec::LineBreak, + InlineSpec::Text("Second".into()), + InlineSpec::LineBreak, + ]), + )?; + result.normalize()?; + let parsed = result.finish()?; + let BlockKind::Paragraph(paragraph) = + parsed.document().blocks().last().ok_or("paragraph")?.kind() + else { + return Err("paragraph kind".into()); + }; + let nodes: Vec<_> = paragraph.content().inlines().collect(); + assert_eq!(nodes.len(), 4); + assert!( + matches!(nodes[0].kind(), InlineKind::Plain(text) if text.text() == "*literal* <&>") + ); + for node in [nodes[1], nodes[3]] { + assert!(matches!(node.kind(), InlineKind::LineBreak(_))); + assert_eq!( + acdc_parser::Location::from(node.location()), + origin.location + ); + } + } + Ok(()) +} + +#[test] +fn extensions_inline_sequences_preserve_paragraph_order_and_literal_text() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse("Replace me.", &options)?; + let target = result + .query() + .blocks() + .next() + .ok_or("target")? + .target() + .clone(); + let collected: InlineSpec = [ + InlineSpec::Text("*literal* <&> {counter:x}".into()), + InlineSpec::LineBreak, + ] + .into_iter() + .collect(); + DocumentEditor::new(&mut result).replace_block( + &target, + BlockBuilder::paragraph_inlines([ + InlineSpec::from("Before "), + InlineSpec::Sequence(vec![ + InlineSpec::Sequence(Vec::new()), + InlineSpec::Sequence(vec![collected]), + ]), + InlineSpec::from([InlineSpec::from("after")]), + ]), + )?; + let parsed = result.finish()?; + assert_eq!(parsed.warnings(), []); + let BlockKind::Paragraph(paragraph) = + parsed.document().blocks().next().ok_or("output")?.kind() + else { + return Err("paragraph".into()); + }; + let mut content = paragraph.content().inlines(); + for expected in ["Before ", "*literal* <&> {counter:x}"] { + assert!( + matches!(content.next().ok_or("literal")?.kind(), InlineKind::Plain(text) if text.text() == expected) + ); + } + assert!(matches!( + content.next().ok_or("break")?.kind(), + InlineKind::LineBreak(_) + )); + assert!( + matches!(content.next().ok_or("suffix")?.kind(), InlineKind::Plain(text) if text.text() == "after") + ); + assert!(content.next().is_none()); + } + Ok(()) +} + #[test] fn extensions_image_replacement_preserves_identity_title_and_source_context() -> TestResult { for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { diff --git a/acdc-parser/src/extensions/tests/display.rs b/acdc-parser/src/extensions/tests/display.rs index 8d9907ba4..59c0f3c03 100644 --- a/acdc-parser/src/extensions/tests/display.rs +++ b/acdc-parser/src/extensions/tests/display.rs @@ -3,7 +3,7 @@ use acdc_parser::{ CompatibilityMode, Options, WarningKind, ast::{BlockKind, InlineKind}, extensions::{ - BlockBuilder, BlockContext, DisplayIntent, DisplayLabel, DocumentEditor, InlineBuilder, + BlockBuilder, BlockContext, DisplayIntent, DisplayLabel, DocumentEditor, InlineSpec, PreparedDocument, TitleSource, }, }; @@ -40,15 +40,15 @@ fn extensions_unordered_list_combines_literal_and_grouped_display_items() -> Tes editor.replace_block( &output, BlockBuilder::unordered_list([ - InlineBuilder::from(owned.clone()), - InlineBuilder::from(&owned), - InlineBuilder::from(owned.as_str()), - InlineBuilder::from([ - InlineBuilder::text("Before "), - InlineBuilder::from(vec![captured.display(DisplayIntent::Title)]), - InlineBuilder::text(" after"), + InlineSpec::from(owned.clone()), + InlineSpec::from(&owned), + InlineSpec::from(owned.as_str()), + InlineSpec::Sequence(vec![ + InlineSpec::from("Before "), + InlineSpec::from(vec![captured.display(DisplayIntent::Title)]), + InlineSpec::from(" after"), ]), - InlineBuilder::from(Vec::new()), + InlineSpec::from(Vec::new()), ]), )?; let parsed = result.finish()?; @@ -280,7 +280,13 @@ fn extensions_foreign_display_is_rejected_atomically() -> TestResult { let before = serde_json::to_value(second.parsed.document())?; let error = DocumentEditor::new(&mut second).replace_block( &output, - BlockBuilder::paragraph_inlines([captured.display(DisplayIntent::Title)]), + BlockBuilder::paragraph_inlines([ + InlineSpec::Text("Before the rejected request".into()), + InlineSpec::Sequence(vec![ + InlineSpec::LineBreak, + InlineSpec::Sequence(vec![captured.display(DisplayIntent::Title)]), + ]), + ]), ); assert!(error.is_err()); assert_eq!(serde_json::to_value(second.parsed.document())?, before); From 4a3c2d98752673c463e9b4269f057c64d1b8d6fc Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Mon, 16 Nov 2026 20:41:54 +0100 Subject: [PATCH 24/55] feat(extensions): retain macro calls for located literal recovery Retain accepted macro text before target expansion and argument interpretation, following ordinary table-cell escape rules. Make the same source available to committed callbacks and deferred processors. Allow tree processors to report located recoverable warnings that survive later edits. Cover quoted arguments, positional holes, expanded targets, cell parsing paths, warning deduplication, and invalid target rejection. SC-542 --- acdc-parser/CHANGELOG.md | 4 ++ acdc-parser/README.adoc | 10 +++ acdc-parser/README.md | 10 +++ acdc-parser/src/extensions/block_macro.rs | 6 ++ acdc-parser/src/extensions/editor.rs | 19 +++++- acdc-parser/src/extensions/recognition.rs | 2 + .../src/extensions/tests/construction.rs | 40 ++++++++++++ .../src/extensions/tests/invocations.rs | 65 +++++++++++++++++++ acdc-parser/src/extensions/tests/mod.rs | 1 + 9 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 acdc-parser/src/extensions/tests/invocations.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index d8a2c6ebb..a6903f5b8 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -11,6 +11,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 and grouped fragments through `InlineSpec` in generated paragraphs and list items. +- Registered block macros retain their accepted call text, including quoted + arguments and unexpanded targets, for literal recovery. Tree processors can + also report source-located recoverable warnings. + - Registered extensions now support reader input, including source-ordered callback attribute changes before later conditionals and includes. Applications can compose registries in order with duplicate-name checks before parsing. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 00cf750fa..088e3cd66 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2097,6 +2097,12 @@ separate `remove_section()` operation. Tree processors run once in registration order and observe earlier edits; copied selections and generated summaries remain snapshots and are not rerun. +`MacroInvocation::source` retains the accepted call from its name through the +closing bracket, before target expansion and argument interpretation. Table-cell +escapes follow the ordinary cell rules. It preserves arguments, quoting, spacing, +and empty slots; outer block metadata and trailing content are excluded. Callbacks and deferred processors can return +this source as literal text without reconstructing the call from resolved values. + `BlockBuilder` builds paragraphs, unordered lists, images, listings, and literal blocks. Body strings remain literal and converters apply ordinary output escaping. `with_attributes()` interprets one attribute-list line, without square brackets, @@ -2133,6 +2139,10 @@ caption. Choose `Title` when a target has no caption; an explicit caption request without a prefix uses `[id]` rather than the target's generic reference label. +`DocumentEditor::warn()` records a recoverable warning at a live target's source +location. Repeated messages at the same location are coalesced; diagnostics +survive later edits and target removal. Foreign or removed targets are rejected. + `finish()` binds requests to surviving handles and their final caption data, following renamed output IDs without repeating selection or callbacks. A removed handle adds a located unresolved-reference warning and retains a missing target, diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 9dec05e9c..e48d501c6 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1741,6 +1741,12 @@ separate `remove_section()` operation. Tree processors run once in registration order and observe earlier edits; copied selections and generated summaries remain snapshots and are not rerun. +`MacroInvocation::source` retains the accepted call from its name through the +closing bracket, before target expansion and argument interpretation. Table-cell +escapes follow the ordinary cell rules. It preserves arguments, quoting, spacing, +and empty slots; outer block metadata and trailing content are excluded. Callbacks and deferred processors can return +this source as literal text without reconstructing the call from resolved values. + `BlockBuilder` builds paragraphs, unordered lists, images, listings, and literal blocks. Body strings remain literal and converters apply ordinary output escaping. `with_attributes()` interprets one attribute-list line, without square brackets, @@ -1777,6 +1783,10 @@ caption. Choose `Title` when a target has no caption; an explicit caption request without a prefix uses `[id]` rather than the target's generic reference label. +`DocumentEditor::warn()` records a recoverable warning at a live target's source +location. Repeated messages at the same location are coalesced; diagnostics +survive later edits and target removal. Foreign or removed targets are rejected. + `finish()` binds requests to surviving handles and their final caption data, following renamed output IDs without repeating selection or callbacks. A removed handle adds a located unresolved-reference warning and retains a missing target, diff --git a/acdc-parser/src/extensions/block_macro.rs b/acdc-parser/src/extensions/block_macro.rs index 98ae43692..88dbe0077 100644 --- a/acdc-parser/src/extensions/block_macro.rs +++ b/acdc-parser/src/extensions/block_macro.rs @@ -103,6 +103,11 @@ impl BlockMacro { #[non_exhaustive] pub struct MacroInvocation<'a> { pub name: Cow<'a, str>, + /// The accepted call from its name through the closing bracket, before + /// target expansion and argument interpretation. Table-cell escapes follow + /// the ordinary cell rules. Outer block metadata and trailing content are + /// excluded. Quotes, spacing, and argument slots remain. + pub source: Cow<'a, str>, pub target: Cow<'a, str>, pub positional: Vec>>, pub attributes: ElementAttributes<'a>, @@ -179,6 +184,7 @@ impl MacroInvocation<'_> { pub(super) fn to_owned_invocation(&self) -> MacroInvocation<'static> { MacroInvocation { name: Cow::Owned(self.name.to_string()), + source: Cow::Owned(self.source.to_string()), target: Cow::Owned(self.target.to_string()), positional: self .positional diff --git a/acdc-parser/src/extensions/editor.rs b/acdc-parser/src/extensions/editor.rs index 10d505bb4..f11957bad 100644 --- a/acdc-parser/src/extensions/editor.rs +++ b/acdc-parser/src/extensions/editor.rs @@ -2,7 +2,7 @@ use super::{ BlockBuilder, DeferredBlock, DocumentQuery, ExtensionParseResult, TargetId, traversal::BlockPath, }; -use crate::{Block, Error, SourceLocation}; +use crate::{Block, Error, SourceLocation, Warning, WarningKind}; mod transaction; use transaction::Edit; @@ -31,6 +31,23 @@ impl<'doc> DocumentEditor<'doc> { self.result.deferred_blocks() } + /// Record a recoverable problem at a live target's source location. + /// Identical messages at the same location are coalesced. Later edits retain + /// the diagnostic, including when its target is removed. + /// + /// # Errors + /// Rejects foreign or removed targets without adding a warning. + pub fn warn(&mut self, target: &TargetId, message: impl Into) -> Result<(), Error> { + self.path(target)?; + let warning = Warning::new( + WarningKind::Other(message.into().into()), + Some(self.location(target)), + ); + warning.emit_trace(); + self.result.parsed.append_extension_warnings(vec![warning]); + Ok(()) + } + /// Return or assign an output ID without changing identity or numbering. /// /// # Errors diff --git a/acdc-parser/src/extensions/recognition.rs b/acdc-parser/src/extensions/recognition.rs index 95aed44a3..ae85dd867 100644 --- a/acdc-parser/src/extensions/recognition.rs +++ b/acdc-parser/src/extensions/recognition.rs @@ -34,6 +34,7 @@ pub(crate) fn recognize<'a>( }; let target = decode(target); let arguments = decode(arguments); + let source = format!("{name}::{target}[{arguments}]"); let target = state.intern_cow(apply_attribute_substitutions( target, &[Substitution::Attributes], @@ -84,6 +85,7 @@ pub(crate) fn recognize<'a>( title, invocation: MacroInvocation { name: Cow::Borrowed(name), + source: Cow::Owned(source), target: Cow::Borrowed(target), positional: positional .into_iter() diff --git a/acdc-parser/src/extensions/tests/construction.rs b/acdc-parser/src/extensions/tests/construction.rs index e64af74cc..587bdfc14 100644 --- a/acdc-parser/src/extensions/tests/construction.rs +++ b/acdc-parser/src/extensions/tests/construction.rs @@ -108,6 +108,46 @@ fn extensions_inline_sequences_preserve_paragraph_order_and_literal_text() -> Te Ok(()) } +#[test] +fn extensions_located_warnings_survive_edits_and_reject_foreign_targets() -> TestResult { + let options = Options::default(); + let mut result = support::registry().parse("Before.\n\n== Remove\n\nBody.", &options)?; + let other = support::registry().parse("Foreign.", &options)?; + let foreign = other + .query() + .blocks() + .next() + .ok_or("foreign")? + .target() + .clone(); + let target = result + .query() + .select(BlockContext::Section) + .next() + .ok_or("section")? + .target() + .clone(); + let origin = result + .query() + .get(&target) + .ok_or("target")? + .source_location(); + let mut editor = DocumentEditor::new(&mut result); + assert!(editor.warn(&foreign, "foreign warning").is_err()); + editor.warn(&target, "recoverable extension problem")?; + editor.warn(&target, "recoverable extension problem")?; + editor.remove_section(&target)?; + assert!(editor.warn(&target, "removed warning").is_err()); + result.normalize()?; + let parsed = result.finish()?; + assert_eq!(parsed.warnings().len(), 1); + assert_eq!(parsed.warnings()[0].source_location(), Some(&origin)); + assert!( + matches!(&parsed.warnings()[0].kind, WarningKind::Other(message) if message == "recoverable extension problem") + ); + Ok(()) +} + #[test] fn extensions_image_replacement_preserves_identity_title_and_source_context() -> TestResult { for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { diff --git a/acdc-parser/src/extensions/tests/invocations.rs b/acdc-parser/src/extensions/tests/invocations.rs new file mode 100644 index 000000000..ae3a1485d --- /dev/null +++ b/acdc-parser/src/extensions/tests/invocations.rs @@ -0,0 +1,65 @@ +use super::{TestResult, paragraph_text, support}; +use acdc_parser::{ + CompatibilityMode, Options, + extensions::{BlockMacro, BlockMacroOutput, MacroExecutionContext, MacroInvocation, Registry}, +}; + +#[test] +fn extensions_invocations_preserve_source_before_target_expansion() -> TestResult { + const CALL: &str = r#"source::{which}[first,,'third,slot',custom="x,y",path='a\b']"#; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("source", || { + |invocation: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { + assert_eq!(invocation.source, CALL); + assert_eq!(invocation.target, "expanded"); + assert_eq!( + invocation + .positional + .iter() + .map(|slot| slot.as_deref()) + .collect::>(), + vec![Some("first"), None, Some("third,slot")] + ); + Ok(BlockMacroOutput::Paragraph(invocation.source.to_string())) + } + }))?; + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = builder + .build() + .parse(&format!("= Document\n:which: expanded\n\n{CALL}"), &options)? + .finish()?; + assert_eq!(result.warnings(), []); + let block = result.document_storage().blocks.first().ok_or("output")?; + assert_eq!(paragraph_text(block), CALL); + } + Ok(()) +} + +#[test] +fn extensions_deferred_source_keeps_quotes_slots_and_normal_cell_escapes() -> TestResult { + let calls = [ + r#"defer::target[first,,'third,slot',custom="x,y"]"#, + r#"defer::target[custom="a\|b"]"#, + ]; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for call in calls { + for input in [ + format!("= Document\n\n{call}"), + format!("[cols=a]\n|===\n|{call}\n|==="), + format!("[cols=a]\n|===\n|{call}\n\nifdef::never[]\nIgnored\nendif::[]\n|==="), + ] { + let result = support::registry().parse(&input, &options)?; + let request = result.deferred_blocks().first().ok_or("deferred")?; + let expected = if input.starts_with("[cols=a]") { + call.replace("\\|", "|") + } else { + call.to_owned() + }; + assert_eq!(request.invocation.source, expected, "{mode:?}: {input}"); + } + } + } + Ok(()) +} diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index df0ffc450..a8622b32c 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -26,6 +26,7 @@ mod queries; mod construction; mod display; +mod invocations; mod title_sources; #[path = "tree_processors.rs"] From 866c56a712b6410189605203fc683b56d57c33f2 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Wed, 18 Nov 2026 18:08:24 +0100 Subject: [PATCH 25/55] fix(converters): honor scoped attributes in native block renderers Use the active traversal when rendering terminal previews so body assignments and table-cell overrides take effect at the block. --- ARCHITECTURE.adoc | 6 ++++-- converters/core/CHANGELOG.md | 6 ++++++ converters/core/src/render.rs | 21 ++++++++------------- converters/html/CHANGELOG.md | 3 +++ converters/html/src/extensions.rs | 17 +++++++++-------- 5 files changed, 30 insertions(+), 23 deletions(-) diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc index 47ccb5ec7..e8f33a6b4 100644 --- a/ARCHITECTURE.adoc +++ b/ARCHITECTURE.adoc @@ -138,8 +138,10 @@ handlers per conversion. `Extensions` combines parser and renderer capabilities; renderer-only selections retain ordinary parsing. Backends dispatch selected renderers in order and use ordinary rendering when every handler declines. HTML supplies streaming output, diagnostics, metadata escaping, and caption/title -services. Selected renderers supply their CSP script hashes. No handler can edit -the shared parsed document through this rendering interface. +services. Renderers read attributes from the active traversal so accepted body +assignments apply in source order and cell-local values expire on exit. Selected +renderers supply their CSP script hashes. No handler can edit the shared parsed +document through this rendering interface. ==== Inline preprocessing diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index 908dbb120..7bef30619 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Native block renderers can read the attributes in effect at the block, + including accepted body assignments and local table-cell settings. + Implementations of `RenderHost::document_attributes` now return a reference + to the current `TraversalContext`. Callers of `RenderHost::output` now + destructure the returned writer, diagnostics, and traversal context. + - Native extensions can register backend-specific block renderers alongside parser processors. Selection creates fresh render handlers for every conversion, retains structured warnings, and lets the backend render titles and metadata. diff --git a/converters/core/src/render.rs b/converters/core/src/render.rs index 8d9ace8d7..ae8805a05 100644 --- a/converters/core/src/render.rs +++ b/converters/core/src/render.rs @@ -2,9 +2,9 @@ use std::{fmt, io::Write, sync::Arc}; -use acdc_parser::{DocumentAttributes, ast::BlockRef}; +use acdc_parser::ast::BlockRef; -use crate::{Diagnostics, Options}; +use crate::{Diagnostics, Options, TraversalContext}; /// A native renderer or host-service failure, preserving its original source. pub type RenderError = Box; @@ -63,8 +63,8 @@ pub trait BlockRenderProcessor { pub trait RenderHost { /// Current backend variant, such as `html5` or `html5s`. fn variant(&self) -> &str; - /// Backend document attributes with parsed values and assignment metadata. - fn document_attributes(&self) -> &DocumentAttributes<'_>; + /// Attributes in effect at this block, including body and table-cell assignments. + fn document_attributes(&self) -> &TraversalContext<'_>; /// Validated application options, including safe mode. fn options(&self) -> &Options; /// Open a backend element with the block's ID, roles, and default classes. @@ -84,20 +84,15 @@ pub trait RenderHost { /// Returns title-rendering or output errors. fn title(&mut self, block: BlockRef<'_>, prefix: &str, suffix: &str) -> Result<(), RenderError>; - /// Borrow output and its structured diagnostics together, without buffering. - /// - /// # Errors - /// Preserves failures returned by the operation. - fn output( - &mut self, - operation: &mut dyn FnMut(&mut dyn Write, &mut Diagnostics<'_>) -> Result<(), RenderError>, - ) -> Result<(), RenderError>; + /// Borrow output, structured diagnostics, and the current traversal together. + fn output(&mut self) -> (&mut dyn Write, Diagnostics<'_>, &TraversalContext<'_>); /// Write trusted backend output. /// /// # Errors /// Returns output errors. fn write(&mut self, bytes: &[u8]) -> Result<(), RenderError> { - self.output(&mut |writer, _| Ok(writer.write_all(bytes)?)) + let (writer, _, _) = self.output(); + Ok(writer.write_all(bytes)?) } } diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index 6f8f1304d..a08d82b14 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Native HTML renderers now observe body attribute changes in source order + and restore the enclosing settings after each AsciiDoc table cell. + - HTML callers can select native block renderers. Their CSP script hashes are included in the document policy. Native renderer failures are exposed through `Error::Extension` with their original error source. diff --git a/converters/html/src/extensions.rs b/converters/html/src/extensions.rs index b2edbd545..8c81907fb 100644 --- a/converters/html/src/extensions.rs +++ b/converters/html/src/extensions.rs @@ -6,7 +6,7 @@ use acdc_converters_core::{ Diagnostics, Options, TraversalContext, render::{RenderError, RenderHost}, }; -use acdc_parser::{CaptionKind, DocumentAttributes, ast::BlockRef}; +use acdc_parser::{CaptionKind, ast::BlockRef}; use crate::{ Error, HtmlVariant, HtmlVisitor, @@ -44,8 +44,8 @@ impl RenderHost for Host<'_, '_, '_, W> { fn variant(&self) -> &str { self.visitor.converter.variant.backend_profile().backend() } - fn document_attributes(&self) -> &DocumentAttributes<'_> { - self.visitor.converter.document_attributes() + fn document_attributes(&self) -> &TraversalContext<'_> { + self.traversal } fn options(&self) -> &Options { &self.visitor.converter.options @@ -87,10 +87,11 @@ impl RenderHost for Host<'_, '_, '_, W> { Ok(()) } - fn output( - &mut self, - operation: &mut dyn FnMut(&mut dyn Write, &mut Diagnostics<'_>) -> Result<(), RenderError>, - ) -> Result<(), RenderError> { - operation(&mut self.visitor.writer, &mut self.visitor.diagnostics) + fn output(&mut self) -> (&mut dyn Write, Diagnostics<'_>, &TraversalContext<'_>) { + ( + &mut self.visitor.writer, + self.visitor.diagnostics.reborrow(), + self.traversal, + ) } } From d519e7c1c225419901d59f80b2c2c3ddc0921fdb Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Wed, 18 Nov 2026 18:09:01 +0100 Subject: [PATCH 26/55] perf(parser): streamline block metadata and author name parsing Use document defaults for blocks without metadata and avoid rebuilding author name components when parsing headers. --- acdc-parser/CHANGELOG.md | 2 ++ acdc-parser/src/author_attributes.rs | 44 +++++++++++-------------- acdc-parser/src/extensions/tests/mod.rs | 9 +++++ acdc-parser/src/grammar/document/peg.rs | 11 ++++++- 4 files changed, 41 insertions(+), 25 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index a6903f5b8..202b4968d 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Reduced parsing overhead for nested blocks and author headers. + - Native extensions can compose literal text, hard breaks, captured target links, and grouped fragments through `InlineSpec` in generated paragraphs and list items. diff --git a/acdc-parser/src/author_attributes.rs b/acdc-parser/src/author_attributes.rs index f88aa5f28..ab529d1b6 100644 --- a/acdc-parser/src/author_attributes.rs +++ b/acdc-parser/src/author_attributes.rs @@ -58,7 +58,13 @@ pub(crate) fn set_author_attrs<'a>( } pub(crate) fn build_author_full_name(author: &Author) -> String { - let mut name = author.first_name.to_string(); + let mut name = String::with_capacity( + author.first_name.len() + + author.middle_name.map_or(0, |middle| middle.len() + 1) + + author.last_name.len() + + 1, + ); + name.push_str(author.first_name); if let Some(middle) = &author.middle_name { name.push(' '); name.push_str(middle); @@ -89,33 +95,23 @@ fn write_author_attrs<'a>( } }; assign("authors".into(), all_names.join(", ").into()); - for (i, author) in authors.iter().enumerate() { - let suffix = if i == 0 { - String::new() - } else { - format!("_{}", i + 1) + for (i, (author, full_name)) in authors.iter().zip(all_names).enumerate() { + let field = |name: &'static str| -> AttributeName<'a> { + if i == 0 { + name.into() + } else { + format!("{name}_{}", i + 1).into() + } }; - assign( - format!("author{suffix}").into(), - build_author_full_name(author).into(), - ); - assign( - format!("firstname{suffix}").into(), - Cow::Borrowed(author.first_name), - ); + assign(field("author"), full_name.into()); + assign(field("firstname"), Cow::Borrowed(author.first_name)); if let Some(middle) = author.middle_name { - assign(format!("middlename{suffix}").into(), Cow::Borrowed(middle)); + assign(field("middlename"), Cow::Borrowed(middle)); } - assign( - format!("lastname{suffix}").into(), - Cow::Borrowed(author.last_name), - ); - assign( - format!("authorinitials{suffix}").into(), - Cow::Borrowed(author.initials), - ); + assign(field("lastname"), Cow::Borrowed(author.last_name)); + assign(field("authorinitials"), Cow::Borrowed(author.initials)); if let Some(email) = author.email { - assign(format!("email{suffix}").into(), Cow::Borrowed(email)); + assign(field("email"), Cow::Borrowed(email)); } } } diff --git a/acdc-parser/src/extensions/tests/mod.rs b/acdc-parser/src/extensions/tests/mod.rs index a8622b32c..166929499 100644 --- a/acdc-parser/src/extensions/tests/mod.rs +++ b/acdc-parser/src/extensions/tests/mod.rs @@ -246,6 +246,15 @@ impl BlockMacroProcessor for Never { #[test] fn extensions_empty_or_unused_registry_preserves_document_and_warnings() -> TestResult { + // Full document equality includes clock-derived intrinsic attributes on each parse. + if std::env::var("SOURCE_DATE_EPOCH").as_deref() != Ok("0") { + let status = std::process::Command::new(std::env::current_exe()?) + .args(["--exact", "extensions::tests::extensions_empty_or_unused_registry_preserves_document_and_warnings"]) + .env("SOURCE_DATE_EPOCH", "0") + .status()?; + assert!(status.success()); + return Ok(()); + } let options = Options::default(); for input in [ include_str!("../../../fixtures/tests/xref_nested_sections.adoc"), diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index a04f62fac..c0c9cd4d6 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -1317,7 +1317,16 @@ peg::parser! { = metadata:block_metadata_with_title(offset, parent_section_level, false) { metadata } rule block_metadata_with_title(offset: usize, parent_section_level: Option, parse_title: bool) -> Result, Error> - = meta_start:position!() lines:block_metadata_lines(offset) + // Media macros and Markdown fences can supply their own attributes. + // Other blocks without a metadata prefix use the document defaults directly. + = !block_metadata_line_match() !media_block_ahead_true() !markdown_code_delimiter() { + let mut metadata = BlockParsingMetadata::new(state.options.compatibility_mode); + metadata.metadata.source_context = crate::extensions::SourceContext::capture(state); + metadata.parent_section_level = parent_section_level; + metadata.hardbreaks = state.hardbreaks && metadata.substitutions.enabled(&Substitution::PostReplacements); + Ok(metadata) + } + / meta_start:position!() lines:block_metadata_lines(offset) block_start:position!() media_ahead:media_block_ahead() form:attribute_block_form(offset) { let mut attributes = ParsedAttributeList::default(); From 092fa61d5e3aef90e785928ee8e7e98a3e7ffc83 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Wed, 18 Nov 2026 18:09:10 +0100 Subject: [PATCH 27/55] perf(parser): avoid copying the document for each checked edit Roll back local replacements on failure and keep reference and footnote repair consistent across edits. Cover repeated list generation with an allocation regression test. --- acdc-parser/CHANGELOG.md | 2 + .../src/extensions/editor/transaction.rs | 69 ++++++++++--------- acdc-parser/src/extensions/finalization.rs | 40 +++++------ .../src/extensions/tests/construction.rs | 46 +++++++++++++ acdc-parser/src/grammar/footnotes.rs | 35 +++++++--- acdc-parser/src/grammar/location_walk.rs | 31 +++++++++ acdc-parser/src/model/section.rs | 17 ++--- 7 files changed, 170 insertions(+), 70 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 202b4968d..e3c65f05a 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Reduced parsing overhead for nested blocks and author headers. +- Reduced allocation traffic when tree processors repeatedly edit a document. + - Native extensions can compose literal text, hard breaks, captured target links, and grouped fragments through `InlineSpec` in generated paragraphs and list items. diff --git a/acdc-parser/src/extensions/editor/transaction.rs b/acdc-parser/src/extensions/editor/transaction.rs index 8b2163dfd..f7bd4a092 100644 --- a/acdc-parser/src/extensions/editor/transaction.rs +++ b/acdc-parser/src/extensions/editor/transaction.rs @@ -30,11 +30,10 @@ impl DocumentEditor<'_> { let (new_target, reference_warnings, construction_warnings) = self.result.parsed.with_document_mut(|owner, document| { let prepared = prepare(owner, document, &path, edit, mode, &origin, &identity)?; - let mut candidate = snapshot(document); let mut candidate_index = index.clone(); - candidate_index.prepare_edit(&mut candidate); + candidate_index.prepare_edit(document); let outcome = transact( - &mut candidate, + document, &mut candidate_index, target, &path, @@ -42,7 +41,6 @@ impl DocumentEditor<'_> { prepared, &origin, )?; - *document = candidate; *index = candidate_index; Ok::<_, Error>(outcome) })?; @@ -67,20 +65,6 @@ impl DocumentEditor<'_> { } } -fn snapshot<'a>(document: &Document<'a>) -> Document<'a> { - Document { - generated_displays: document.generated_displays.clone(), - header: document.header.clone(), - untitled_header_location: document.untitled_header_location.clone(), - attributes: document.attributes.clone(), - blocks: document.blocks.clone(), - footnotes: document.footnotes.clone(), - toc_entries: document.toc_entries.clone(), - references: document.references.clone(), - location: document.location.clone(), - } -} - struct Prepared<'a> { block: Block<'a>, kind: Option, @@ -266,9 +250,7 @@ fn transact<'a>( mut prepared: Option>, origin: &SourceLocation, ) -> Result { - if prepared.as_ref().is_some_and(|prepared| prepared.displays) { - document.generated_displays.activate(); - } + let displays = prepared.as_ref().is_some_and(|prepared| prepared.displays); if let Some(prepared) = &mut prepared && prepared.recaption { @@ -280,34 +262,55 @@ fn transact<'a>( let warnings = prepared .as_mut() .map_or_else(Vec::new, |prepared| std::mem::take(&mut prepared.warnings)); - let handle = match edit { + // The staged index can be discarded. Keep the displaced block so an + // unsuccessful catalog repair only needs to undo this one splice. + let (handle, previous) = match edit { Edit::Insert(_) => { + let handle = index + .insert_before(target) + .ok_or_else(|| failure(origin, "target is absent"))?; blocks.insert( position, prepared .ok_or_else(|| failure(origin, "construction is absent"))? .block, ); - index - .insert_before(target) - .ok_or_else(|| failure(origin, "target is absent"))? + (handle, None) } Edit::Replace(_) => { - *blocks + let old = blocks .get_mut(position) - .ok_or_else(|| failure(origin, "target is absent"))? = prepared - .ok_or_else(|| failure(origin, "construction is absent"))? - .block; + .ok_or_else(|| failure(origin, "target is absent"))?; + let previous = std::mem::replace( + old, + prepared + .ok_or_else(|| failure(origin, "construction is absent"))? + .block, + ); index.replace(target); - target.clone() + (target.clone(), Some(previous)) } Edit::Remove => { - blocks.remove(position); index.remove(target); - target.clone() + (target.clone(), Some(blocks.remove(position))) } }; - Ok((handle, repair_document(document, Some(index))?, warnings)) + let references = match repair_document(document, Some(index)) { + Ok(warnings) => warnings, + Err(error) => { + // Repair is atomic and cannot move the parent container. + let (blocks, position) = path + .container_mut(&mut document.blocks) + .ok_or_else(|| failure(origin, "target container is absent"))?; + let inserted = usize::from(!matches!(edit, Edit::Remove)); + blocks.splice(position..position + inserted, previous); + return Err(error); + } + }; + if displays { + document.generated_displays.activate(); + } + Ok((handle, references, warnings)) } fn caption( diff --git a/acdc-parser/src/extensions/finalization.rs b/acdc-parser/src/extensions/finalization.rs index 9a2925cae..15ae4ddf3 100644 --- a/acdc-parser/src/extensions/finalization.rs +++ b/acdc-parser/src/extensions/finalization.rs @@ -6,7 +6,6 @@ use crate::{ #[derive(Default)] struct Uses<'a> { - xrefs: Vec<(&'a str, crate::Location)>, seen: std::collections::HashMap<&'a str, crate::Location>, warnings: Vec, } @@ -73,12 +72,17 @@ pub(super) fn repair_document( document: &mut crate::Document<'_>, index: Option<&super::query::TargetIndex>, ) -> Result, Error> { - document - .rebuild_footnotes() + let mut repaired = document + .with_repaired_footnotes() .map_err(|error| failure(document, error))?; - document + let candidate = repaired.as_mut().unwrap_or(document); + candidate .rebuild_extension_references() - .map_err(|error| failure(document, error))?; + .map_err(|error| failure(candidate, error))?; + if let Some(repaired) = repaired { + document.commit_repair(repaired); + } + if let Some(index) = index { index.repair_section_references(document); } @@ -88,28 +92,24 @@ pub(super) fn repair_document( } reference_walk::blocks(&mut uses, &mut document.blocks, true) .unwrap_or_else(|never| match never {}); + let ids: std::collections::HashSet<_> = document.references.keys().copied().collect(); crate::grammar::walk_document_inline_nodes_mut(document, &mut |inline| { if let crate::InlineNode::Macro(crate::InlineMacro::CrossReference(reference)) = inline && (reference.target_is_local || reference.source_syntax.target_is_local(reference.target)) + && !ids.contains(reference.target) { - uses.xrefs - .push((reference.target, reference.location.clone())); + uses.warnings.push(Warning::new( + WarningKind::UnresolvedReference { + target: reference.target.into(), + }, + Some(crate::SourceLocation::at_location( + None, + reference.location.clone(), + )), + )); } }); - uses.warnings.extend( - uses.xrefs - .into_iter() - .filter(|(target, _)| !document.references.contains_key(target)) - .map(|(target, location)| { - Warning::new( - WarningKind::UnresolvedReference { - target: target.into(), - }, - Some(crate::SourceLocation::at_location(None, location)), - ) - }), - ); Ok::<_, Error>(uses.warnings) } diff --git a/acdc-parser/src/extensions/tests/construction.rs b/acdc-parser/src/extensions/tests/construction.rs index 587bdfc14..5a20aeec9 100644 --- a/acdc-parser/src/extensions/tests/construction.rs +++ b/acdc-parser/src/extensions/tests/construction.rs @@ -333,6 +333,52 @@ fn extensions_repair_failure_does_not_publish_edits_or_consume_caption_numbers() Ok(()) } +#[test] +fn extensions_reference_repair_failure_restores_each_splice() -> TestResult { + let mut result = support::registry().parse( + "= Document\n\n== Section\n\nInside.\n\ndefer::[]", + &Options::default(), + )?; + let target = result + .deferred_blocks() + .first() + .ok_or("placeholder")? + .target() + .clone(); + // Simulate a prepared section whose reference membership cannot be rebuilt. + result.parsed.with_document_mut(|_, document| { + if let Some(acdc_parser::Block::Section(section)) = document.blocks.first_mut() { + section.id = None; + } + }); + let before = serde_json::to_value(result.parsed.document())?; + let mut editor = DocumentEditor::new(&mut result); + assert!( + editor + .insert_before(&target, BlockBuilder::paragraph("insert")) + .is_err() + ); + assert_eq!(serde_json::to_value(editor.document_storage())?, before); + assert!( + editor + .replace_placeholder(&target, BlockBuilder::paragraph("replace")) + .is_err() + ); + assert_eq!(serde_json::to_value(editor.document_storage())?, before); + assert!(editor.discard_placeholder(&target).is_err()); + assert_eq!(serde_json::to_value(editor.document_storage())?, before); + assert_eq!( + editor + .deferred_blocks() + .first() + .ok_or("pending placeholder")? + .target(), + &target + ); + assert!(editor.query().get(&target).is_some()); + Ok(()) +} + #[test] fn extensions_verbatim_styles_follow_ordinary_caption_rules() -> TestResult { for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { diff --git a/acdc-parser/src/grammar/footnotes.rs b/acdc-parser/src/grammar/footnotes.rs index 1c02894cf..66e6f9dce 100644 --- a/acdc-parser/src/grammar/footnotes.rs +++ b/acdc-parser/src/grammar/footnotes.rs @@ -356,6 +356,18 @@ impl Document<'_> { /// Missing or ambiguous definitions or owner bindings, cycles, and number /// overflow leave the document unchanged. pub fn rebuild_footnotes(&mut self) -> Result<(), FootnoteRebuildError> { + if let Some(candidate) = self.with_repaired_footnotes()? { + self.commit_repair(candidate); + } + Ok(()) + } + + /// Prepare changed owners without publishing them, so a checked edit can + /// validate reference membership before committing either catalog. + pub(crate) fn with_repaired_footnotes(&mut self) -> Result, FootnoteRebuildError> { + if !super::location_walk::has_footnotes(self) { + return Ok(None); + } let mut header = self.header.clone(); let mut blocks = self.blocks.clone(); let mut footnotes = self.footnotes.clone(); @@ -376,21 +388,26 @@ impl Document<'_> { try_walk_document_inline_nodes_mut(&mut derived, &mut |node| { bindings.borrow().rebind(node) })?; - let mut prepared = Document { + let mut candidate = Self { header, blocks, footnotes, - ..Document::default() + attributes: self.attributes.clone(), + location: self.location.clone(), + untitled_header_location: self.untitled_header_location.clone(), + ..Self::default() }; - try_walk_document_reftext_inlines_mut(&mut prepared, &mut |node| { + try_walk_document_reftext_inlines_mut(&mut candidate, &mut |node| { bindings.borrow().rebind(node) })?; - self.header = prepared.header; - self.blocks = prepared.blocks; - self.footnotes = prepared.footnotes; - self.toc_entries = derived.toc_entries; - self.references = derived.references; - Ok(()) + candidate.toc_entries = derived.toc_entries; + candidate.references = derived.references; + Ok(Some(candidate)) + } + + pub(crate) fn commit_repair(&mut self, mut candidate: Self) { + candidate.generated_displays = std::mem::take(&mut self.generated_displays); + *self = candidate; } } diff --git a/acdc-parser/src/grammar/location_walk.rs b/acdc-parser/src/grammar/location_walk.rs index b39384644..332e468ec 100644 --- a/acdc-parser/src/grammar/location_walk.rs +++ b/acdc-parser/src/grammar/location_walk.rs @@ -46,6 +46,37 @@ pub(crate) fn walk_document_inline_nodes_mut<'a, F: FnMut(&mut InlineNode<'a>)>( .unwrap_or_else(|never: Infallible| match never {}); } +/// A footnote repair can be skipped only if neither a use nor a catalog remains. +pub(super) fn has_footnotes(document: &mut Document<'_>) -> bool { + if !document.footnotes.is_empty() { + return true; + } + let mut walker = AstWalker::new( + |_| Ok(()), + |node| { + if matches!(node, InlineNode::Macro(InlineMacro::Footnote(_))) { + Err(()) + } else { + Ok(()) + } + }, + |_, _| Ok(()), + |cell| match &cell.footnotes { + Some(notes) if !notes.is_empty() => Err(()), + _ => Ok(true), + }, + ); + // With no registrations the derived labels have no bindings to update. + // Only authored uses and nonempty owner catalogs can require repair. + walker.include_derived = false; + if let Some(header) = &mut document.header + && walker.header(header).is_err() + { + return true; + } + walker.blocks(&mut document.blocks).is_err() +} + /// Visit a single inline node's location and recurse into any inline children. pub(super) fn walk_inline_locations_mut( node: &mut InlineNode<'_>, diff --git a/acdc-parser/src/model/section.rs b/acdc-parser/src/model/section.rs index ead531c56..2d840a891 100644 --- a/acdc-parser/src/model/section.rs +++ b/acdc-parser/src/model/section.rs @@ -560,7 +560,8 @@ pub(crate) fn renumber_sections<'a>( let mut toc_numbers: HashMap>> = HashMap::with_capacity(toc_entries.len()); let mut record_number = - |section: &Section<'a>, numbers: SectionNumbers, name, record_toc: bool| { + |section: &mut Section<'a>, numbers: SectionNumbers, name, record_toc: bool| { + section.numbering.number.clone_from(&numbers.shown); update_section_reference(section, name, &numbers, references); if record_toc { toc_numbers @@ -653,7 +654,7 @@ pub(crate) fn extension_reference_numbers( ) -> Vec { let mut references = Vec::new(); let mut state = NumberingState::default(); - let mut record = |_: &Section<'_>, numbers: SectionNumbers, name, _: bool| { + let mut record = |_: &mut Section<'_>, numbers: SectionNumbers, name, _: bool| { references.push(SectionReference { name, number: numbers.reference, @@ -673,7 +674,8 @@ pub(crate) fn number_parsed_sections<'a>( let mut state = NumberingState::default(); let mut toc_index = 0; let mut record_number = - |section: &Section<'a>, numbers: SectionNumbers, name, record_toc: bool| { + |section: &mut Section<'a>, numbers: SectionNumbers, name, record_toc: bool| { + section.numbering.number.clone_from(&numbers.shown); update_section_reference(section, name, &numbers, references); if !record_toc { return; @@ -727,7 +729,7 @@ fn renumber_blocks<'a, F>( record_toc: bool, record_number: &mut F, ) where - F: FnMut(&Section<'a>, SectionNumbers, &'static str, bool), + F: FnMut(&mut Section<'a>, SectionNumbers, &'static str, bool), { for block in blocks { match block { @@ -838,7 +840,7 @@ fn renumber_delimited<'a, F>( record_toc: bool, record_number: &mut F, ) where - F: FnMut(&Section<'a>, SectionNumbers, &'static str, bool), + F: FnMut(&mut Section<'a>, SectionNumbers, &'static str, bool), { match inner { DelimitedBlockType::DelimitedExample(blocks) @@ -872,7 +874,7 @@ fn renumber_section<'a, F>( record_toc: bool, record_number: &mut F, ) where - F: FnMut(&Section<'a>, SectionNumbers, &'static str, bool), + F: FnMut(&mut Section<'a>, SectionNumbers, &'static str, bool), { let level = state.numbering_level(section.level, section.kind); let participates = section_participates(section, is_book); @@ -899,7 +901,6 @@ fn renumber_section<'a, F>( reference: number, } }; - section.numbering.number.clone_from(&numbers.shown); record_number( section, numbers, @@ -950,7 +951,7 @@ fn renumber_table<'a, F>( record_toc: bool, record_number: &mut F, ) where - F: FnMut(&Section<'a>, SectionNumbers, &'static str, bool), + F: FnMut(&mut Section<'a>, SectionNumbers, &'static str, bool), { for row in table .header From 55588c0b533aea62c1e6e95866847ae212ff6e24 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Wed, 18 Nov 2026 23:36:59 +0100 Subject: [PATCH 28/55] fix(extensions): bind deferred requests to their owning macro MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolve each macro’s surviving requests in source order and reject edits to another macro’s pending placeholders. Migrate the lists and diagram handlers to the scoped registration. Refs: SC-584 --- ARCHITECTURE.adoc | 3 + acdc-parser/CHANGELOG.md | 5 + acdc-parser/src/extensions/editor.rs | 55 +++++++---- acdc-parser/src/extensions/mod.rs | 12 ++- acdc-parser/src/extensions/registry.rs | 49 ++++++---- .../src/extensions/tests/construction.rs | 40 ++++---- acdc-parser/src/extensions/tests/display.rs | 14 +-- acdc-parser/src/extensions/tests/queries.rs | 4 +- acdc-parser/src/extensions/tests/support.rs | 11 +-- .../src/extensions/tests/title_sources.rs | 2 +- .../src/extensions/tests/tree_processors.rs | 87 ++++++++--------- acdc-parser/src/extensions/tree_processor.rs | 15 +++ acdc-parser/tests/extensions.rs | 95 ++++++++++++++++++- converters/dev/src/fixtures/display.rs | 8 +- .../html/tests/extension_construction.rs | 3 +- .../html/tests/typed_document_entrypoints.rs | 4 +- 16 files changed, 281 insertions(+), 126 deletions(-) diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc index e8f33a6b4..b791d7481 100644 --- a/ARCHITECTURE.adoc +++ b/ARCHITECTURE.adoc @@ -101,6 +101,9 @@ content services. Extension edits preserve surviving numbering. The host allocat generated text; builders do not reparse it or store backend markup. The working session retains deferred requests and document-local processors. +A tree processor registered with `TreeProcessorRegistration::for_macro` receives +its macro's surviving requests in source order. Only that processor can resolve +those placeholders. Removing a containing section cancels its pending requests. Its checked `finish()` operation rejects unresolved requests and returns the ordinary `ParseResult` for conversion. Registrations are explicit, and an empty registry retains the ordinary parsing path. Callback attribute changes follow diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index e3c65f05a..e892270b9 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Register a deferred block macro's tree processor with + `TreeProcessorRegistration::for_macro`. Its editor yields only that macro's + surviving requests in source order. Other processors can still query the + whole document and remove sections containing pending requests. + - Reduced parsing overhead for nested blocks and author headers. - Reduced allocation traffic when tree processors repeatedly edit a document. diff --git a/acdc-parser/src/extensions/editor.rs b/acdc-parser/src/extensions/editor.rs index f11957bad..6a6c501cd 100644 --- a/acdc-parser/src/extensions/editor.rs +++ b/acdc-parser/src/extensions/editor.rs @@ -10,12 +10,16 @@ use transaction::Edit; /// next observation. Validation and repair failures preserve the tree, handles, /// assigned numbers, and diagnostics. Surviving targets retain their identity. pub struct DocumentEditor<'doc> { + owner: Option<&'doc str>, pub(super) result: &'doc mut ExtensionParseResult, } impl<'doc> DocumentEditor<'doc> { - pub(super) const fn new(result: &'doc mut ExtensionParseResult) -> Self { - Self { result } + pub(super) const fn new( + result: &'doc mut ExtensionParseResult, + owner: Option<&'doc str>, + ) -> Self { + Self { owner, result } } #[must_use] pub fn query(&self) -> DocumentQuery<'_> { @@ -25,10 +29,15 @@ impl<'doc> DocumentEditor<'doc> { pub(super) fn document_storage(&self) -> &crate::Document<'_> { self.result.parsed.document_storage() } - /// Pending requests whose placeholders remain in the document. - #[must_use] - pub fn deferred_blocks(&self) -> &[DeferredBlock] { - self.result.deferred_blocks() + /// Surviving requests for this processor's macro, in source order. + /// A general tree processor has no deferred requests. + pub fn deferred_blocks(&self) -> impl Iterator { + self.owner.into_iter().flat_map(|owner| { + self.result + .deferred_blocks() + .iter() + .filter(move |request| request.invocation.name == owner) + }) } /// Record a recoverable problem at a live target's source location. @@ -76,21 +85,25 @@ impl<'doc> DocumentEditor<'doc> { /// metadata unless overridden. Descendant handles and requests are removed. /// /// # Errors - /// Rejects foreign/removed targets, sections, attribute events, and invalid content. + /// Rejects placeholders owned by another registration, foreign/removed targets, + /// sections, attribute events, and invalid content. pub fn replace_block(&mut self, target: &TargetId, content: BlockBuilder) -> Result<(), Error> { + if let Some(Block::Extension(block)) = self.query().get(target).map(|view| view.storage()) { + self.check_owner(target, block)?; + } self.apply(target, &Edit::Replace(content)).map(|_| ()) } /// Replace a pending placeholder through the shared construction and repair path. /// /// # Errors - /// Rejects nonpending, foreign, or removed targets and invalid content. + /// Rejects targets outside this processor's pending requests and invalid content. pub fn replace_placeholder( &mut self, target: &TargetId, content: BlockBuilder, ) -> Result<(), Error> { self.pending(target)?; - self.replace_block(target, content) + self.apply(target, &Edit::Replace(content)).map(|_| ()) } /// Replace retained paragraph or listing/literal source. Inline substitutions /// use the captured context and `subs=`. No block grammar or callbacks run. @@ -140,20 +153,30 @@ impl<'doc> DocumentEditor<'doc> { /// Remove a pending placeholder and consume its request. /// /// # Errors - /// Rejects nonpending, foreign, or removed targets. + /// Rejects targets outside this processor's pending requests. pub fn discard_placeholder(&mut self, target: &TargetId) -> Result<(), Error> { self.pending(target)?; self.apply(target, &Edit::Remove).map(|_| ()) } fn pending(&self, target: &TargetId) -> Result<(), Error> { - if self - .deferred_blocks() - .iter() - .any(|request| request.target() == target) - { + match self.query().get(target).map(|view| view.storage()) { + Some(Block::Extension(block)) => self.check_owner(target, block), + _ => Err(self.error(target, "target is not a pending placeholder")), + } + } + + fn check_owner( + &self, + target: &TargetId, + block: &super::ExtensionBlock<'_>, + ) -> Result<(), Error> { + if self.owner == Some(block.invocation.name.as_ref()) { Ok(()) } else { - Err(self.error(target, "target is not a pending placeholder")) + Err(self.error( + target, + "only the owning macro's deferred processor can resolve this placeholder", + )) } } pub(super) fn path(&self, target: &TargetId) -> Result { diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index b4ae8ec2e..8838f393d 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -93,8 +93,12 @@ //! through [`PreparedDocument`] before traversal; the shared parse stays unchanged. //! Checked ASG export rejects symbolic displays until they have been prepared. //! -//! Tree processors run after block macros and can replace pending requests with -//! ordinary content. Builder bodies are literal; attribute lists use the parser's +//! Tree processors run after block macros. Register a macro's resolver with +//! [`TreeProcessorRegistration::for_macro`] to receive its surviving requests in +//! source order. Only that processor can replace or discard those placeholders. +//! All tree processors can query the document and edit ordinary blocks. +//! +//! Builder bodies are literal; attribute lists use the parser's //! metadata rules. Use [`DocumentEditor::replace_source`] explicitly to interpret //! retained paragraph or listing/literal source with its original substitutions. //! @@ -113,7 +117,7 @@ //! struct Fill; //! impl TreeProcessor for Fill { //! fn process(&mut self, document: &mut DocumentEditor<'_>) -> Result<(), Error> { -//! let targets: Vec<_> = document.deferred_blocks().iter() +//! let targets: Vec<_> = document.deferred_blocks() //! .map(|request| request.target().clone()).collect(); //! for target in targets { //! document.replace_placeholder(&target, BlockBuilder::unordered_list(["One", "Two"]))?; @@ -123,7 +127,7 @@ //! } //! let mut builder = Registry::builder(); //! builder.register(BlockMacro::new("request", || Request))?; -//! builder.register_tree_processor(TreeProcessorRegistration::new("fill", || Fill))?; +//! builder.register_tree_processor(TreeProcessorRegistration::for_macro("request", || Fill))?; //! let result = builder.build().parse("request::[]", &Options::default())?; //! assert!(result.deferred_blocks().is_empty()); //! # Ok::<(), Box>(()) diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index d593bde50..1afcf9881 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -18,6 +18,8 @@ pub enum RegistrationError { UnknownName(String), #[error("tree processor is already registered: {0}")] DuplicateTreeProcessor(String), + #[error("deferred processor already registered for block macro: {0}")] + DuplicateDeferredProcessor(String), } /// Builds a registry without modifying existing registry snapshots. @@ -40,11 +42,7 @@ impl RegistryBuilder { } } for descriptor in ®istry.0.trees { - if self.trees.iter().any(|entry| entry.name == descriptor.name) { - return Err(RegistrationError::DuplicateTreeProcessor( - descriptor.name.clone(), - )); - } + self.check_tree_name(descriptor)?; } let offset = self.macros.len(); self.names.extend( @@ -62,26 +60,42 @@ impl RegistryBuilder { /// Register a tree processor after the existing tree processors. /// - /// Names match `[A-Za-z][A-Za-z0-9_-]*` and are independent of macro names. + /// General tree processor names are independent of macro names. + /// Use [`TreeProcessorRegistration::for_macro`] for deferred requests. /// /// # Errors - /// Rejects invalid names and duplicate tree processor registrations. + /// Rejects invalid or duplicate registrations. A macro must be registered + /// before its deferred processor and can have only one such processor. pub fn register_tree_processor( &mut self, registration: TreeProcessorRegistration, ) -> Result<&mut Self, RegistrationError> { validate_identifier(®istration.name)?; - if self - .trees - .iter() - .any(|entry| entry.name == registration.name) - { - return Err(RegistrationError::DuplicateTreeProcessor(registration.name)); + if registration.handles_deferred && !self.names.contains_key(®istration.name) { + return Err(RegistrationError::UnknownName(registration.name)); } + self.check_tree_name(®istration)?; self.trees.push(registration); Ok(self) } + fn check_tree_name( + &self, + registration: &TreeProcessorRegistration, + ) -> Result<(), RegistrationError> { + if self.trees.iter().any(|entry| { + entry.name == registration.name + && entry.handles_deferred == registration.handles_deferred + }) { + return Err(if registration.handles_deferred { + RegistrationError::DuplicateDeferredProcessor(registration.name.clone()) + } else { + RegistrationError::DuplicateTreeProcessor(registration.name.clone()) + }); + } + Ok(()) + } + /// Register a macro after the existing registrations. /// /// Names match `[A-Za-z][A-Za-z0-9_-]*`. Built-in macro names are reserved. @@ -99,7 +113,7 @@ impl RegistryBuilder { Ok(self) } - /// Replace a macro explicitly, preserving its registration position. + /// Replace a macro explicitly, preserving its registration position and deferred processor. /// /// # Errors /// Rejects names that have not been registered. @@ -236,8 +250,11 @@ impl Registry { result.repair_after_edit()?; } let mut processors = std::mem::take(&mut result.session.tree_processors); - for processor in &mut processors { - processor.process(&mut DocumentEditor::new(&mut result))?; + for (processor, registration) in processors.iter_mut().zip(&self.0.trees) { + let owner = registration + .handles_deferred + .then_some(registration.name.as_str()); + processor.process(&mut DocumentEditor::new(&mut result, owner))?; } result.session.tree_processors = processors; Ok(result) diff --git a/acdc-parser/src/extensions/tests/construction.rs b/acdc-parser/src/extensions/tests/construction.rs index 5a20aeec9..06f06531b 100644 --- a/acdc-parser/src/extensions/tests/construction.rs +++ b/acdc-parser/src/extensions/tests/construction.rs @@ -22,7 +22,7 @@ fn extensions_generated_paragraph_has_explicit_located_line_breaks() -> TestResu .get(&target) .ok_or("target")? .source_location(); - DocumentEditor::new(&mut result).replace_block( + DocumentEditor::new(&mut result, None).replace_block( &target, BlockBuilder::paragraph_inlines([ InlineSpec::Text("*literal* <&>".into()), @@ -72,7 +72,7 @@ fn extensions_inline_sequences_preserve_paragraph_order_and_literal_text() -> Te ] .into_iter() .collect(); - DocumentEditor::new(&mut result).replace_block( + DocumentEditor::new(&mut result, None).replace_block( &target, BlockBuilder::paragraph_inlines([ InlineSpec::from("Before "), @@ -132,7 +132,7 @@ fn extensions_located_warnings_survive_edits_and_reject_foreign_targets() -> Tes .get(&target) .ok_or("target")? .source_location(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); assert!(editor.warn(&foreign, "foreign warning").is_err()); editor.warn(&target, "recoverable extension problem")?; editor.warn(&target, "recoverable extension problem")?; @@ -164,7 +164,7 @@ fn extensions_image_replacement_preserves_identity_title_and_source_context() -> let before = result.query().get(&target).ok_or("original")?; let title = serde_json::to_value(before.title())?; let location = before.source_location(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); editor.replace_block( &target, BlockBuilder::image("generated.svg") @@ -227,7 +227,7 @@ fn extensions_literal_diagrams_keep_custom_disabled_and_generated_captions() -> .iter() .map(|request| request.target().clone()) .collect(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, Some("defer")); for (position, target) in targets.iter().enumerate() { let literal = BlockBuilder::literal("*literal* <&>\n spaces"); editor.replace_placeholder( @@ -274,7 +274,7 @@ fn extensions_generated_captions_respect_local_counter_seeds_without_reusing_num .iter() .map(|request| request.target().clone()) .collect(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, Some("defer")); for target in &targets { editor.replace_placeholder(target, BlockBuilder::image("generated.svg"))?; } @@ -308,7 +308,7 @@ fn extensions_repair_failure_does_not_publish_edits_or_consume_caption_numbers() .clone(); let before = serde_json::to_value(result.parsed.document())?; let warnings = format!("{:?}", result.warnings()); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); let error = editor.replace_block( &target, BlockBuilder::image("new.svg") @@ -352,7 +352,7 @@ fn extensions_reference_repair_failure_restores_each_splice() -> TestResult { } }); let before = serde_json::to_value(result.parsed.document())?; - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, Some("defer")); assert!( editor .insert_before(&target, BlockBuilder::paragraph("insert")) @@ -370,7 +370,7 @@ fn extensions_reference_repair_failure_restores_each_splice() -> TestResult { assert_eq!( editor .deferred_blocks() - .first() + .next() .ok_or("pending placeholder")? .target(), &target @@ -404,7 +404,8 @@ fn extensions_verbatim_styles_follow_ordinary_caption_rules() -> TestResult { .ok_or("request")? .target() .clone(); - DocumentEditor::new(&mut result).replace_placeholder(&target, content)?; + DocumentEditor::new(&mut result, Some("defer")) + .replace_placeholder(&target, content)?; assert_eq!( matches!( result.query().get(&target).and_then(|view| view.caption()), @@ -437,7 +438,7 @@ fn extensions_caption_overflow_rejects_the_edit_without_consuming_the_request() .clone(); let before = serde_json::to_value(result.parsed.document())?; assert!( - DocumentEditor::new(&mut result) + DocumentEditor::new(&mut result, Some("defer")) .replace_placeholder(&target, BlockBuilder::image("x.svg")) .is_err() ); @@ -472,7 +473,7 @@ fn extensions_source_replacement_uses_local_substitutions_and_repairs_references .iter() .any(|warning| matches!(warning.kind, WarningKind::UnresolvedReference { .. })) ); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); editor.replace_source( ¶graph, "New *{label}* footnote:new[New definition] <>.", @@ -534,7 +535,7 @@ fn extensions_invalid_construction_is_atomic_and_removes_replaced_descendants() .clone(); let before = serde_json::to_value(result.parsed.document())?; let warnings = format!("{:?}", result.warnings()); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, Some("defer")); assert!( editor .replace_block(&target, BlockBuilder::image("x.svg").with_id("duplicate")) @@ -558,7 +559,7 @@ fn extensions_invalid_construction_is_atomic_and_removes_replaced_descendants() editor.replace_block(&target, BlockBuilder::literal("Replacement"))?; assert!(editor.query().get(&child).is_none()); assert!(editor.ensure_id(&child).is_err()); - assert!(editor.deferred_blocks().is_empty()); + assert!(editor.deferred_blocks().next().is_none()); assert_eq!(format!("{:?}", result.warnings()), warnings); assert!(result.parsed.document().references().get("child").is_none()); let _ = result.finish()?; @@ -581,7 +582,7 @@ fn extensions_generated_metadata_distinguishes_empty_values_and_unsets() -> Test .ok_or("image")? .target() .clone(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); editor.replace_block( &target, BlockBuilder::image("new.svg") @@ -663,7 +664,7 @@ fn extensions_source_replacement_reuses_scoped_notes_without_number_collisions() .filter(|view| matches!(view.output_id(), Some("body" | "cell"))) .map(|view| view.target().clone()) .collect(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); for target in targets { editor.replace_source(&target, "New footnote:[New anonymous] footnote:shared[].")?; } @@ -676,7 +677,7 @@ fn extensions_source_replacement_reuses_scoped_notes_without_number_collisions() .ok_or("original")? .target() .clone(); - DocumentEditor::new(&mut result) + DocumentEditor::new(&mut result, None) .replace_source(&original, "Updated footnote:shared[Updated named].")?; let document = result.finish()?; assert_eq!(document.document().footnotes().count(), 2); @@ -711,14 +712,15 @@ fn extensions_normalize_preserves_unedited_numbers_and_clears_stale_duplicate_wa .ok_or("body")? .target() .clone(); - DocumentEditor::new(&mut result).replace_source(&target, "Replacement.")?; + DocumentEditor::new(&mut result, None).replace_source(&target, "Replacement.")?; assert!( !result .warnings() .iter() .any(|warning| matches!(warning.kind, WarningKind::DuplicateId { .. })) ); - DocumentEditor::new(&mut result).replace_source(&target, "[[fresh]] One [[fresh]] two.")?; + DocumentEditor::new(&mut result, None) + .replace_source(&target, "[[fresh]] One [[fresh]] two.")?; assert_eq!( result .warnings() diff --git a/acdc-parser/src/extensions/tests/display.rs b/acdc-parser/src/extensions/tests/display.rs index 59c0f3c03..533a00019 100644 --- a/acdc-parser/src/extensions/tests/display.rs +++ b/acdc-parser/src/extensions/tests/display.rs @@ -35,7 +35,7 @@ fn extensions_unordered_list_combines_literal_and_grouped_display_items() -> Tes .target() .clone(); let owned = String::from("*literal* <&> {counter:x}"); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); let captured = editor.capture(&image)?; editor.replace_block( &output, @@ -110,7 +110,7 @@ fn extensions_display_freezes_titles_and_defers_renamed_target_captions() -> Tes .ok_or("paragraph")? .target() .clone(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); let selected = editor.capture(&target)?; let second = editor.capture(&target)?; editor.replace_block( @@ -212,7 +212,7 @@ fn extensions_display_removed_identity_never_rebinds_to_reused_id() -> TestResul .get(&output) .ok_or("output view")? .source_location(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); let captured = editor.capture(&image)?; editor.replace_block( &output, @@ -268,7 +268,7 @@ fn extensions_foreign_display_is_rejected_atomically() -> TestResult { .ok_or("image")? .target() .clone(); - let captured = DocumentEditor::new(&mut first).capture(&image)?; + let captured = DocumentEditor::new(&mut first, None).capture(&image)?; let mut second = registry.parse("Paragraph.", &Options::default())?; let output = second .query() @@ -278,7 +278,7 @@ fn extensions_foreign_display_is_rejected_atomically() -> TestResult { .target() .clone(); let before = serde_json::to_value(second.parsed.document())?; - let error = DocumentEditor::new(&mut second).replace_block( + let error = DocumentEditor::new(&mut second, None).replace_block( &output, BlockBuilder::paragraph_inlines([ InlineSpec::Text("Before the rejected request".into()), @@ -310,7 +310,7 @@ fn extensions_display_distinguishes_absent_and_present_empty_titles() -> TestRes .ok_or("paragraph")? .target() .clone(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); let captured = editor.capture(&target)?; editor.insert_before( &target, @@ -355,7 +355,7 @@ fn extensions_symbolic_display_requires_lowering_before_checked_asg() -> TestRes .ok_or("image")? .target() .clone(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, None); let captured = editor.capture(&target)?; editor.insert_before( &target, diff --git a/acdc-parser/src/extensions/tests/queries.rs b/acdc-parser/src/extensions/tests/queries.rs index 9866bbce2..3533fa1ce 100644 --- a/acdc-parser/src/extensions/tests/queries.rs +++ b/acdc-parser/src/extensions/tests/queries.rs @@ -95,7 +95,7 @@ fn extensions_queries_observe_edits_and_reject_foreign_or_removed_handles() -> T let reused_id = result .ensure_id(handles.get(1).ok_or("pending")?)? .to_owned(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, Some("defer")); for target in foreign.query().blocks().map(|view| view.target().clone()) { assert!(editor.query().get(&target).is_none()); assert!(editor.ensure_id(&target).is_err()); @@ -118,7 +118,7 @@ fn extensions_queries_observe_edits_and_reject_foreign_or_removed_handles() -> T let snapshot = handles.clone(); assert_eq!(editor.query().select(BlockContext::Extension).count(), 1); editor.remove_section(section)?; - assert!(editor.deferred_blocks().is_empty()); + assert!(editor.deferred_blocks().next().is_none()); assert_eq!(editor.query().select(BlockContext::Extension).count(), 0); let new = editor.insert_before( stay, diff --git a/acdc-parser/src/extensions/tests/support.rs b/acdc-parser/src/extensions/tests/support.rs index 18adb2cfe..142acb74a 100644 --- a/acdc-parser/src/extensions/tests/support.rs +++ b/acdc-parser/src/extensions/tests/support.rs @@ -67,10 +67,13 @@ pub(super) fn registry() -> Registry { .register(BlockMacro::new("fixture-build", || Defer)) .expect("valid construction fixture macro"); builder - .register_tree_processor(TreeProcessorRegistration::new("construct", || Construct)) + .register_tree_processor(TreeProcessorRegistration::for_macro( + "fixture-build", + || Construct, + )) .expect("valid construction fixture processor"); builder - .register_tree_processor(TreeProcessorRegistration::new("query", || Query)) + .register_tree_processor(TreeProcessorRegistration::for_macro("query", || Query)) .expect("valid query fixture processor"); builder.build() } @@ -81,8 +84,6 @@ impl TreeProcessor for Construct { fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { let requests: Vec<_> = editor .deferred_blocks() - .iter() - .filter(|request| request.invocation.name == "fixture-build") .map(|request| { ( request.target().clone(), @@ -109,8 +110,6 @@ impl TreeProcessor for Query { fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { let requests: Vec<_> = editor .deferred_blocks() - .iter() - .filter(|request| request.invocation.name == "query") .map(|request| request.target().clone()) .collect(); if requests.is_empty() { diff --git a/acdc-parser/src/extensions/tests/title_sources.rs b/acdc-parser/src/extensions/tests/title_sources.rs index d54f1531d..3aa8e25b4 100644 --- a/acdc-parser/src/extensions/tests/title_sources.rs +++ b/acdc-parser/src/extensions/tests/title_sources.rs @@ -225,7 +225,7 @@ fn extensions_title_sources_survive_placeholder_replacement_and_preserve_caption .target() .clone(); let id = result.ensure_id(&target)?.to_owned(); - let mut editor = DocumentEditor::new(&mut result); + let mut editor = DocumentEditor::new(&mut result, Some("defer")); editor.replace_placeholder(&target, BlockBuilder::paragraph("Replaced"))?; let query = editor.query(); let replacement = query.get(&target).ok_or("replacement")?; diff --git a/acdc-parser/src/extensions/tests/tree_processors.rs b/acdc-parser/src/extensions/tests/tree_processors.rs index 128d3988f..72811d577 100644 --- a/acdc-parser/src/extensions/tests/tree_processors.rs +++ b/acdc-parser/src/extensions/tests/tree_processors.rs @@ -28,7 +28,7 @@ impl TreeProcessor for Fresh { fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { self.calls.fetch_add(1, Ordering::Relaxed); self.local.set(self.local.get() + 1); - let request = editor.deferred_blocks().first().expect("pending request"); + let request = editor.deferred_blocks().next().expect("pending request"); if self.fail { return Err(Error::Extension( Box::new(request.invocation.location.clone()), @@ -57,11 +57,13 @@ fn extensions_tree_processors_are_fresh_local_and_retained_until_result_drop() - let owned_drops = Arc::clone(&drops); let mut builder = Registry::builder(); builder.register(BlockMacro::new("defer", || support::Defer))?; - builder.register_tree_processor(TreeProcessorRegistration::new("fresh", move || Fresh { - local: Rc::new(Cell::new(0)), - calls: Arc::clone(&owned_calls), - drops: Arc::clone(&owned_drops), - fail: false, + builder.register_tree_processor(TreeProcessorRegistration::for_macro("defer", move || { + Fresh { + local: Rc::new(Cell::new(0)), + calls: Arc::clone(&owned_calls), + drops: Arc::clone(&owned_drops), + fail: false, + } }))?; let registry = builder.build(); assert!(!registry.is_empty()); @@ -90,15 +92,20 @@ fn extensions_tree_errors_stop_later_processors_at_included_request() -> TestRes let mut builder = Registry::builder(); builder .register(BlockMacro::new("defer", || support::Defer).with_target(MacroTarget::Required))?; - for name in ["failure", "later"] { + for first in [true, false] { let calls = Arc::clone(&calls); let drops = Arc::clone(&drops); - builder.register_tree_processor(TreeProcessorRegistration::new(name, move || Fresh { + let factory = move || Fresh { local: Rc::new(Cell::new(0)), calls: Arc::clone(&calls), drops: Arc::clone(&drops), fail: true, - }))?; + }; + builder.register_tree_processor(if first { + TreeProcessorRegistration::for_macro("defer", factory) + } else { + TreeProcessorRegistration::new("later", factory) + })?; } let registry = builder.build(); let options = Options::builder() @@ -221,7 +228,6 @@ impl TreeProcessor for FillNested { fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { let targets: Vec<_> = editor .deferred_blocks() - .iter() .map(|request| request.target().clone()) .collect(); for target in &targets { @@ -257,7 +263,8 @@ impl TreeProcessor for FillNested { fn extensions_tree_edits_follow_list_compound_and_table_cell_containers() -> TestResult { let mut builder = Registry::builder(); builder.register(BlockMacro::new("defer", || support::Defer))?; - builder.register_tree_processor(TreeProcessorRegistration::new("nested", || FillNested))?; + builder + .register_tree_processor(TreeProcessorRegistration::for_macro("defer", || FillNested))?; let result = builder.build().parse( include_str!("../../../fixtures/tests/includes/extensions/extension-tree-nested.adoc"), &Options::default(), @@ -299,26 +306,15 @@ impl TreeProcessor for Producer { self.0.fetch_add(1, Ordering::Relaxed); let requests: Vec<_> = editor .deferred_blocks() - .iter() - .map(|request| { - ( - request.target().clone(), - request.invocation.target == "discard", - ) - }) + .map(|request| request.target().clone()) .collect(); - for (target, discard) in requests { - let target = ⌖ - if discard { - editor.discard_placeholder(target)?; - } else { - let inserted = editor.insert_before( - target, - BlockBuilder::paragraph("Produced").with_id("produced"), - )?; - assert_eq!(editor.ensure_id(&inserted)?, "produced"); - assert!(editor.query().get(target).is_some()); - } + for target in &requests { + let inserted = editor.insert_before( + target, + BlockBuilder::paragraph("Produced").with_id("produced"), + )?; + assert_eq!(editor.ensure_id(&inserted)?, "produced"); + editor.discard_placeholder(target)?; } Ok(()) } @@ -336,13 +332,12 @@ impl TreeProcessor for Consumer { .collect(); let targets: Vec<_> = editor .deferred_blocks() - .iter() .map(|request| request.target().clone()) .collect(); for target in targets { editor.replace_placeholder(&target, BlockBuilder::unordered_list(selection.clone()))?; } - assert!(editor.deferred_blocks().is_empty()); + assert!(editor.deferred_blocks().next().is_none()); Ok(()) } } @@ -406,7 +401,6 @@ impl TreeProcessor for RemoveAndFill { Remove(Arc::new(AtomicUsize::new(0))).process(editor)?; let targets: Vec<_> = editor .deferred_blocks() - .iter() .map(|request| request.target().clone()) .collect(); for target in targets { @@ -421,7 +415,9 @@ fn extensions_generated_captions_keep_source_labels_and_advance_past_removed_ord { let mut builder = Registry::builder(); builder.register(BlockMacro::new("defer", || support::Defer))?; - builder.register_tree_processor(TreeProcessorRegistration::new("fill", || RemoveAndFill))?; + builder.register_tree_processor(TreeProcessorRegistration::for_macro("defer", || { + RemoveAndFill + }))?; let result = builder.build().parse( include_str!("../../../fixtures/tests/includes/extensions/extension-tree-captions.adoc"), &Options::default(), @@ -463,20 +459,21 @@ fn extensions_tree_order_and_snapshot_selection() -> TestResult { let calls = Arc::new(AtomicUsize::new(0)); let mut builder = Registry::builder(); builder.register(BlockMacro::new("defer", || support::Defer))?; + builder.register(BlockMacro::new("produce", || support::Defer))?; for name in ["producer", "consumer", "remover"] { let calls = Arc::clone(&calls); match name { "producer" => { - builder - .register_tree_processor(TreeProcessorRegistration::new(name, move || { - Producer(Arc::clone(&calls)) - }))?; + builder.register_tree_processor(TreeProcessorRegistration::for_macro( + "produce", + move || Producer(Arc::clone(&calls)), + ))?; } "consumer" => { - builder - .register_tree_processor(TreeProcessorRegistration::new(name, move || { - Consumer(Arc::clone(&calls)) - }))?; + builder.register_tree_processor(TreeProcessorRegistration::for_macro( + "defer", + move || Consumer(Arc::clone(&calls)), + ))?; } _ => { builder @@ -486,7 +483,7 @@ fn extensions_tree_order_and_snapshot_selection() -> TestResult { } } } - let result = builder.build().parse("[#gone]\n== Remove\n\nRemoved\n\n[#stay]\n== Keep\n\n.Title\n[#snapshot]\n[role=kept]\ndefer::content[]\n\ndefer::discard[]", &Options::default())?; + let result = builder.build().parse("[#gone]\n== Remove\n\nRemoved\n\n[#stay]\n== Keep\n\n.Title\n[#snapshot]\n[role=kept]\ndefer::content[]\n\nproduce::discard[]", &Options::default())?; assert_eq!(calls.load(Ordering::Relaxed), 3); assert!(result.deferred_blocks().is_empty()); let query = result.query(); @@ -546,7 +543,7 @@ impl TreeProcessor for CaptureAndRemove { .map(|view| view.target().clone()) .collect(); editor.remove_section(&gone)?; - assert!(editor.deferred_blocks().is_empty()); + assert!(editor.deferred_blocks().next().is_none()); let stay = editor .query() .select(BlockContext::Section) @@ -580,7 +577,7 @@ impl TreeProcessor for CaptureAndRemove { fn extensions_removed_handles_do_not_rebind_and_surviving_paths_shift() -> TestResult { let mut builder = Registry::builder(); builder.register(BlockMacro::new("defer", || support::Defer))?; - builder.register_tree_processor(TreeProcessorRegistration::new("capture", || { + builder.register_tree_processor(TreeProcessorRegistration::for_macro("defer", || { CaptureAndRemove }))?; let result = builder.build().parse( diff --git a/acdc-parser/src/extensions/tree_processor.rs b/acdc-parser/src/extensions/tree_processor.rs index b23deec1e..f3418f4f7 100644 --- a/acdc-parser/src/extensions/tree_processor.rs +++ b/acdc-parser/src/extensions/tree_processor.rs @@ -20,6 +20,7 @@ pub trait TreeProcessor { #[derive(Clone)] pub struct TreeProcessorRegistration { pub(super) name: String, + pub(super) handles_deferred: bool, pub(super) factory: Arc Box + Send + Sync>, } @@ -32,9 +33,22 @@ impl TreeProcessorRegistration { ) -> Self { Self { name: name.into(), + handles_deferred: false, factory: Arc::new(move || Box::new(factory())), } } + + /// Resolve the pending calls of one previously registered block macro. + /// The processor runs in tree registration order and can query the entire document. + pub fn for_macro( + macro_name: impl Into, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Self { + Self { + handles_deferred: true, + ..Self::new(macro_name, factory) + } + } } impl fmt::Debug for TreeProcessorRegistration { @@ -42,6 +56,7 @@ impl fmt::Debug for TreeProcessorRegistration { formatter .debug_struct("TreeProcessorRegistration") .field("name", &self.name) + .field("handles_deferred", &self.handles_deferred) .finish_non_exhaustive() } } diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index e0ed73168..5ed2f6f69 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -20,12 +20,102 @@ impl BlockMacroProcessor for Defer { } } +struct ResolveOwn(&'static str); + +impl TreeProcessor for ResolveOwn { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let own: Vec<_> = editor + .deferred_blocks() + .map(|request| { + assert_eq!(request.invocation.name, self.0); + ( + request.target().clone(), + request.invocation.target.to_string(), + ) + }) + .collect(); + assert_eq!( + own.iter() + .map(|(_, value)| value.as_str()) + .collect::>(), + ["one", "two"] + ); + let others: Vec<_> = editor + .query() + .select(BlockContext::Extension) + .map(|view| view.target().clone()) + .filter(|target| own.iter().all(|(owned, _)| owned != target)) + .collect(); + for target in others { + assert!( + editor + .replace_placeholder(&target, BlockBuilder::literal("wrong")) + .is_err() + ); + assert!( + editor + .replace_block(&target, BlockBuilder::literal("wrong")) + .is_err() + ); + assert!(editor.discard_placeholder(&target).is_err()); + } + for (target, value) in own { + editor.replace_placeholder(&target, BlockBuilder::paragraph(value))?; + } + Ok(()) + } +} + +#[test] +fn deferred_handlers_only_resolve_their_own_interleaved_requests() -> TestResult { + for order in [["alpha", "beta"], ["beta", "alpha"]] { + let mut builder = Registry::builder(); + builder.register_tree_processor(TreeProcessorRegistration::new("alpha", || RemoveFirst))?; + for name in order { + let mut package = Registry::builder(); + package.register(BlockMacro::new(name, || Defer))?; + package + .register_tree_processor(TreeProcessorRegistration::for_macro(name, move || { + ResolveOwn(name) + }))?; + builder.extend(&package.build())?; + } + let parsed = builder + .build() + .parse( + "alpha::one[]\n\nbeta::one[]\n\nalpha::two[]\n\nbeta::two[]\n\n[#gone]\n== Removed\n\nalpha::cancel[]\n\nbeta::cancel[]", + &Options::default(), + )? + .finish()?; + assert_eq!(parsed.document().blocks().count(), 4); + } + Ok(()) +} + +#[test] +fn a_deferred_processor_requires_one_registered_macro() -> TestResult { + use acdc_parser::extensions::RegistrationError; + + let mut builder = Registry::builder(); + let resolve = TreeProcessorRegistration::for_macro("alpha", || ResolveOwn("alpha")); + assert!(matches!( + builder.register_tree_processor(resolve.clone()), + Err(RegistrationError::UnknownName(name)) if name == "alpha" + )); + builder.register(BlockMacro::new("alpha", || Defer))?; + builder.register_tree_processor(resolve.clone())?; + assert!(matches!( + builder.register_tree_processor(resolve), + Err(RegistrationError::DuplicateDeferredProcessor(name)) if name == "alpha" + )); + Ok(()) +} + struct Fill; impl TreeProcessor for Fill { fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { let targets: Vec<_> = editor .deferred_blocks() - .iter() .map(|request| request.target().clone()) .collect(); for target in targets { @@ -68,7 +158,8 @@ fn extensions_finish_checks_pending_requests_and_returns_normal_parse_result() - let mut builder = Registry::builder(); builder.register(BlockMacro::new("request", || Defer))?; - builder.register_tree_processor(TreeProcessorRegistration::new("fill", || Fill))?; + builder + .register_tree_processor(TreeProcessorRegistration::for_macro("request", || Fill))?; let parsed: ParseResult = builder .build() .parse(".A *title*\n[#list]\nrequest::[]", &options)? diff --git a/converters/dev/src/fixtures/display.rs b/converters/dev/src/fixtures/display.rs index dda0f4086..d5523a248 100644 --- a/converters/dev/src/fixtures/display.rs +++ b/converters/dev/src/fixtures/display.rs @@ -12,9 +12,10 @@ use acdc_parser::{ pub(super) fn registry() -> Result { let mut builder = Registry::builder(); builder.register(BlockMacro::new("fixture-display", || Defer))?; - builder.register_tree_processor(TreeProcessorRegistration::new("fixture-display", || { - Display - }))?; + builder.register_tree_processor(TreeProcessorRegistration::for_macro( + "fixture-display", + || Display, + ))?; Ok(builder.build()) } @@ -36,7 +37,6 @@ impl TreeProcessor for Display { fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { let requests: Vec<_> = editor .deferred_blocks() - .iter() .map(|request| { ( request.target().clone(), diff --git a/converters/html/tests/extension_construction.rs b/converters/html/tests/extension_construction.rs index b8d69bbf3..545d2d5d3 100644 --- a/converters/html/tests/extension_construction.rs +++ b/converters/html/tests/extension_construction.rs @@ -32,7 +32,6 @@ impl TreeProcessor for DiagramProducer { } let requests: Vec<_> = editor .deferred_blocks() - .iter() .map(|request| request.target().clone()) .collect(); for target in requests { @@ -57,7 +56,7 @@ fn diagram_consumer_builds_images_and_literal_figures_with_normal_rendering() Ok(BlockMacroOutput::Deferred) } }))?; - builder.register_tree_processor(TreeProcessorRegistration::new("diagram", || { + builder.register_tree_processor(TreeProcessorRegistration::for_macro("diagram", || { DiagramProducer }))?; let converter = Converter::new( diff --git a/converters/html/tests/typed_document_entrypoints.rs b/converters/html/tests/typed_document_entrypoints.rs index 9165d56b3..b1246b980 100644 --- a/converters/html/tests/typed_document_entrypoints.rs +++ b/converters/html/tests/typed_document_entrypoints.rs @@ -74,7 +74,6 @@ impl TreeProcessor for FillList { fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { let targets: Vec<_> = editor .deferred_blocks() - .iter() .map(|request| request.target().clone()) .collect(); for target in targets { @@ -92,7 +91,8 @@ fn extension_generated_lists_preserve_metadata_references_and_literal_text() -> Result<(), Box> { let mut builder = Registry::builder(); builder.register(BlockMacro::new("request", || ListRequest))?; - builder.register_tree_processor(TreeProcessorRegistration::new("fill", || FillList))?; + builder + .register_tree_processor(TreeProcessorRegistration::for_macro("request", || FillList))?; let registry = builder.build(); for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { let converter = Converter::new( From 070bf8edca630b501e167c823defb2a77e32d07a Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 19 Nov 2026 20:37:45 +0100 Subject: [PATCH 29/55] perf(parser): speed up tag selection on complete include lines Use the buffered tag recognizer when an entire line is available and retain streaming recognition across decoder chunks. Exercise both paths through the existing include loader. Refs: SC-546 --- acdc-parser/CHANGELOG.md | 2 + .../src/preprocessor/include/reader.rs | 68 +++++++++++++------ acdc-parser/src/preprocessor/tag.rs | 2 +- .../preprocessor/include_source_provider.rs | 34 ++++++++++ 4 files changed, 84 insertions(+), 22 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index e892270b9..6084501a3 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Tagged includes read complete lines faster while preserving selection across reader chunk boundaries. + - Register a deferred block macro's tree processor with `TreeProcessorRegistration::for_macro`. Its editor yields only that macro's surviving requests in source order. Other processors can still query the diff --git a/acdc-parser/src/preprocessor/include/reader.rs b/acdc-parser/src/preprocessor/include/reader.rs index 94cd78dc2..967d72120 100644 --- a/acdc-parser/src/preprocessor/include/reader.rs +++ b/acdc-parser/src/preprocessor/include/reader.rs @@ -397,7 +397,11 @@ impl<'a> Selection<'a> { if let Some(line) = self.pending.take() { self.accept(&line)?; } - self.line = Some(Line::new(self.requirement(), self.tags.is_some())); + self.line = Some(Line::new( + self.requirement(), + self.tags.is_some(), + newline.then_some(fragment), + )); } if let Some(line) = &mut self.line { line.extend(fragment); @@ -430,7 +434,7 @@ impl<'a> Selection<'a> { } fn accept(&mut self, line: &Line) -> Result<(), Error> { - let required = self.requirement(); + let required = line.required_end; self.rebuild |= line.crlf; self.number += 1; let marker = line.marker(self.name)?; @@ -545,11 +549,26 @@ struct Line { previous: Option, carriage_returns: usize, crlf: bool, - probes: Option<[Probe; 2]>, + marker: LineMarker, +} + +/// A complete decoded line fits in one decoder buffer. Only lines crossing +/// buffer boundaries need incremental keyword recognition and name limits. +enum LineMarker { + Complete(Option<(&'static str, String)>), + Streaming([Probe; 2]), } impl Line { - fn new(required_end: Option, tags: bool) -> Self { + fn new(required_end: Option, tags: bool, complete: Option<&str>) -> Self { + let marker = match (tags, complete) { + (false, _) => LineMarker::Complete(None), + (true, Some(line)) => LineMarker::Complete( + tag::extract_tag_directive(line) + .map(|(directive, name)| (directive, name.to_owned())), + ), + (true, None) => LineMarker::Streaming([Probe::new("tag::"), Probe::new("end::")]), + }; Self { prefix: String::new(), required_end, @@ -559,7 +578,7 @@ impl Line { previous: None, carriage_returns: 0, crlf: false, - probes: tags.then(|| [Probe::new("tag::"), Probe::new("end::")]), + marker, } } @@ -583,7 +602,7 @@ impl Line { self.last = Some(last); } self.carriage_returns += text.bytes().filter(|&byte| byte == b'\r').count(); - if let Some(probes) = &mut self.probes { + if let LineMarker::Streaming(probes) = &mut self.marker { for ch in text.chars() { for probe in &mut *probes { probe.push(ch); @@ -610,22 +629,29 @@ impl Line { } fn marker(&self, source: &str) -> Result, Error> { - if let Some(probes) = &self.probes { - // Match the buffered tag extractor: a valid `tag::` marker takes - // priority over `end::`, even if `end::` comes first on the line. - for probe in probes { - if matches!(probe.state, ProbeState::Done(true)) { - if probe.overflow { - return Err(Error::IncludeSelectionTooComplex(source.to_string())); + match &self.marker { + LineMarker::Complete(marker) => { + return Ok(marker + .as_ref() + .map(|(directive, name)| (*directive, name.as_str()))); + } + LineMarker::Streaming(probes) => { + // Match the buffered tag extractor: a valid `tag::` marker takes + // priority over `end::`, even if `end::` comes first on the line. + for probe in probes { + if matches!(probe.state, ProbeState::Done(true)) { + if probe.overflow { + return Err(Error::IncludeSelectionTooComplex(source.to_string())); + } + return Ok(Some(( + if probe.keyword == "tag::" { + "tag" + } else { + "end" + }, + &probe.name, + ))); } - return Ok(Some(( - if probe.keyword == "tag::" { - "tag" - } else { - "end" - }, - &probe.name, - ))); } } } diff --git a/acdc-parser/src/preprocessor/tag.rs b/acdc-parser/src/preprocessor/tag.rs index 9c3f97bd8..154b32184 100644 --- a/acdc-parser/src/preprocessor/tag.rs +++ b/acdc-parser/src/preprocessor/tag.rs @@ -77,7 +77,7 @@ pub(super) enum Issue { /// Returns `("tag", name)` for an opening marker and `("end", name)` for a /// closing marker. The marker may follow a comment prefix or another /// non-word-boundary character. -fn extract_tag_directive(line: &str) -> Option<(&'static str, &str)> { +pub(super) fn extract_tag_directive(line: &str) -> Option<(&'static str, &str)> { for (directive, keyword) in [("tag", "tag::"), ("end", "end::")] { if let Some(pos) = line.find(keyword) { if pos > 0 diff --git a/acdc-parser/tests/preprocessor/include_source_provider.rs b/acdc-parser/tests/preprocessor/include_source_provider.rs index 06417b0a4..80bc10a8d 100644 --- a/acdc-parser/tests/preprocessor/include_source_provider.rs +++ b/acdc-parser/tests/preprocessor/include_source_provider.rs @@ -787,3 +787,37 @@ fn provider_survives_options_round_trip_with_locked_attributes() -> TestResult { assert_eq!(provider.requests(), [file_target(target)]); Ok(()) } + +#[test] +fn tag_selection_is_independent_of_decoder_chunk_boundaries() -> TestResult { + struct Fragmented<'a>(&'a [u8], usize); + impl std::io::Read for Fragmented<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let limit = buf.len().min(self.1); + self.0.read(buf.split_at_mut(limit).0) + } + } + let content = + "πtag::one[]\r\n// end::absent[] tag::one[]\r\nSelected.\r\n// end::one[]\r\nDropped."; + for width in [1, 2, 5, 8192] { + let options = Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::custom(move |_: &IncludeSourceTarget| { + Ok(IncludeSource::from_reader(Fragmented( + content.as_bytes(), + width, + ))) + })) + .build()?; + let parsed = parse("include::part.adoc[tag=one]", &options)?; + assert_eq!(parsed.preprocessed_source(), "Selected."); + assert_eq!(parsed.warnings(), []); + let block = parsed + .document() + .blocks() + .next() + .ok_or("missing selected line")?; + assert_eq!(block.location().start().line(), 3); + } + Ok(()) +} From 2d26378fe6f20b1c6959de585c6ec0fa28f23520 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 19 Nov 2026 20:39:09 +0100 Subject: [PATCH 30/55] feat(parser): add entry-source preprocessors with mapped line edits Run registered preprocessors once on the normalized entry source. Compose edits in registration order, anchor generated lines at the authored position, and keep the borrowed input when there are no edits. Refs: SC-546 --- acdc-parser/CHANGELOG.md | 2 + acdc-parser/README.adoc | 10 +- acdc-parser/README.md | 10 +- acdc-parser/src/extensions/mod.rs | 24 +++- acdc-parser/src/extensions/registry.rs | 82 +++++++++++-- acdc-parser/src/extensions/source.rs | 115 ++++++++++++++++++ .../grammar/document/construction/tests.rs | 2 +- acdc-parser/src/grammar/document/tests.rs | 4 +- acdc-parser/src/grammar/source/tests.rs | 2 +- acdc-parser/src/grammar/source_remap.rs | 18 +-- acdc-parser/src/grammar/state.rs | 8 +- acdc-parser/src/model/location.rs | 9 +- acdc-parser/src/parsed.rs | 20 +++ acdc-parser/src/preprocessor/cursor.rs | 3 +- acdc-parser/src/preprocessor/include.rs | 7 +- .../src/preprocessor/include/reader.rs | 2 +- acdc-parser/src/preprocessor/mod.rs | 10 +- acdc-parser/src/preprocessor/source.rs | 84 ++++++++++++- acdc-parser/tests/preprocessor/main.rs | 1 + .../tests/preprocessor/source_processors.rs | 62 ++++++++++ 20 files changed, 428 insertions(+), 47 deletions(-) create mode 100644 acdc-parser/src/extensions/source.rs create mode 100644 acdc-parser/tests/preprocessor/source_processors.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 6084501a3..5288bce30 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Native extensions can edit entry-source lines before parsing. Retained lines keep their original source locations. + - Tagged includes read complete lines faster while preserving selection across reader chunk boundaries. - Register a deferred block macro's tree processor with diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 088e3cd66..fe8171f2e 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2055,7 +2055,7 @@ to preserve their isolation. The fixture runner's case names are unchanged. [#registered-extensions] == Registered extensions -Applications can register block macros and ordered tree processors with +Applications can register source preprocessors, block macros, and tree processors with `extensions::Registry`. Each parse creates fresh processor instances. Block-macro callbacks run once when their block commits. `MacroExecutionContext::set_attribute` and `unset_attribute` request changes before subsequent conditionals and includes, @@ -2067,7 +2067,13 @@ non-`Send` state. Completed callback effects remain if later parsing fails. `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects -duplicate macro or tree-processor names before changing the builder. +duplicate registrations within each family before changing the builder. + +Use `register_preprocessor` to edit normalized entry text before the reader +interprets directives. Each processor sees the previous processor's edits. +Return an empty vector to keep the borrowed source. Removed lines retain the +original positions of subsequent text. Replacement text points to the start +of the edited line. Nested source ordering supports compound bodies and pipe/exclamation-delimited AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered diff --git a/acdc-parser/README.md b/acdc-parser/README.md index e48d501c6..7d3c1f1d4 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1699,7 +1699,7 @@ to preserve their isolation. The fixture runner's case names are unchanged. ## Registered extensions -Applications can register block macros and ordered tree processors with +Applications can register source preprocessors, block macros, and tree processors with `extensions::Registry`. Each parse creates fresh processor instances. Block-macro callbacks run once when their block commits. `MacroExecutionContext::set_attribute` and `unset_attribute` request changes before subsequent conditionals and includes, @@ -1711,7 +1711,13 @@ non-`Send` state. Completed callback effects remain if later parsing fails. `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects -duplicate macro or tree-processor names before changing the builder. +duplicate registrations within each family before changing the builder. + +Use `register_preprocessor` to edit normalized entry text before the reader +interprets directives. Each processor sees the previous processor's edits. +Return an empty vector to keep the borrowed source. Removed lines retain the +original positions of subsequent text. Replacement text points to the start +of the edited line. Nested source ordering supports compound bodies and pipe/exclamation-delimited AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 8838f393d..1c937f3b7 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -1,4 +1,4 @@ -//! Registered block macros and ordered tree processors with fresh document sessions. +//! Registered source, block macro, and tree processors with fresh document sessions. //! //! ``` //! use acdc_parser::{Options, extensions::{ @@ -58,6 +58,26 @@ //! # Ok::<(), Box>(()) //! ``` //! +//! Source preprocessors run once on the normalized entry text. Return line edits +//! in source order. Each processor sees the preceding edits. +//! +//! ``` +//! use acdc_parser::{Options, +//! extensions::{Registry, SourceEdit, SourceProcessorContext}}; +//! +//! let mut builder = Registry::builder(); +//! builder.register_preprocessor("strip-marker", || |text: &str, _: &SourceProcessorContext<'_>| { +//! Ok(if text.lines().next() == Some("GENERATED") { +//! vec![SourceEdit::Remove(1)] +//! } else { +//! Vec::new() +//! }) +//! })?; +//! let parsed = builder.build().parse("GENERATED\nVersion 1.", &Options::default())?.finish()?; +//! assert_eq!(parsed.preprocessed_source(), "Version 1."); +//! # Ok::<(), Box>(()) +//! ``` +//! //! Query parsed blocks by semantic context and let the host assign link targets: //! //! ``` @@ -170,6 +190,8 @@ mod query; mod recognition; mod registry; mod session; +mod source; +pub use source::{SourceEdit, SourcePreprocessor, SourceProcessorContext}; mod target; mod title; mod traversal; diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 1afcf9881..e6e96ab23 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -2,7 +2,10 @@ use std::{collections::HashMap, path::Path, sync::Arc}; use crate::{Error, Options, ParseResult}; -use super::{BlockMacro, DocumentEditor, ExtensionParseResult, Session, TreeProcessorRegistration}; +use super::{ + BlockMacro, DocumentEditor, ExtensionParseResult, Session, SourcePreprocessor, + TreeProcessorRegistration, source::SourceRegistration, +}; /// A registration rejected before any document is parsed. #[derive(Debug, thiserror::Error, PartialEq, Eq)] @@ -18,6 +21,8 @@ pub enum RegistrationError { UnknownName(String), #[error("tree processor is already registered: {0}")] DuplicateTreeProcessor(String), + #[error("source preprocessor is already registered: {0}")] + DuplicatePreprocessor(String), #[error("deferred processor already registered for block macro: {0}")] DuplicateDeferredProcessor(String), } @@ -28,13 +33,14 @@ pub struct RegistryBuilder { macros: Vec, names: HashMap, trees: Vec, + preprocessors: Vec>, } impl RegistryBuilder { /// Append another immutable registry in its registration order. /// /// # Errors - /// Rejects duplicate macro or tree-processor names without changing this builder. + /// Rejects duplicate registrations without changing this builder. pub fn extend(&mut self, registry: &Registry) -> Result<&mut Self, RegistrationError> { for descriptor in ®istry.0.macros { if self.names.contains_key(&descriptor.name) { @@ -44,6 +50,15 @@ impl RegistryBuilder { for descriptor in ®istry.0.trees { self.check_tree_name(descriptor)?; } + for entry in ®istry.0.preprocessors { + check_source_name( + &self.preprocessors, + &entry.name, + RegistrationError::DuplicatePreprocessor, + )?; + } + self.preprocessors + .extend_from_slice(®istry.0.preprocessors); let offset = self.macros.len(); self.names.extend( registry @@ -58,6 +73,28 @@ impl RegistryBuilder { Ok(self) } + /// Append an entry-source preprocessor in registration order. + /// + /// # Errors + /// Rejects invalid identifiers and duplicate names within this family. + pub fn register_preprocessor( + &mut self, + name: impl Into, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Result<&mut Self, RegistrationError> { + let name = name.into(); + check_source_name( + &self.preprocessors, + &name, + RegistrationError::DuplicatePreprocessor, + )?; + self.preprocessors.push(SourceRegistration { + name, + factory: Arc::new(move || Box::new(factory())), + }); + Ok(self) + } + /// Register a tree processor after the existing tree processors. /// /// General tree processor names are independent of macro names. @@ -134,10 +171,23 @@ impl RegistryBuilder { macros: self.macros, names: self.names, trees: self.trees, + preprocessors: self.preprocessors, })) } } +fn check_source_name( + entries: &[SourceRegistration

], + name: &str, + duplicate: fn(String) -> RegistrationError, +) -> Result<(), RegistrationError> { + validate_identifier(name)?; + if entries.iter().any(|entry| entry.name == name) { + return Err(duplicate(name.to_owned())); + } + Ok(()) +} + fn validate_name(name: &str) -> Result<(), RegistrationError> { validate_identifier(name)?; if matches!( @@ -164,6 +214,7 @@ struct RegistryData { macros: Vec, names: HashMap, trees: Vec, + preprocessors: Vec>, } /// A cheap-to-clone, immutable collection of extension factories. @@ -178,7 +229,15 @@ impl Registry { #[must_use] pub fn is_empty(&self) -> bool { - self.0.macros.is_empty() && self.0.trees.is_empty() + !self.has_input_processors() && self.0.trees.is_empty() + } + + fn has_input_processors(&self) -> bool { + !(self.0.macros.is_empty() && self.0.preprocessors.is_empty()) + } + + pub(crate) fn preprocessors(&self) -> impl Iterator> + '_ { + self.0.preprocessors.iter().map(|entry| (entry.factory)()) } pub(crate) fn has_tree_processors(&self) -> bool { @@ -243,7 +302,7 @@ impl Registry { options.extensions = Some(self.clone()); let parsed = parse( &options, - (!self.0.macros.is_empty()).then_some(&mut session), + self.has_input_processors().then_some(&mut session), )?; let mut result = ExtensionParseResult::new(parsed, session, options.compatibility_mode); if result.session.processed_blocks { @@ -271,13 +330,14 @@ impl Registry { /// A conservative dispatch filter, not a syntax recognizer. Includes can /// introduce registered names that are absent from the entry source. pub(crate) fn may_execute(&self, source: &str) -> bool { - source.match_indices("::").any(|(end, _)| { - let name = source[..end] - .rsplit(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-') - .next() - .unwrap_or_default(); - name == "include" || self.0.names.contains_key(name) - }) + !self.0.preprocessors.is_empty() + || source.match_indices("::").any(|(end, _)| { + let name = source[..end] + .rsplit(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-') + .next() + .unwrap_or_default(); + name == "include" || self.0.names.contains_key(name) + }) } pub(crate) fn session(&self) -> Session { diff --git a/acdc-parser/src/extensions/source.rs b/acdc-parser/src/extensions/source.rs new file mode 100644 index 000000000..0c8df4083 --- /dev/null +++ b/acdc-parser/src/extensions/source.rs @@ -0,0 +1,115 @@ +//! Document-local hooks for the entry source. + +use std::{cell::RefCell, fmt, path::Path, sync::Arc}; + +use crate::{ + DocumentAttributes, Error, Position, SourceLocation, Warning, WarningKind, + warning::WarningCollection, +}; + +/// An edit to one line of the normalized entry source supplied to this processor. +/// Line numbers start at one. Return edits in ascending order, once per line. +#[derive(Debug)] +#[non_exhaustive] +pub enum SourceEdit { + /// Remove the line and its separator. + Remove(usize), + /// Replace a line with text. The reader trims trailing whitespace on each + /// replacement line. Each LF-separated line in the + /// replacement originates at the edited line. Empty text leaves a blank line. + Replace { line: usize, text: String }, +} + +impl SourceEdit { + pub(crate) fn line(&self) -> usize { + match self { + Self::Remove(line) | Self::Replace { line, .. } => *line, + } + } +} + +/// Read-only document attributes and the source position of the current hook. +/// Entry preprocessors run at the start of the document. +pub struct SourceProcessorContext<'a> { + pub file: Option<&'a Path>, + pub line: usize, + pub(crate) offset: usize, + pub attributes: &'a DocumentAttributes<'a>, + pub(crate) warnings: &'a RefCell, +} + +impl SourceProcessorContext<'_> { + /// The original position where this hook runs. + #[must_use] + pub fn location(&self) -> SourceLocation { + let mut source = SourceLocation::at_position( + self.file.map(Path::to_path_buf), + Position::from_line_col(self.line, 1), + ); + source.location.absolute_start = self.offset; + source.location.absolute_end = self.offset; + source + } + + pub(crate) fn error(&self, message: String) -> Error { + Error::Extension(Box::new(self.location()), message) + } + + /// Add a recoverable warning at the hook's source position. + pub fn warn(&self, message: impl Into) { + let warning = Warning::new( + WarningKind::Other(message.into().into()), + Some(self.location()), + ); + warning.emit_trace(); + self.warnings.borrow_mut().push(warning); + } +} + +/// Runs once on the normalized entry source, before directive or block processing. +pub trait SourcePreprocessor { + /// Return edits to the current input. An empty vector preserves its storage. + /// + /// # Errors + /// Return a message to stop parsing with a located extension error. + fn process( + &mut self, + input: &str, + context: &SourceProcessorContext<'_>, + ) -> Result, String>; +} + +impl SourcePreprocessor for F +where + F: FnMut(&str, &SourceProcessorContext<'_>) -> Result, String>, +{ + fn process( + &mut self, + input: &str, + context: &SourceProcessorContext<'_>, + ) -> Result, String> { + self(input, context) + } +} + +pub(super) struct SourceRegistration { + pub(super) name: String, + pub(super) factory: Arc Box

+ Send + Sync>, +} + +impl Clone for SourceRegistration

{ + fn clone(&self) -> Self { + Self { + name: self.name.clone(), + factory: Arc::clone(&self.factory), + } + } +} + +impl fmt::Debug for SourceRegistration

{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("SourceRegistration") + .field(&self.name) + .finish() + } +} diff --git a/acdc-parser/src/grammar/document/construction/tests.rs b/acdc-parser/src/grammar/document/construction/tests.rs index e9bf75bdb..699c23d9f 100644 --- a/acdc-parser/src/grammar/document/construction/tests.rs +++ b/acdc-parser/src/grammar/document/construction/tests.rs @@ -129,7 +129,7 @@ fn compound_driver_restores_context_when_a_child_handler_fails( file_chain: vec!["part.adoc".into()], start_line: 41, source_start_offset: 100, - column_shift: 0, + column_shift: Some(0), }); } let mut calls = 0; diff --git a/acdc-parser/src/grammar/document/tests.rs b/acdc-parser/src/grammar/document/tests.rs index d49aee460..f93400357 100644 --- a/acdc-parser/src/grammar/document/tests.rs +++ b/acdc-parser/src/grammar/document/tests.rs @@ -1497,7 +1497,7 @@ fn test_grammar_warning_resolves_source_range() { file_chain: vec!["sponsor.adoc".to_string()], start_line: 1, source_start_offset: 0, - column_shift: 0, + column_shift: Some(0), }]; // Trigger warning at byte offset 40 (inside the included range) @@ -1538,7 +1538,7 @@ fn test_grammar_warning_falls_back_to_entry_file() { file_chain: vec!["other.adoc".to_string()], start_line: 1, source_start_offset: 0, - column_shift: 0, + column_shift: Some(0), }]; state.add_generic_warning_at("example warning".into(), state.create_location(17, 21)); diff --git a/acdc-parser/src/grammar/source/tests.rs b/acdc-parser/src/grammar/source/tests.rs index 483afb526..2703eb846 100644 --- a/acdc-parser/src/grammar/source/tests.rs +++ b/acdc-parser/src/grammar/source/tests.rs @@ -143,7 +143,7 @@ fn windows_preserve_included_diagnostic_ranges_and_final_separator_clipping() -> file_chain: vec!["part.adoc".into()], start_line: 41, source_start_offset: 900, - column_shift: 0, + column_shift: Some(0), }; let mut reference = ParserState::new(&complete, &arena, Rc::new(Options::default())); reference.source_ranges.push(range.clone()); diff --git a/acdc-parser/src/grammar/source_remap.rs b/acdc-parser/src/grammar/source_remap.rs index 1c740cc5f..3318eedf8 100644 --- a/acdc-parser/src/grammar/source_remap.rs +++ b/acdc-parser/src/grammar/source_remap.rs @@ -43,10 +43,11 @@ //! file on each boundary independently (so a span crossing a file boundary reports each //! endpoint's own file). Columns are normally left untouched — same-file line edits and //! include splicing only add or remove whole lines, never shift within-line columns. The -//! one exception is `include::[indent=N]`, which re-indents every line by a uniform +//! include option `indent=N` re-indents every line by a uniform //! [`SourceRange::column_shift`]; the remap subtracts it to recover origin columns. //! -//! Byte offsets are origin-relative only for **1:1** ranges (`column_shift == 0`). +//! Generated source points to column one and the byte offset of the edited line. +//! Unmodified ranges retain the original byte offset at each position. //! An indented include inserts/removes bytes per line, so a single linear map can't //! recover origin offsets; for such ranges the offsets are left in preprocessed //! coordinates (line/column are still origin-correct) rather than overrun the shorter @@ -328,10 +329,10 @@ pub(super) fn remap_endpoints( }; location.start.column = shift_column(location.start.column, start_range.column_shift); location.end.column = shift_column(location.end.column, end_range.column_shift); - if start_range.column_shift == 0 { + if start_range.column_shift.unwrap_or(0) == 0 { location.absolute_start = start_offset; } - if end_range.column_shift == 0 { + if end_range.column_shift.unwrap_or(0) == 0 { location.absolute_end = end_offset.max(location.absolute_start); } else { location.absolute_end = location.absolute_end.max(location.absolute_start); @@ -366,11 +367,14 @@ fn covering_range_index( /// Subtract a re-indent's `column_shift` from a preprocessed `column` to recover the /// origin column, clamped to a minimum of 1. A `0` shift returns `column` unchanged. -fn shift_column(column: u32, column_shift: isize) -> u32 { +fn shift_column(column: u32, column_shift: Option) -> u32 { + let Some(column_shift) = column_shift else { + return 1; + }; if column_shift == 0 { return column; } - let shifted = isize::try_from(column).unwrap_or(isize::MAX) - column_shift; + let shifted = i64::from(column) - i64::from(column_shift); u32::try_from(shifted.max(1)).unwrap_or(1) } @@ -386,7 +390,7 @@ mod tests { file_chain: Vec::new(), start_line: 1, source_start_offset: 0, - column_shift: 0, + column_shift: Some(0), } } diff --git a/acdc-parser/src/grammar/state.rs b/acdc-parser/src/grammar/state.rs index b7d1cf997..165258d05 100644 --- a/acdc-parser/src/grammar/state.rs +++ b/acdc-parser/src/grammar/state.rs @@ -1509,7 +1509,7 @@ mod tests { file_chain: vec!["included.adoc".to_string()], start_line: 1, source_start_offset: 0, - column_shift: 0, + column_shift: Some(0), }); // Location inside the included range (second line of include: "inc_line2") @@ -1551,7 +1551,7 @@ mod tests { file_chain: vec!["outer.adoc".to_string(), "inner.adoc".to_string()], start_line: 4, source_start_offset: 0, - column_shift: shift, + column_shift: Some(shift), }); let start = input.find("<<").ok_or("missing reference")?; let location = state.create_location(start, input.len() - 2); @@ -1580,7 +1580,7 @@ mod tests { file_chain: chain, start_line: 4, source_start_offset: 100, - column_shift: 0, + column_shift: Some(0), }, SourceRange { start_offset: 4, @@ -1589,7 +1589,7 @@ mod tests { file_chain: vec!["b.adoc".to_owned()], start_line: 2, source_start_offset: 0, - column_shift: 0, + column_shift: Some(0), }, ]; let source = state.create_error_source_location(state.create_location(0, 6)); diff --git a/acdc-parser/src/model/location.rs b/acdc-parser/src/model/location.rs index 667d8328a..142fec97c 100644 --- a/acdc-parser/src/model/location.rs +++ b/acdc-parser/src/model/location.rs @@ -99,7 +99,8 @@ pub(crate) struct SourceRange { /// subtracts it to recover origin columns. `0` for untransformed ranges, whose /// preprocessed↔origin mapping is byte-for-byte (1:1); a non-zero shift marks the /// range as **not 1:1**, so its `source_offset` no longer recovers origin offsets. - pub(crate) column_shift: isize, + /// Generated source uses the edited line start as a point anchor (`None`). + pub(crate) column_shift: Option, } impl SourceRange { @@ -120,7 +121,11 @@ impl SourceRange { /// Original-file byte offset for a preprocessed `offset` inside this range. #[must_use] pub(crate) fn source_offset(&self, offset: usize) -> usize { - self.source_start_offset + offset.saturating_sub(self.start_offset) + if self.column_shift.is_none() { + self.source_start_offset + } else { + self.source_start_offset + offset.saturating_sub(self.start_offset) + } } } diff --git a/acdc-parser/src/parsed.rs b/acdc-parser/src/parsed.rs index 7cfa55174..cf75ef24e 100644 --- a/acdc-parser/src/parsed.rs +++ b/acdc-parser/src/parsed.rs @@ -107,6 +107,26 @@ impl OwnedInput { #[cfg(test)] mod source_storage_tests { + #[test] + fn inactive_source_edits_keep_the_owned_input() -> Result<(), Box> { + let mut builder = crate::extensions::Registry::builder(); + builder.register_preprocessor("observe", || { + |_: &str, _: &crate::extensions::SourceProcessorContext<'_>| Ok(Vec::new()) + })?; + let input = "A paragraph.\n\n".repeat(1000); + let parsed = builder + .build() + .parse(&input, &crate::Options::default())? + .finish()?; + let owner = parsed.cell.borrow_owner(); + assert!(std::ptr::eq( + parsed.preprocessed_source(), + owner.source.as_ref() + )); + assert!(owner.processed_source.get().is_none()); + Ok(()) + } + #[test] fn ordered_pass_through_keeps_one_complete_source_buffer() -> Result<(), crate::Error> { for paragraphs in [100, 1000] { diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs index c41aeb9a5..dbc240c39 100644 --- a/acdc-parser/src/preprocessor/cursor.rs +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -709,7 +709,8 @@ impl<'input> InputCursor<'input> { } fn skip_unchanged_input(&mut self, options: &Options<'_>, include_root: bool) { - if (!include_root && self.preprocessor.include_context.depth == 0) + let at_root = self.preprocessor.include_context.depth == 0; + if at_root && (!include_root || !self.out.line_origins.is_empty()) || self.bulk_consumed || self.line_number != 1 || self.front_matter.is_some() diff --git a/acdc-parser/src/preprocessor/include.rs b/acdc-parser/src/preprocessor/include.rs index 9a75d53a3..e72dbf1d9 100644 --- a/acdc-parser/src/preprocessor/include.rs +++ b/acdc-parser/src/preprocessor/include.rs @@ -736,7 +736,7 @@ impl<'a> Include<'a> { /// Remove common leading whitespace and add `indent` spaces to nonblank lines. /// Return the text and its column change. Return `None` if the text exceeds the size limit. - fn apply_indent(lines: &[&str], indent: usize) -> Option<(String, isize)> { + fn apply_indent(lines: &[&str], indent: usize) -> Option<(String, i32)> { let min_indent = lines .iter() .filter(|line| !line.trim().is_empty()) @@ -766,8 +766,7 @@ impl<'a> Include<'a> { content.push_str(&line[min_indent..]); } } - let column_shift = - isize::try_from(indent).unwrap_or(0) - isize::try_from(min_indent).unwrap_or(0); + let column_shift = i32::try_from(indent).ok()? - i32::try_from(min_indent).ok()?; Some((content, column_shift)) } @@ -890,7 +889,7 @@ impl<'a> Include<'a> { )); } for origin in &mut line_origins { - origin.column_shift = column_shift; + origin.column_shift = Some(column_shift); } let scoped_options = self.scoped_options()?; let mut included = IncludeResult { diff --git a/acdc-parser/src/preprocessor/include/reader.rs b/acdc-parser/src/preprocessor/include/reader.rs index 967d72120..f3801c650 100644 --- a/acdc-parser/src/preprocessor/include/reader.rs +++ b/acdc-parser/src/preprocessor/include/reader.rs @@ -271,7 +271,7 @@ impl Candidates { origins.push(SourceLineOrigin { line: line.number, offset: line.offset, - column_shift: 0, + column_shift: Some(0), }); } Ok(Selected { diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index b3fa9372e..9b42c981a 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -364,7 +364,7 @@ impl SourceOrigin { struct SourceLineOrigin { pub(super) line: usize, pub(super) offset: usize, - pub(super) column_shift: isize, + pub(super) column_shift: Option, } impl SourceLineOrigin { @@ -372,7 +372,7 @@ impl SourceLineOrigin { Self { line, offset, - column_shift: 0, + column_shift: Some(0), } } } @@ -596,9 +596,9 @@ impl<'input> PreprocessorState<'input> { let origin = self.origin_of_line(input_line); if self.run.is_some() && (origin.line != self.run_expected_src_line - || self - .run - .is_some_and(|run| run.origin.column_shift != origin.column_shift)) + || self.run.is_some_and(|run| { + origin.column_shift.is_none() || run.origin.column_shift != origin.column_shift + })) { self.flush_run(); } diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs index da3cc007a..44736befc 100644 --- a/acdc-parser/src/preprocessor/source.rs +++ b/acdc-parser/src/preprocessor/source.rs @@ -12,12 +12,13 @@ use bumpalo::Bump; use crate::{ Error, Options, + extensions::{SourceEdit, SourceProcessorContext}, model::{LeveloffsetRange, SourceRange}, warning::WarningCollection, }; use super::{ - Preprocessor, PreprocessorResult, SourceOrigin, + Preprocessor, PreprocessorResult, SourceLineOrigin, SourceOrigin, cursor::{Advance, Emission, InputCursor}, has_attribute_driven_styles, skim_front_matter, }; @@ -75,7 +76,33 @@ impl<'a> SourceReader<'a> { Some(file) => SourceOrigin::entry_file(file, options.base_dir.as_deref())?, None => SourceOrigin::memory(options.base_dir.as_deref()), }; + let mut origins = Vec::new(); + let mut text = Cow::Borrowed(normalized); + if let Some(registry) = &options.extensions { + let context = SourceProcessorContext { + file, + line: 1, + offset: 0, + attributes: &options.document_attributes, + warnings: &warnings, + }; + for mut processor in registry.preprocessors() { + let edits = processor + .process(&text, &context) + .map_err(|message| context.error(message))?; + if !edits.is_empty() { + let (updated, mapped) = apply_edits(&text, &origins, edits) + .map_err(|message| context.error(message))?; + text = Cow::Owned(updated); + origins = mapped; + } + } + } let preprocessor = Preprocessor::new(&options, warnings); + let normalized = match text { + Cow::Borrowed(text) => text, + Cow::Owned(text) => arena.alloc_str(&text), + }; let front_matter = options .document_attributes .contains_key("skip-front-matter") @@ -85,7 +112,8 @@ impl<'a> SourceReader<'a> { // That can expose directives previously hidden in a comment block, so // those sources must keep the scanner resumable even if today's values // would allow the complete input to pass through unchanged. - if front_matter.is_none() + if origins.is_empty() + && front_matter.is_none() && !has_attribute_driven_styles(normalized) && let Some(scanner) = preprocessor.try_pass_through( normalized, @@ -118,7 +146,7 @@ impl<'a> SourceReader<'a> { normalized, Some(origin), Rc::make_mut(&mut options), - Vec::new(), + origins, front_matter, arena, ); @@ -234,5 +262,55 @@ impl<'a> SourceReader<'a> { } } +/// Compose each line edit with the previous stage's source map. Only an +/// editing processor pays for a new text buffer and line map. +fn apply_edits( + input: &str, + origins: &[SourceLineOrigin], + edits: Vec, +) -> Result<(String, Vec), String> { + let mut edits = edits.into_iter().peekable(); + let mut output = String::with_capacity(input.len()); + let mut mapped = Vec::new(); + let mut offset = 0; + let mut emit = |line: &str, origin| { + if !mapped.is_empty() { + output.push('\n'); + } + output.push_str(line); + mapped.push(origin); + }; + for (index, line) in input.split('\n').enumerate() { + let number = index + 1; + let origin = origins + .get(index) + .copied() + .unwrap_or_else(|| SourceLineOrigin::one_to_one(number, offset)); + offset += line.len() + 1; + match edits.next_if(|edit| edit.line() == number) { + None => emit(line, origin), + Some(SourceEdit::Remove(_)) => {} + Some(SourceEdit::Replace { text, .. }) => { + for replacement in text.split('\n') { + emit( + replacement.trim_end(), + SourceLineOrigin { + column_shift: None, + ..origin + }, + ); + } + } + } + } + if let Some(edit) = edits.next() { + return Err(format!( + "invalid source edit at line {}: edits must address existing lines in ascending order", + edit.line() + )); + } + Ok((output, mapped)) +} + #[cfg(test)] mod tests; diff --git a/acdc-parser/tests/preprocessor/main.rs b/acdc-parser/tests/preprocessor/main.rs index 912697e45..c003f797f 100644 --- a/acdc-parser/tests/preprocessor/main.rs +++ b/acdc-parser/tests/preprocessor/main.rs @@ -23,3 +23,4 @@ mod max_attribute_value_size; mod preprocessed_conditionals; mod recoverable_directives; mod retained_source; +mod source_processors; diff --git a/acdc-parser/tests/preprocessor/source_processors.rs b/acdc-parser/tests/preprocessor/source_processors.rs new file mode 100644 index 000000000..72de7b930 --- /dev/null +++ b/acdc-parser/tests/preprocessor/source_processors.rs @@ -0,0 +1,62 @@ +use acdc_parser::{ + Error, Options, + extensions::{Registry, SourceEdit, SourceProcessorContext}, +}; + +type TestResult = Result<(), Box>; + +#[test] +fn preprocessors_compose_and_retain_authored_positions() -> TestResult { + let mut builder = Registry::builder(); + builder.register_preprocessor("first", || { + |_: &str, _: &SourceProcessorContext<'_>| { + Ok(vec![ + SourceEdit::Replace { + line: 1, + text: "Generated one.\n\nGenerated two.".into(), + }, + SourceEdit::Remove(3), + ]) + } + })?; + builder.register_preprocessor("second", || { + |source: &str, _: &SourceProcessorContext<'_>| { + assert!(source.starts_with("Generated one.\n\nGenerated two.")); + Ok(vec![SourceEdit::Remove(1)]) + } + })?; + let result = builder + .build() + .parse("x\n\nomit\nTail.", &Options::default())? + .finish()?; + let positions: Vec<_> = result + .document() + .blocks() + .map(acdc_parser::ast::BlockRef::location) + .collect(); + let [generated, tail] = positions.as_slice() else { + return Err("expected two paragraphs".into()); + }; + assert_eq!(generated.start().line(), 1); + assert_eq!(generated.end().column(), 1); + assert_eq!(generated.absolute_end(), 0); + assert_eq!(tail.start().line(), 4); + assert_eq!(tail.absolute_start(), 8); + Ok(()) +} + +#[test] +fn invalid_source_edits_are_located() -> TestResult { + let mut builder = Registry::builder(); + builder.register_preprocessor("bad", || { + |_: &str, _: &SourceProcessorContext<'_>| Ok(vec![SourceEdit::Remove(4)]) + })?; + let Err(Error::Extension(location, message)) = + builder.build().parse("One.", &Options::default()) + else { + return Err("expected source edit error".into()); + }; + assert_eq!(location.location.start.line, 1); + assert!(message.contains("line 4")); + Ok(()) +} From 8fa7ff4f506703bd0b9a276ca620e9724102c224 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 19 Nov 2026 20:40:44 +0100 Subject: [PATCH 31/55] feat(parser): add document-local include processors Dispatch active include directives after target resolution and access checks. Pass supplied bytes through the existing include reader to preserve selection, limits, nested scopes, and source locations. Refs: SC-546 --- acdc-parser/CHANGELOG.md | 2 + acdc-parser/README.adoc | 12 +- acdc-parser/README.md | 12 +- acdc-parser/src/extensions/mod.rs | 20 +- acdc-parser/src/extensions/registry.rs | 45 ++- acdc-parser/src/extensions/source.rs | 75 +++- acdc-parser/src/preprocessor/include.rs | 79 +++- acdc-parser/src/preprocessor/include/peg.rs | 1 + acdc-parser/src/preprocessor/mod.rs | 35 +- acdc-parser/src/preprocessor/source.rs | 9 +- .../tests/preprocessor/source_processors.rs | 341 +++++++++++++++++- 11 files changed, 588 insertions(+), 43 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 5288bce30..b13a232cd 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Include processors can supply virtual content. They see attributes set by earlier block macros and follow the caller's include permissions, selection options, and expansion limits. + - Native extensions can edit entry-source lines before parsing. Retained lines keep their original source locations. - Tagged includes read complete lines faster while preserving selection across reader chunk boundaries. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index fe8171f2e..3263772d6 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2055,7 +2055,7 @@ to preserve their isolation. The fixture runner's case names are unchanged. [#registered-extensions] == Registered extensions -Applications can register source preprocessors, block macros, and tree processors with +Applications can register source preprocessors, include processors, block macros, and tree processors with `extensions::Registry`. Each parse creates fresh processor instances. Block-macro callbacks run once when their block commits. `MacroExecutionContext::set_attribute` and `unset_attribute` request changes before subsequent conditionals and includes, @@ -2075,6 +2075,16 @@ Return an empty vector to keep the borrowed source. Removed lines retain the original positions of subsequent text. Replacement text points to the start of the edited line. +Use `register_include_processor` to supply bytes for a resolved file or HTTP(S) +target. The callback can read the document attributes at the directive and +report a located warning. The first processor returning a source handles the +directive. If all decline, the reader uses the configured loader. Line and tag +selection, encoding, nesting, indentation, and byte limits apply to virtual +sources. Secure mode, disabled loading, depth limits, and URI permissions +are checked before dispatch. A system-local target may be entirely virtual. +For custom loaders and URI targets the loader must successfully open the +target before any processor can supply replacement bytes. + Nested source ordering supports compound bodies and pipe/exclamation-delimited AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered preprocessing. Unlike Asciidoctor 2.0.26, callbacks in supported nested bodies can diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 7d3c1f1d4..aa781a6f4 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1699,7 +1699,7 @@ to preserve their isolation. The fixture runner's case names are unchanged. ## Registered extensions -Applications can register source preprocessors, block macros, and tree processors with +Applications can register source preprocessors, include processors, block macros, and tree processors with `extensions::Registry`. Each parse creates fresh processor instances. Block-macro callbacks run once when their block commits. `MacroExecutionContext::set_attribute` and `unset_attribute` request changes before subsequent conditionals and includes, @@ -1719,6 +1719,16 @@ Return an empty vector to keep the borrowed source. Removed lines retain the original positions of subsequent text. Replacement text points to the start of the edited line. +Use `register_include_processor` to supply bytes for a resolved file or HTTP(S) +target. The callback can read the document attributes at the directive and +report a located warning. The first processor returning a source handles the +directive. If all decline, the reader uses the configured loader. Line and tag +selection, encoding, nesting, indentation, and byte limits apply to virtual +sources. Secure mode, disabled loading, depth limits, and URI permissions +are checked before dispatch. A system-local target may be entirely virtual. +For custom loaders and URI targets the loader must successfully open the +target before any processor can supply replacement bytes. + Nested source ordering supports compound bodies and pipe/exclamation-delimited AsciiDoc cells. CSV, TSV, DSV, and custom table separators retain buffered preprocessing. Unlike Asciidoctor 2.0.26, callbacks in supported nested bodies can diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 1c937f3b7..90056eee4 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -1,4 +1,4 @@ -//! Registered source, block macro, and tree processors with fresh document sessions. +//! Registered source, include, block macro, and tree processors with fresh document sessions. //! //! ``` //! use acdc_parser::{Options, extensions::{ @@ -59,10 +59,11 @@ //! ``` //! //! Source preprocessors run once on the normalized entry text. Return line edits -//! in source order. Each processor sees the preceding edits. +//! in source order. The first include processor to supply bytes handles that +//! resolved target. All supplied bytes pass through ordinary include processing. //! //! ``` -//! use acdc_parser::{Options, +//! use acdc_parser::{IncludeSource, IncludeSourceTarget, Options, SafeMode, //! extensions::{Registry, SourceEdit, SourceProcessorContext}}; //! //! let mut builder = Registry::builder(); @@ -73,7 +74,15 @@ //! Vec::new() //! }) //! })?; -//! let parsed = builder.build().parse("GENERATED\nVersion 1.", &Options::default())?.finish()?; +//! builder.register_include_processor("version", || |target: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| { +//! Ok(match target { +//! IncludeSourceTarget::File(path) if path.ends_with("version.adoc") => +//! Some(IncludeSource::from_string("Version 1.")), +//! _ => None, +//! }) +//! })?; +//! let options = Options::builder().with_safe_mode(SafeMode::Safe).build()?; +//! let parsed = builder.build().parse("GENERATED\ninclude::version.adoc[]", &options)?.finish()?; //! assert_eq!(parsed.preprocessed_source(), "Version 1."); //! # Ok::<(), Box>(()) //! ``` @@ -191,7 +200,8 @@ mod recognition; mod registry; mod session; mod source; -pub use source::{SourceEdit, SourcePreprocessor, SourceProcessorContext}; +pub(crate) use source::IncludeProcessors; +pub use source::{IncludeProcessor, SourceEdit, SourcePreprocessor, SourceProcessorContext}; mod target; mod title; mod traversal; diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index e6e96ab23..4d1c6b09e 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -3,8 +3,8 @@ use std::{collections::HashMap, path::Path, sync::Arc}; use crate::{Error, Options, ParseResult}; use super::{ - BlockMacro, DocumentEditor, ExtensionParseResult, Session, SourcePreprocessor, - TreeProcessorRegistration, source::SourceRegistration, + BlockMacro, DocumentEditor, ExtensionParseResult, IncludeProcessor, IncludeProcessors, Session, + SourcePreprocessor, TreeProcessorRegistration, source::SourceRegistration, }; /// A registration rejected before any document is parsed. @@ -23,6 +23,8 @@ pub enum RegistrationError { DuplicateTreeProcessor(String), #[error("source preprocessor is already registered: {0}")] DuplicatePreprocessor(String), + #[error("include processor is already registered: {0}")] + DuplicateIncludeProcessor(String), #[error("deferred processor already registered for block macro: {0}")] DuplicateDeferredProcessor(String), } @@ -34,6 +36,7 @@ pub struct RegistryBuilder { names: HashMap, trees: Vec, preprocessors: Vec>, + includes: Vec>, } impl RegistryBuilder { @@ -57,8 +60,16 @@ impl RegistryBuilder { RegistrationError::DuplicatePreprocessor, )?; } + for entry in ®istry.0.includes { + check_source_name( + &self.includes, + &entry.name, + RegistrationError::DuplicateIncludeProcessor, + )?; + } self.preprocessors .extend_from_slice(®istry.0.preprocessors); + self.includes.extend_from_slice(®istry.0.includes); let offset = self.macros.len(); self.names.extend( registry @@ -95,6 +106,28 @@ impl RegistryBuilder { Ok(self) } + /// Append an include processor. Each parse gets its own instance. + /// + /// # Errors + /// Rejects invalid identifiers and duplicate names within this family. + pub fn register_include_processor( + &mut self, + name: impl Into, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Result<&mut Self, RegistrationError> { + let name = name.into(); + check_source_name( + &self.includes, + &name, + RegistrationError::DuplicateIncludeProcessor, + )?; + self.includes.push(SourceRegistration { + name, + factory: Arc::new(move || Box::new(factory())), + }); + Ok(self) + } + /// Register a tree processor after the existing tree processors. /// /// General tree processor names are independent of macro names. @@ -172,6 +205,7 @@ impl RegistryBuilder { names: self.names, trees: self.trees, preprocessors: self.preprocessors, + includes: self.includes, })) } } @@ -215,6 +249,7 @@ struct RegistryData { names: HashMap, trees: Vec, preprocessors: Vec>, + includes: Vec>, } /// A cheap-to-clone, immutable collection of extension factories. @@ -233,13 +268,17 @@ impl Registry { } fn has_input_processors(&self) -> bool { - !(self.0.macros.is_empty() && self.0.preprocessors.is_empty()) + !(self.0.macros.is_empty() && self.0.preprocessors.is_empty() && self.0.includes.is_empty()) } pub(crate) fn preprocessors(&self) -> impl Iterator> + '_ { self.0.preprocessors.iter().map(|entry| (entry.factory)()) } + pub(crate) fn include_processors(&self) -> Option { + IncludeProcessors::new(&self.0.includes) + } + pub(crate) fn has_tree_processors(&self) -> bool { !self.0.trees.is_empty() } diff --git a/acdc-parser/src/extensions/source.rs b/acdc-parser/src/extensions/source.rs index 0c8df4083..76620434d 100644 --- a/acdc-parser/src/extensions/source.rs +++ b/acdc-parser/src/extensions/source.rs @@ -1,10 +1,10 @@ -//! Document-local hooks for the entry source. +//! Document-local hooks for the entry source and resolved includes. use std::{cell::RefCell, fmt, path::Path, sync::Arc}; use crate::{ - DocumentAttributes, Error, Position, SourceLocation, Warning, WarningKind, - warning::WarningCollection, + DocumentAttributes, Error, IncludeSource, IncludeSourceTarget, Position, SourceLocation, + Warning, WarningKind, warning::WarningCollection, }; /// An edit to one line of the normalized entry source supplied to this processor. @@ -29,7 +29,8 @@ impl SourceEdit { } /// Read-only document attributes and the source position of the current hook. -/// Entry preprocessors run at the start of the document. +/// For entry preprocessors the position is the start of the document. For +/// include processors it is the directive in its containing source. pub struct SourceProcessorContext<'a> { pub file: Option<&'a Path>, pub line: usize, @@ -92,6 +93,37 @@ where } } +/// Supplies bytes for a resolved include. The host selects lines, enforces +/// budgets, resolves nested targets and maps locations in the supplied source. +pub trait IncludeProcessor { + /// The first processor returning a source handles the directive. + /// Return `Ok(None)` to try the next processor or the configured loader. + /// + /// # Errors + /// Return a message to stop parsing at the include directive. + fn process( + &mut self, + target: &IncludeSourceTarget, + context: &SourceProcessorContext<'_>, + ) -> Result, String>; +} + +impl IncludeProcessor for F +where + F: FnMut( + &IncludeSourceTarget, + &SourceProcessorContext<'_>, + ) -> Result, String>, +{ + fn process( + &mut self, + target: &IncludeSourceTarget, + context: &SourceProcessorContext<'_>, + ) -> Result, String> { + self(target, context) + } +} + pub(super) struct SourceRegistration { pub(super) name: String, pub(super) factory: Arc Box

+ Send + Sync>, @@ -113,3 +145,38 @@ impl fmt::Debug for SourceRegistration

{ .finish() } } + +/// Nested include scopes share the active document's processor instances. +pub(crate) struct IncludeProcessors(RefCell]>>); + +impl IncludeProcessors { + pub(super) fn new(registrations: &[SourceRegistration]) -> Option { + (!registrations.is_empty()).then(|| { + Self(RefCell::new( + registrations.iter().map(|r| (r.factory)()).collect(), + )) + }) + } + + pub(crate) fn process( + &self, + target: &IncludeSourceTarget, + context: &SourceProcessorContext<'_>, + ) -> Result, Error> { + for processor in self.0.borrow_mut().iter_mut() { + if let Some(source) = processor + .process(target, context) + .map_err(|message| context.error(message))? + { + return Ok(Some(source)); + } + } + Ok(None) + } +} + +impl fmt::Debug for IncludeProcessors { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("IncludeProcessors").finish_non_exhaustive() + } +} diff --git a/acdc-parser/src/preprocessor/include.rs b/acdc-parser/src/preprocessor/include.rs index e72dbf1d9..85d0ce134 100644 --- a/acdc-parser/src/preprocessor/include.rs +++ b/acdc-parser/src/preprocessor/include.rs @@ -85,8 +85,8 @@ use url::Url; use crate::{ CompatibilityMode, DocumentAttributeAssignment, DocumentAttributeValue, DocumentAttributes, - IncludeSourceErrorKind, IncludeSourceProvider, IncludeSourceTarget, Location, Options, - SafeMode, Warning, + IncludeLoader, IncludeSource, IncludeSourceErrorKind, IncludeSourceProvider, + IncludeSourceTarget, Location, Options, SafeMode, Warning, document_attribute::{AttributeDeclaration, RawAttributeValue}, error::{Error, SourceLocation}, model::{LeveloffsetRange, Position, SourceRange}, @@ -140,6 +140,7 @@ pub(super) struct Include<'a> { context: IncludeContext, // Location information for error reporting line_number: usize, + current_offset: usize, current_file: Option, /// Shared warnings sink threaded from the outer `Preprocessor` so /// non-fatal include conditions (disabled URL includes, missing @@ -242,7 +243,7 @@ fn uri_directory(uri: &str) -> &str { #[derive(Debug, Clone, Copy)] pub(super) struct LocationContext<'a> { line_number: usize, - _current_offset: usize, + current_offset: usize, current_file: Option<&'a Path>, } @@ -254,7 +255,7 @@ impl<'a> LocationContext<'a> { ) -> Self { Self { line_number, - _current_offset: current_offset, + current_offset, current_file, } } @@ -1129,20 +1130,61 @@ impl<'a> Include<'a> { ranges } + /// Custom loaders are caller capabilities. A rejected target must never + /// reach an extension. URI targets also require a supported transport. + /// System-local targets can be supplied entirely in memory. + fn open_source( + &self, + target: &IncludeSourceTarget, + provider: &dyn IncludeSourceProvider, + ) -> Result { + let open = || provider.open(target).map_err(Error::IncludeSource); + let Some(processors) = &self.context.session.processors else { + return open(); + }; + let loaded = if matches!(self.options.include_loader, IncludeLoader::Custom(_)) + || matches!(target, IncludeSourceTarget::Uri(_)) + { + Some(open()?) + } else { + None + }; + let context = crate::extensions::SourceProcessorContext { + file: self.current_file.as_deref(), + line: self.line_number, + offset: self.current_offset, + attributes: &self.options.document_attributes, + warnings: &self.warnings, + }; + match processors.process(target, &context)?.or(loaded) { + Some(source) => Ok(source), + None => open(), + } + } + /// Read and select URI content. Do not process nested directives yet. fn read_content_from_url( &self, url: &str, source_provider: &dyn IncludeSourceProvider, ) -> Result { - let source = source_provider - .open(&IncludeSourceTarget::Uri(url.to_string())) - .map_err(|error| match error.kind() { - IncludeSourceErrorKind::Unsupported => UrlReadError::Unsupported(error.to_string()), - IncludeSourceErrorKind::NotFound | IncludeSourceErrorKind::Unavailable => { - UrlReadError::Retrieval + let source = self + .open_source(&IncludeSourceTarget::Uri(url.to_string()), source_provider) + .map_err(|error| { + let Error::IncludeSource(error) = error else { + return UrlReadError::Other(error); + }; + match error.kind() { + IncludeSourceErrorKind::Unsupported => { + UrlReadError::Unsupported(error.to_string()) + } + IncludeSourceErrorKind::NotFound | IncludeSourceErrorKind::Unavailable => { + UrlReadError::Retrieval + } + IncludeSourceErrorKind::Fatal => { + UrlReadError::Other(Error::IncludeSource(error)) + } } - IncludeSourceErrorKind::Fatal => UrlReadError::Other(Error::IncludeSource(error)), })?; reader::read(source, self.encoding.as_deref(), url, &self.selection).map_err(|error| { // Discard partial content when the response cannot be read. @@ -1206,9 +1248,14 @@ impl<'a> Include<'a> { optional: bool, source_provider: &dyn IncludeSourceProvider, ) -> Result { - let source = match source_provider.open(&IncludeSourceTarget::File(path.to_path_buf())) { + let source = match self.open_source( + &IncludeSourceTarget::File(path.to_path_buf()), + source_provider, + ) { Ok(source) => source, - Err(error) if error.kind() == IncludeSourceErrorKind::NotFound => { + Err(Error::IncludeSource(error)) + if error.kind() == IncludeSourceErrorKind::NotFound => + { if optional { tracing::info!( line = self.line_number, @@ -1219,7 +1266,7 @@ impl<'a> Include<'a> { } return Ok(LocalIncludeOutcome::Missing); } - Err(error) + Err(Error::IncludeSource(error)) if matches!( error.kind(), IncludeSourceErrorKind::Unavailable | IncludeSourceErrorKind::Unsupported @@ -1228,7 +1275,7 @@ impl<'a> Include<'a> { self.warn_located(format!("include file not readable: {}", path.display())); return Ok(LocalIncludeOutcome::Unreadable); } - Err(error) => return Err(Error::IncludeSource(error)), + Err(error) => return Err(error), }; let display_path = path.display().to_string(); @@ -1585,7 +1632,7 @@ mod tests { line, LocationContext::new(1, 0, None), options, - IncludeContext::root(options), + IncludeContext::root(options, None), &Rc::default(), ) } diff --git a/acdc-parser/src/preprocessor/include/peg.rs b/acdc-parser/src/preprocessor/include/peg.rs index bcd3750c2..b2cbb0ea8 100644 --- a/acdc-parser/src/preprocessor/include/peg.rs +++ b/acdc-parser/src/preprocessor/include/peg.rs @@ -31,6 +31,7 @@ peg::parser! { options: inputs.options.clone(), context: inputs.context.clone(), line_number: inputs.location.line_number, + current_offset: inputs.location.current_offset, current_file: inputs.location.current_file.map(Path::to_path_buf), warnings: Rc::clone(inputs.warnings), }; diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index 9b42c981a..4cf2afd45 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -233,13 +233,22 @@ struct IncludeContext { depth: usize, max_depth: usize, local_depth_limit: Option, - // Clones share one counter across all sibling and nested includes. - remaining_include_bytes: Rc>, + session: Rc, block_context: comment::BlockContext, } +/// Sibling and nested scopes share one byte budget and one set of processors. +#[derive(Debug)] +struct IncludeSession { + remaining_bytes: Cell, + processors: Option, +} + impl IncludeContext { - fn root(options: &Options<'_>) -> Self { + fn root( + options: &Options<'_>, + processors: Option, + ) -> Self { let max_depth = options .document_attributes .get(crate::document_attribute::MAX_INCLUDE_DEPTH_ATTR) @@ -251,7 +260,10 @@ impl IncludeContext { depth: 0, max_depth, local_depth_limit: None, - remaining_include_bytes: Rc::new(Cell::new(options.max_total_include_bytes())), + session: Rc::new(IncludeSession { + remaining_bytes: Cell::new(options.max_total_include_bytes()), + processors, + }), block_context: comment::BlockContext::default(), } } @@ -270,10 +282,10 @@ impl IncludeContext { let bytes = content .len() .saturating_add(usize::from(!content.is_empty())); - let Some(remaining) = self.remaining_include_bytes.get().checked_sub(bytes) else { + let Some(remaining) = self.session.remaining_bytes.get().checked_sub(bytes) else { return false; }; - self.remaining_include_bytes.set(remaining); + self.session.remaining_bytes.set(remaining); true } @@ -766,7 +778,7 @@ impl Preprocessor { fn new(options: &Options<'_>, warnings: Rc>) -> Self { Self { warnings, - include_context: IncludeContext::root(options), + include_context: IncludeContext::root(options, None), } } @@ -1561,7 +1573,8 @@ mod tests { ..Options::default() }; - let actual = i128::try_from(IncludeContext::root(&options).max_depth).unwrap_or(i128::MAX); + let actual = + i128::try_from(IncludeContext::root(&options, None).max_depth).unwrap_or(i128::MAX); assert_eq!( crate::document_attribute::default_value( crate::document_attribute::MAX_INCLUDE_DEPTH_ATTR @@ -1591,8 +1604,10 @@ mod tests { #[test] fn mapped_include_fast_path_preserves_normalization() -> Result<(), Error> { let mut options = Options::default(); - let preprocessor = - Preprocessor::nested(&Rc::default(), IncludeContext::root(&options).nested()); + let preprocessor = Preprocessor::nested( + &Rc::default(), + IncludeContext::root(&options, None).nested(), + ); let origin = SourceOrigin::Memory { base_dir: None }; for (input, expected) in [ ("", ""), diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs index 44736befc..d03c50adb 100644 --- a/acdc-parser/src/preprocessor/source.rs +++ b/acdc-parser/src/preprocessor/source.rs @@ -98,7 +98,14 @@ impl<'a> SourceReader<'a> { } } } - let preprocessor = Preprocessor::new(&options, warnings); + let includes = options + .extensions + .as_ref() + .and_then(crate::extensions::Registry::include_processors); + let preprocessor = Preprocessor { + warnings, + include_context: super::IncludeContext::root(&options, includes), + }; let normalized = match text { Cow::Borrowed(text) => text, Cow::Owned(text) => arena.alloc_str(&text), diff --git a/acdc-parser/tests/preprocessor/source_processors.rs b/acdc-parser/tests/preprocessor/source_processors.rs index 72de7b930..ab7e7197a 100644 --- a/acdc-parser/tests/preprocessor/source_processors.rs +++ b/acdc-parser/tests/preprocessor/source_processors.rs @@ -1,10 +1,152 @@ +use std::{ + fs, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, +}; + use acdc_parser::{ - Error, Options, - extensions::{Registry, SourceEdit, SourceProcessorContext}, + CompatibilityMode, Error, IncludeLoader, IncludeSource, IncludeSourceError, + IncludeSourceErrorKind, IncludeSourceTarget, Options, SafeMode, + extensions::{ + BlockMacro, BlockMacroOutput, MacroExecutionContext, MacroInvocation, Registry, SourceEdit, + SourceProcessorContext, + }, }; type TestResult = Result<(), Box>; +#[rstest::rstest] +fn ordered_callbacks_share_committed_attributes_and_nested_origins( + #[values(CompatibilityMode::Asciidoctor, CompatibilityMode::Draft)] mode: CompatibilityMode, +) -> TestResult { + let trace = Arc::new(Mutex::new(Vec::new())); + let mut builder = Registry::builder(); + let events = trace.clone(); + builder.register_preprocessor("expand", move || { + let events = events.clone(); + move |input: &str, _: &SourceProcessorContext<'_>| { + assert!(input.starts_with("omit\nconfigure")); + events.lock().map_err(|e| e.to_string())?.push("preprocess"); + Ok(vec![SourceEdit::Remove(1)]) + } + })?; + let events = trace.clone(); + builder.register(BlockMacro::new("configure", move || { + let events = events.clone(); + move |call: &MacroInvocation<'_>, context: &mut MacroExecutionContext| { + assert_eq!(call.location.location.start.line, 2); + events.lock().map_err(|e| e.to_string())?.push("block"); + context.set_attribute("audience", "expert"); + Ok(BlockMacroOutput::None) + } + }))?; + let events = trace.clone(); + builder.register_include_processor("virtual", move || { + let events = events.clone(); + let mut ordinal = 0; + move |target: &IncludeSourceTarget, context: &SourceProcessorContext<'_>| { + let IncludeSourceTarget::File(path) = target else { + return Ok(None); + }; + assert_eq!( + context + .attributes + .get("audience") + .and_then(acdc_parser::DocumentAttributeValue::text), + Some("expert") + ); + ordinal += 1; + if path.ends_with("parts/expert.adoc") { + assert_eq!((ordinal, context.line), (1, 5)); + events.lock().map_err(|e| e.to_string())?.push("outer"); + return Ok(Some(IncludeSource::from_string( + "ignored\ninclude::nested.adoc[lines=2]\nignored", + ))); + } + assert!(path.ends_with("parts/nested.adoc")); + assert_eq!((ordinal, context.line), (2, 2)); + assert!( + context + .file + .is_some_and(|path| path.ends_with("parts/expert.adoc")) + ); + context.warn("nested virtual include"); + events.lock().map_err(|e| e.to_string())?.push("nested"); + Ok(Some(IncludeSource::from_string("ignored\nSelected."))) + } + })?; + let registry = builder.build(); + let source = "omit\nconfigure::expert[]\n\nifdef::audience[]\ninclude::parts/{audience}.adoc[lines=2]\nendif::[]\n\nTail."; + let directory = tempfile::tempdir()?; + let file = directory.path().join("main.adoc"); + fs::write(&file, source)?; + let options = Options::builder() + .with_base_dir(directory.path()) + .with_safe_mode(SafeMode::Safe) + .with_compatibility_mode(mode) + .build()?; + for parsed in [ + registry.parse(source, &options)?, + registry.parse_from_reader(source.as_bytes(), &options)?, + registry.parse_file(&file, &options)?, + ] { + let result = parsed.finish()?; + let conditional = result.conditionals().next().ok_or("missing conditional")?; + assert_eq!( + (conditional.start_line(), conditional.is_active()), + (4, true) + ); + let blocks: Vec<_> = result.document().blocks().collect(); + let selected = blocks + .iter() + .find(|b| b.location().start().include_chain().is_some()) + .ok_or("missing included block")?; + assert_eq!(selected.location().start().line(), 2); + assert_eq!( + selected + .location() + .start() + .include_chain() + .ok_or("missing include chain")? + .count(), + 2 + ); + assert_eq!( + blocks + .last() + .ok_or("missing tail")? + .location() + .start() + .line(), + 8 + ); + assert!(result.preprocessed_source().contains("Selected.")); + assert!(!result.preprocessed_source().contains("ignored")); + assert_eq!(result.warnings().len(), 1); + let warning = result + .warnings() + .first() + .ok_or("missing include warning")? + .source_location() + .ok_or("unlocated warning")?; + assert!( + warning + .file + .as_ref() + .is_some_and(|path| path.ends_with("parts/expert.adoc")) + ); + assert_eq!(warning.location.start.line, 2); + assert_eq!(warning.location.absolute_start, "ignored\n".len()); + } + assert_eq!( + *trace.lock().map_err(|e| e.to_string())?, + ["preprocess", "block", "outer", "nested"].repeat(3) + ); + Ok(()) +} + #[test] fn preprocessors_compose_and_retain_authored_positions() -> TestResult { let mut builder = Registry::builder(); @@ -45,6 +187,96 @@ fn preprocessors_compose_and_retain_authored_positions() -> TestResult { Ok(()) } +#[test] +fn policies_control_dispatch_and_fallback() -> TestResult { + let count = Arc::new(AtomicUsize::new(0)); + let visits = count.clone(); + let mut builder = Registry::builder(); + builder.register_include_processor("virtual", move || { + let visits = visits.clone(); + move |_: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| { + visits.fetch_add(1, Ordering::Relaxed); + Ok(Some(IncludeSource::from_string("virtual"))) + } + })?; + let registry = builder.build(); + let include = "include::child.adoc[]"; + let remote = "include::https://example.invalid/doc.adoc[]"; + let denied = IncludeLoader::custom(|_: &IncludeSourceTarget| { + Err(IncludeSourceError::new( + IncludeSourceErrorKind::Unavailable, + "denied", + )) + }); + for (input, options) in [ + (include, Options::default()), + ( + include, + Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_include_loader(IncludeLoader::Disabled) + .build()?, + ), + ( + include, + Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_include_loader(denied) + .build()?, + ), + ( + include, + Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_attribute("max-include-depth", "0") + .build()?, + ), + ( + ":allow-uri-read:\n\ninclude::https://example.invalid/doc.adoc[]", + Options::builder().with_safe_mode(SafeMode::Safe).build()?, + ), + ( + remote, + Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .build()?, + ), + ( + "ifdef::missing[]\ninclude::ignored.adoc[]\nendif::[]\n\\include::ignored.adoc[]", + Options::builder().with_safe_mode(SafeMode::Safe).build()?, + ), + ] { + let result = registry.parse(input, &options)?.finish()?; + assert!(!result.preprocessed_source().contains("virtual")); + assert_eq!(count.load(Ordering::Relaxed), 0); + } + let allowed = Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_attribute("allow-uri-read", true) + .with_include_loader(IncludeLoader::custom(|target: &IncludeSourceTarget| { + assert!(matches!(target, IncludeSourceTarget::Uri(_))); + Ok(IncludeSource::from_string("permitted")) + })) + .build()?; + assert_eq!( + registry + .parse(remote, &allowed)? + .finish()? + .preprocessed_source(), + "virtual" + ); + let limited = Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_max_total_include_bytes(3) + .build()?; + assert!(matches!( + registry.parse(include, &limited), + Err(Error::IncludeExpansionTooLarge(..)) + )); + assert_eq!(count.load(Ordering::Relaxed), 2); + Ok(()) +} + #[test] fn invalid_source_edits_are_located() -> TestResult { let mut builder = Registry::builder(); @@ -60,3 +292,108 @@ fn invalid_source_edits_are_located() -> TestResult { assert!(message.contains("line 4")); Ok(()) } + +#[test] +fn include_failures_are_located_and_stop_the_chain() -> TestResult { + let mut builder = Registry::builder(); + builder.register_include_processor("fail", || { + |_: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| Err("failed include".into()) + })?; + builder.register_include_processor("unreached", || { + |_: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| Err("unexpected call".into()) + })?; + let options = Options::builder().with_safe_mode(SafeMode::Safe).build()?; + let Err(Error::Extension(location, message)) = builder + .build() + .parse("Intro.\n\ninclude::child.adoc[]", &options) + else { + return Err("expected include error".into()); + }; + assert_eq!(location.location.start.line, 3); + assert_eq!(message, "failed include"); + Ok(()) +} + +#[test] +fn include_registrations_compose_atomically_and_decline_to_the_loader() -> TestResult { + let directory = tempfile::tempdir()?; + fs::write(directory.path().join("part.adoc"), "disk")?; + let options = Options::builder() + .with_safe_mode(SafeMode::Safe) + .with_base_dir(directory.path()) + .build()?; + let mut builder = Registry::builder(); + let base = directory.path().to_owned(); + builder.register_include_processor("first", move || { + let base = base.clone(); + move |target: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| { + assert_eq!(target, &IncludeSourceTarget::File(base.join("part.adoc"))); + Ok(None) + } + })?; + let mut duplicate = Registry::builder(); + duplicate.register_preprocessor("unwanted", || { + |_: &str, _: &SourceProcessorContext<'_>| Err("partial registry merge".into()) + })?; + duplicate.register_include_processor("first", || { + |_: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| Err("duplicate processor".into()) + })?; + assert!(builder.extend(&duplicate.build()).is_err()); + assert!( + builder + .register_preprocessor("-", || |_: &str, _: &SourceProcessorContext<'_>| Ok(vec![])) + .is_err() + ); + let registry = builder.build(); + let input = "include::../part.adoc[]"; + assert_eq!( + registry + .parse(input, &options)? + .finish()? + .preprocessed_source(), + "disk" + ); + let mut package = Registry::builder(); + package.register_include_processor("second", || { + |_: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| { + Ok(Some(IncludeSource::from_string("override"))) + } + })?; + let mut all = Registry::builder(); + all.extend(®istry)?.extend(&package.build())?; + assert_eq!( + all.build() + .parse(input, &options)? + .finish()? + .preprocessed_source(), + "override" + ); + Ok(()) +} + +#[test] +fn concurrent_parses_create_independent_include_processors() -> TestResult { + let mut builder = Registry::builder(); + builder.register_include_processor("count", || { + let mut count = 0; + move |_: &IncludeSourceTarget, _: &SourceProcessorContext<'_>| { + count += 1; + Ok(Some(IncludeSource::from_string(format!("call {count}")))) + } + })?; + let registry = builder.build(); + let parse = || -> Result<(), Error> { + let options = Options::builder().with_safe_mode(SafeMode::Safe).build()?; + let parsed = registry + .parse("include::one.adoc[]\n\ninclude::two.adoc[]", &options)? + .finish()?; + assert_eq!(parsed.preprocessed_source(), "call 1\n\ncall 2"); + Ok(()) + }; + std::thread::scope(|scope| -> TestResult { + let other = scope.spawn(parse); + parse()?; + other.join().map_err(|_| "concurrent parse failed")??; + Ok(()) + }) +} From f5ee9f1279159a43d1c1aa91a66cb2ad489a26c8 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 19 Nov 2026 21:15:27 +0100 Subject: [PATCH 32/55] feat(parser): let block macros return ordinary blocks Construct returned builders at the committed invocation and retain its title, metadata, and source span. Tree processors can query the ordinary block immediately. Keep the callback output usable by shared registry factories. Refs: SC-547 --- acdc-parser/CHANGELOG.md | 2 + acdc-parser/README.adoc | 6 + acdc-parser/README.md | 6 + acdc-parser/src/extensions/block_macro.rs | 9 + acdc-parser/src/extensions/builder.rs | 52 +++++- acdc-parser/src/extensions/display.rs | 2 +- .../src/extensions/display/prepared.rs | 6 +- .../src/extensions/editor/transaction.rs | 34 ++-- acdc-parser/src/extensions/inline.rs | 30 ++-- acdc-parser/src/extensions/session.rs | 45 +++-- acdc-parser/src/extensions/target.rs | 8 +- acdc-parser/src/grammar/document/generated.rs | 55 +++++- acdc-parser/tests/extensions.rs | 161 +++++++++++++++++- 13 files changed, 331 insertions(+), 85 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index b13a232cd..8b28cdc7b 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Block macro handlers can return a `BlockBuilder` directly with `.into()`. Tree processors see the resulting block with the invocation’s title, ID, roles, and source location. + - Include processors can supply virtual content. They see attributes set by earlier block macros and follow the caller's include permissions, selection options, and expansion limits. - Native extensions can edit entry-source lines before parsing. Retained lines keep their original source locations. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 3263772d6..db0e7b088 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2064,6 +2064,12 @@ source location and a read-only attribute snapshot. Both compatibility modes support registrations. Factories are shared; handlers may use document-local, non-`Send` state. Completed callback effects remain if later parsing fails. +A block macro can return an ordinary block directly. For example, a handler for +`logo::acme[]` can return `Ok(BlockBuilder::image("acme.svg").into())`. +The image inherits the invocation's title, ID, roles, and source location. +Tree processors see the image as soon as they run. Use +`BlockMacroOutput::Deferred` when construction needs the rest of the document. + `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects diff --git a/acdc-parser/README.md b/acdc-parser/README.md index aa781a6f4..0cb6a8856 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1708,6 +1708,12 @@ source location and a read-only attribute snapshot. Both compatibility modes support registrations. Factories are shared; handlers may use document-local, non-`Send` state. Completed callback effects remain if later parsing fails. +A block macro can return an ordinary block directly. For example, a handler for +`logo::acme[]` can return `Ok(BlockBuilder::image("acme.svg").into())`. +The image inherits the invocation's title, ID, roles, and source location. +Tree processors see the image as soon as they run. Use +`BlockMacroOutput::Deferred` when construction needs the rest of the document. + `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects diff --git a/acdc-parser/src/extensions/block_macro.rs b/acdc-parser/src/extensions/block_macro.rs index 88dbe0077..94d2b9090 100644 --- a/acdc-parser/src/extensions/block_macro.rs +++ b/acdc-parser/src/extensions/block_macro.rs @@ -174,12 +174,21 @@ pub enum BlockMacroOutput { /// Emit one plain-text node in a paragraph, preserving the macro's outer /// title and metadata. The text is not parsed as inline markup. Paragraph(String), + /// Construct an ordinary block at the invocation, inheriting its title and metadata. + /// Captured target displays require the document available during tree processing. + Block(super::BlockBuilder), /// Remove the macro and its block metadata. None, /// Retain a placeholder and its arguments for document-level construction. Deferred, } +impl From for BlockMacroOutput { + fn from(builder: super::BlockBuilder) -> Self { + Self::Block(builder) + } +} + impl MacroInvocation<'_> { pub(super) fn to_owned_invocation(&self) -> MacroInvocation<'static> { MacroInvocation { diff --git a/acdc-parser/src/extensions/builder.rs b/acdc-parser/src/extensions/builder.rs index d37670d93..6f2010321 100644 --- a/acdc-parser/src/extensions/builder.rs +++ b/acdc-parser/src/extensions/builder.rs @@ -1,12 +1,12 @@ use std::sync::Arc; -use super::InlineSpec; +use super::{ExtensionBlock, InlineSpec}; use bumpalo::Bump; use crate::{ - Anchor, Block, BlockMetadata, CaptionKind, CompatibilityMode, DelimitedBlock, - DelimitedBlockType, DocumentAttributes, Image, InlineNode, ListItem, Location, Paragraph, - Plain, Source, Title, UnorderedList, Verbatim, + Anchor, Block, BlockMetadata, Caption, CaptionKind, CompatibilityMode, DelimitedBlock, + DelimitedBlockType, DocumentAttributes, Error, Image, InlineNode, ListItem, Location, + Paragraph, Plain, Source, Title, UnorderedList, Verbatim, grammar::ParserState, }; #[derive(Clone, Debug)] @@ -195,6 +195,50 @@ impl BlockBuilder { self } + pub(super) fn build_at_macro<'a>( + self, + extension: &mut ExtensionBlock<'a>, + state: &ParserState<'a>, + ) -> Result, Error> { + if self.id.as_deref() == Some("") { + return Err(Error::Extension( + Box::new(extension.invocation.location.clone()), + "output ID must not be empty".into(), + )); + } + let prepared = state.prepare_macro_output(&self, extension)?; + let mut metadata = prepared.metadata; + for warning in prepared.warnings { + state.add_warning(warning); + } + if let Some(kind) = self.caption_kind(metadata.style) { + metadata.caption = Some(Caption::resolve( + &metadata, + &extension.invocation.document_attributes, + kind, + )); + } + let location = &extension.location; + let mut block = self.build( + state.arena, + location.clone(), + metadata, + prepared.title, + |inline| { + inline.build(state.arena, location, |_, _| { + Err(Error::Extension( + Box::new(extension.invocation.location.clone()), + "captured displays require a tree processor".into(), + )) + }) + }, + )?; + if let Block::Image(image) = &mut block { + image.alt = prepared.alt; + } + Ok(block) + } + pub(super) fn build<'a>( self, arena: &'a Bump, diff --git a/acdc-parser/src/extensions/display.rs b/acdc-parser/src/extensions/display.rs index 2f5bb7179..2b77c97de 100644 --- a/acdc-parser/src/extensions/display.rs +++ b/acdc-parser/src/extensions/display.rs @@ -93,7 +93,7 @@ impl DisplayRequest { xref, )))); if intent == DisplayIntent::CaptionAndTitle && selection.title.is_present() { - nodes.push(plain(" ", origin)); + nodes.push(plain(" ", &origin.location)); nodes.extend(selection.title.as_inlines().iter().cloned()); } Ok(()) diff --git a/acdc-parser/src/extensions/display/prepared.rs b/acdc-parser/src/extensions/display/prepared.rs index 643406dea..c76afab77 100644 --- a/acdc-parser/src/extensions/display/prepared.rs +++ b/acdc-parser/src/extensions/display/prepared.rs @@ -93,7 +93,7 @@ impl<'doc> PreparedDocument<'doc> { xref.text = build_label(&owner.arena, &display, label); // A present-empty label must not fall back to generic reftext. if xref.text.is_empty() { - xref.text.push(plain("", &display.origin)); + xref.text.push(plain("", &display.origin.location)); } } Ok::<_, Error>(()) @@ -122,11 +122,11 @@ fn build_label<'a>( } else { vec![plain( arena.alloc_str(&format!("[{}]", GeneratedDisplayRef(display).target())), - &display.origin, + &display.origin.location, )] } } - DisplayLabel::Text(text) => vec![plain(arena.alloc_str(&text), &display.origin)], + DisplayLabel::Text(text) => vec![plain(arena.alloc_str(&text), &display.origin.location)], DisplayLabel::Caption { trim_end } => { let mut nodes = display .resolved diff --git a/acdc-parser/src/extensions/editor/transaction.rs b/acdc-parser/src/extensions/editor/transaction.rs index f7bd4a092..11c1657d1 100644 --- a/acdc-parser/src/extensions/editor/transaction.rs +++ b/acdc-parser/src/extensions/editor/transaction.rs @@ -120,27 +120,23 @@ fn prepare<'a>( if builder.source_body { return prepare_source(owner, original, builder, &inline_context, origin).map(Some); } - let mut inherited = if replacing { - original.metadata().cloned().unwrap_or_default() + let (mut inherited, title) = if replacing { + ( + original.metadata().cloned().unwrap_or_default(), + original.title().cloned().unwrap_or_default(), + ) } else { - BlockMetadata::default() + (BlockMetadata::default(), Title::default()) }; - inherited.attribute_positions = None; - inherited.positional_attributes.clear(); - inherited.reftext_source = None; inherited.prefix_events = None; - let title = if replacing { - original.title().cloned().unwrap_or_default() - } else { - Title::default() - }; let mut attributes = crate::grammar::prepare_generated( &owner.arena, builder, inherited, title, - &inline_context, origin, + &origin.location, + |input| inline_context.state(input, &owner.arena), )?; attributes.metadata.source_context = Some(std::sync::Arc::new(context)); let kind = builder.caption_kind(attributes.metadata.style); @@ -156,16 +152,16 @@ fn prepare<'a>( origin.location.clone(), attributes.metadata, attributes.title, - |inline| inline.build(&owner.arena, document, identity, origin), + |inline| { + inline.build(&owner.arena, &origin.location, |request, nodes| { + request.build_into(document, identity, origin, nodes) + }) + }, ) .map_err(|error| failure(origin, &error.to_string()))?; if let Block::Image(image) = &mut block { - let inherited_alt = if replacing { - if let Block::Image(image) = original { - image.alt.clone() - } else { - None - } + let inherited_alt = if replacing && let Block::Image(image) = original { + image.alt.clone() } else { None }; diff --git a/acdc-parser/src/extensions/inline.rs b/acdc-parser/src/extensions/inline.rs index c1c3bc94f..97f6db514 100644 --- a/acdc-parser/src/extensions/inline.rs +++ b/acdc-parser/src/extensions/inline.rs @@ -2,9 +2,9 @@ use bumpalo::Bump; -use crate::{Document, Error, InlineNode, LineBreak, Plain, SourceLocation}; +use crate::{Error, InlineNode, LineBreak, Location, Plain}; -use super::{DisplayRequest, target::DocumentIdentity}; +use super::DisplayRequest; /// Declarative input for generated inline content. /// @@ -52,34 +52,30 @@ impl InlineSpec { pub(super) fn build<'a>( self, arena: &'a Bump, - document: &Document<'a>, - identity: &DocumentIdentity, - origin: &SourceLocation, + location: &Location, + mut display: impl FnMut(DisplayRequest, &mut Vec>) -> Result<(), Error>, ) -> Result>, Error> { let mut nodes = Vec::new(); - self.build_into(arena, document, identity, origin, &mut nodes)?; + self.build_into(arena, location, &mut display, &mut nodes)?; Ok(nodes) } fn build_into<'a>( self, arena: &'a Bump, - document: &Document<'a>, - identity: &DocumentIdentity, - origin: &SourceLocation, + location: &Location, + display: &mut impl FnMut(DisplayRequest, &mut Vec>) -> Result<(), Error>, nodes: &mut Vec>, ) -> Result<(), Error> { match self { - Self::Text(text) => nodes.push(plain(arena.alloc_str(&text), origin)), + Self::Text(text) => nodes.push(plain(arena.alloc_str(&text), location)), Self::LineBreak => { - nodes.push(InlineNode::LineBreak(LineBreak::new( - origin.location.clone(), - ))); + nodes.push(InlineNode::LineBreak(LineBreak::new(location.clone()))); } - Self::Display(request) => request.build_into(document, identity, origin, nodes)?, + Self::Display(request) => display(request, nodes)?, Self::Sequence(content) => { for inline in content { - inline.build_into(arena, document, identity, origin, nodes)?; + inline.build_into(arena, location, display, nodes)?; } } } @@ -123,10 +119,10 @@ impl From<[Self; N]> for InlineSpec { } } -pub(super) fn plain<'a>(text: &'a str, origin: &SourceLocation) -> InlineNode<'a> { +pub(super) fn plain<'a>(text: &'a str, location: &Location) -> InlineNode<'a> { InlineNode::PlainText(Plain { content: text, - location: origin.location.clone(), + location: location.clone(), escaped: true, }) } diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index be156bf1e..b25f66328 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -1,10 +1,10 @@ use std::{cell::OnceCell, fmt}; -use crate::{Block, Error, InlineNode, Paragraph, ParseResult, Plain, grammar::ParserState}; +use crate::{Block, Error, ParseResult, grammar::ParserState}; use super::{ - BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, PlaceholderId, TargetId, - TreeProcessor, query::TargetIndex, target::DocumentIdentity, + BlockBuilder, BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, + PlaceholderId, TargetId, TreeProcessor, query::TargetIndex, target::DocumentIdentity, }; pub(crate) struct Session { @@ -146,27 +146,9 @@ impl Session { .map_err(|message| { Error::Extension(Box::new(extension.invocation.location.clone()), message) })?; - match output { - BlockMacroOutput::Paragraph(text) => { - let mut paragraph = Paragraph::new( - vec![InlineNode::PlainText(Plain { - content: state.intern_str(&text), - location: extension.location.clone(), - escaped: true, - })], - extension.location.clone(), - ); - paragraph.metadata = std::mem::take(&mut extension.metadata); - paragraph.title = std::mem::take(&mut extension.title); - if let Some(kind) = crate::CaptionKind::for_style(paragraph.metadata.style) { - paragraph.metadata.caption = Some(crate::Caption::resolve( - ¶graph.metadata, - &extension.invocation.document_attributes, - kind, - )); - } - *block = Block::Paragraph(paragraph); - } + let builder = match output { + BlockMacroOutput::Paragraph(text) => BlockBuilder::paragraph(text), + BlockMacroOutput::Block(builder) => builder, BlockMacroOutput::None => return Ok(false), BlockMacroOutput::Deferred => { let placeholder = PlaceholderId(self.deferred.len()); @@ -179,8 +161,21 @@ impl Session { slot: placeholder.0, }, }); + return Ok(true); + } + }; + *block = builder.build_at_macro(extension, state).map_err(|error| { + if matches!(error, Error::Extension(..)) { + return error; } - } + let message = if let Error::Parse(_, message) | Error::PegParse(_, message) = error + { + message + } else { + error.to_string() + }; + Error::Extension(Box::new(extension.invocation.location.clone()), message) + })?; } Ok(true) } diff --git a/acdc-parser/src/extensions/target.rs b/acdc-parser/src/extensions/target.rs index ba54c506b..3b9abde33 100644 --- a/acdc-parser/src/extensions/target.rs +++ b/acdc-parser/src/extensions/target.rs @@ -1,7 +1,7 @@ use std::{ fmt, hash::{Hash, Hasher}, - rc::Rc, + sync::Arc, }; use crate::{Anchor, Block, ReferenceTarget, grammar::reference_walk}; @@ -9,11 +9,11 @@ use crate::{Anchor, Block, ReferenceTarget, grammar::reference_walk}; use super::ExtensionParseResult; #[derive(Clone, Debug, Default)] -pub(super) struct DocumentIdentity(Rc<()>); +pub(super) struct DocumentIdentity(Arc<()>); impl PartialEq for DocumentIdentity { fn eq(&self, other: &Self) -> bool { - Rc::ptr_eq(&self.0, &other.0) + Arc::ptr_eq(&self.0, &other.0) } } @@ -21,7 +21,7 @@ impl Eq for DocumentIdentity {} impl Hash for DocumentIdentity { fn hash(&self, state: &mut H) { - Rc::as_ptr(&self.0).hash(state); + Arc::as_ptr(&self.0).hash(state); } } diff --git a/acdc-parser/src/grammar/document/generated.rs b/acdc-parser/src/grammar/document/generated.rs index f7401e65a..1843e6905 100644 --- a/acdc-parser/src/grammar/document/generated.rs +++ b/acdc-parser/src/grammar/document/generated.rs @@ -7,7 +7,7 @@ use bumpalo::Bump; use crate::{ BlockMetadata, ContentAttribute, Error, FootnoteDefinition, Location, Options, SourceLocation, Title, Warning, - extensions::{BlockBuilder, SourceContext}, + extensions::{BlockBuilder, ExtensionBlock, SourceContext}, grammar::{BlockAttributeMode, ParserState}, }; @@ -23,7 +23,7 @@ pub(crate) struct Context<'doc, 'a> { } impl<'a> Context<'_, 'a> { - fn state(&self, input: &'a str, arena: &'a Bump) -> Result, Error> { + pub(crate) fn state(&self, input: &'a str, arena: &'a Bump) -> Result, Error> { let mut options = Options::builder() .with_compatibility_mode(self.source.mode) .build()?; @@ -47,13 +47,45 @@ pub(crate) struct Prepared<'a> { pub(crate) warnings: Vec, } +impl<'a> ParserState<'a> { + pub(crate) fn prepare_macro_output( + &self, + builder: &BlockBuilder, + extension: &mut ExtensionBlock<'a>, + ) -> Result, Error> { + let metadata = std::mem::take(&mut extension.metadata); + let title = std::mem::take(&mut extension.title); + // The invocation's metadata has already been interpreted in source order. + if builder.defaults.is_none() && builder.attributes.is_empty() && builder.unsets.is_empty() + { + return Ok(Prepared { + metadata, + title, + alt: None, + explicit_alt: false, + warnings: Vec::new(), + }); + } + prepare( + self.arena, + builder, + metadata, + title, + &extension.invocation.location, + &extension.location, + |input| Ok(Self::for_inline_parsing(input, self, self.inline_ctx)), + ) + } +} + pub(crate) fn prepare<'a>( arena: &'a Bump, builder: &BlockBuilder, - inherited: BlockMetadata<'a>, + mut inherited: BlockMetadata<'a>, title: Title<'a>, - context: &Context<'_, 'a>, origin: &SourceLocation, + location: &Location, + make_state: impl FnOnce(&'a str) -> Result, Error>, ) -> Result, Error> { let sources: Vec<_> = builder.defaults.iter().chain(&builder.attributes).collect(); if sources.iter().any(|source| source.contains(['\n', '\r'])) { @@ -69,7 +101,7 @@ pub(crate) fn prepare<'a>( .collect::>() .join("\n"), ); - let mut state = context.state(input, arena)?; + let mut state = make_state(input)?; let mode = if builder.is_image() { BlockAttributeMode::Macro } else { @@ -85,15 +117,20 @@ pub(crate) fn prepare<'a>( if title.is_present() { attributes.title = None; } + // Attribute positions and pending reftext belong to the parsed source. + // Generated lists have their own input and positions. + inherited.attribute_positions = None; + inherited.positional_attributes.clear(); + inherited.reftext_source = None; let previous = inherited.clone(); - attributes.overlay_prepared(inherited, context.source.mode); + attributes.overlay_prepared(inherited, state.options.compatibility_mode); let mut explicit_alt = builder.unsets.iter().any(|name| name == "alt"); for source in &builder.attributes { let source = input.get(offset..offset + source.len()).unwrap_or_default(); let parsed = metadata::parse_block_attribute_list(&mut state, source, offset, mode, 0)?; explicit_alt |= parsed.metadata.first_source.is_some() || parsed.metadata.alt_source.is_some(); - attributes.merge(parsed, context.source.mode); + attributes.merge(parsed, state.options.compatibility_mode); offset += source.len() + 1; } let explicit_title = attributes.title.is_some(); @@ -102,7 +139,7 @@ pub(crate) fn prepare<'a>( for name in &builder.unsets { unset(&mut prepared, name); } - prepared.warnings = std::mem::take(&mut *state.warnings.borrow_mut()).into_vec(); + prepared.warnings = state.take_inline_warnings(); for warning in &mut prepared.warnings { warning.location = Some(origin.clone()); } @@ -112,7 +149,7 @@ pub(crate) fn prepare<'a>( prepared.title = std::mem::take(&mut prepared.title).with_source(Some(std::sync::Arc::new(source))); } - remap(&mut prepared, &previous, explicit_title, &origin.location); + remap(&mut prepared, &previous, explicit_title, location); Ok(prepared) } diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index 5ed2f6f69..438351ff8 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -1,9 +1,12 @@ use acdc_parser::{ CompatibilityMode, Error, Options, ParseResult, - ast::{BlockKind, ElementIdRef, FootnoteDefinitionRef, InlineKind, ReferenceTargetRef}, + ast::{ + BlockKind, CaptionRef, ElementIdRef, FootnoteDefinitionRef, InlineKind, ReferenceTargetRef, + }, extensions::{ BlockBuilder, BlockContext, BlockMacro, BlockMacroOutput, BlockMacroProcessor, - DocumentEditor, MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, + DocumentEditor, MacroExecutionContext, MacroInvocation, Registry, TitleSource, + TreeProcessor, TreeProcessorRegistration, }, }; @@ -14,7 +17,7 @@ impl BlockMacroProcessor for Defer { fn process( &mut self, _: &MacroInvocation<'_>, - _: &mut acdc_parser::extensions::MacroExecutionContext, + _: &mut MacroExecutionContext, ) -> Result { Ok(BlockMacroOutput::Deferred) } @@ -379,3 +382,155 @@ fn extensions_preserve_scoped_include_assignments_and_origins() -> TestResult { } Ok(()) } + +struct ObserveLogo; + +impl TreeProcessor for ObserveLogo { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + assert_eq!(editor.query().select(BlockContext::Image).count(), 1); + assert_eq!(editor.query().select(BlockContext::Extension).count(), 0); + Ok(()) + } +} + +#[test] +fn committed_macro_returns_an_ordinary_image_at_its_include_location() -> TestResult { + let directory = tempfile::tempdir()?; + let included = directory.path().join("branding.adoc"); + std::fs::write(&included, ".The *logo*\n[#brand.wide]\nlogo::acme[]\n")?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(acdc_parser::SafeMode::Safe) + .with_base_dir(directory.path()) + .build()?; + for observe in [false, true] { + let mut registry = Registry::builder(); + registry.register(BlockMacro::new("logo", || { + let mut called = false; + move |call: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { + assert!(!std::mem::replace(&mut called, true)); + assert_eq!(call.target, "acme"); + Ok(BlockBuilder::image(format!("{}.svg", call.target)).into()) + } + }))?; + if observe { + registry + .register_tree_processor(TreeProcessorRegistration::new("observe", || { + ObserveLogo + }))?; + } + let result = registry + .build() + .parse("Intro.\n\ninclude::branding.adoc[]", &options)?; + assert!(result.deferred_blocks().is_empty()); + let logo = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("missing image")?; + assert_eq!(logo.output_id(), Some("brand")); + assert_eq!( + logo.source_location().file.as_deref(), + Some(included.as_path()) + ); + // A block span starts at its first attached metadata line. + assert_eq!(logo.source_location().location.start.line, 1); + assert_eq!(logo.source_location().location.end.line, 3); + assert_eq!( + logo.title_source().map(TitleSource::raw_source), + Some("The *logo*") + ); + assert!(logo.title().is_some_and(|title| { + title + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + })); + let BlockKind::Image(image) = logo.block().kind() else { + return Err("missing image".into()); + }; + assert!(image.roles().contains("wide")); + assert_eq!(image.source().to_string(), "acme.svg"); + assert!( + matches!(logo.caption(), Some(CaptionRef::Numbered { number: Some(n), .. }) if n.get() == 1) + ); + let parsed = result.finish()?; + assert_eq!(parsed.warnings(), []); + } + } + Ok(()) +} + +#[test] +fn committed_macro_interprets_builder_attributes_at_the_invocation() -> TestResult { + let mut registry = Registry::builder(); + registry.register(BlockMacro::new("logo", || { + |_: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { + Ok(BlockBuilder::image("brand.svg") + .with_attributes("alt={label},width=120") + .into()) + } + }))?; + let registry = registry.build(); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = registry.parse( + ":label: Early\n\n[#brand.wide]\nlogo::acme[]\n\n:label: Late", + &options, + )?; + let logo = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("missing image")?; + let BlockKind::Image(image) = logo.block().kind() else { + return Err("missing image".into()); + }; + assert!(image.roles().contains("wide")); + assert_eq!(logo.output_id(), Some("brand")); + let alt = image + .alt() + .and_then(|alt| alt.inlines().next()) + .ok_or("missing alt")?; + assert!( + matches!(alt.kind(), InlineKind::Plain(plain) if plain.text() == "Early") + || matches!(alt.kind(), InlineKind::Raw(raw) if raw.text() == "Early") + ); + assert_eq!(alt.location().start().line(), 3); + assert_eq!(alt.location().end().line(), 4); + } + Ok(()) +} + +#[test] +fn invalid_direct_macro_output_reports_the_included_invocation() -> TestResult { + let directory = tempfile::tempdir()?; + let included = directory.path().join("branding.adoc"); + std::fs::write(&included, "First.\n\nlogo::acme[]")?; + let options = Options::builder() + .with_safe_mode(acdc_parser::SafeMode::Safe) + .with_base_dir(directory.path()) + .build()?; + for invalid in [ + BlockBuilder::image("http://[invalid"), + BlockBuilder::paragraph("text").with_id(""), + BlockBuilder::literal("text").with_attributes("role=one\nrole=two"), + ] { + let mut registry = Registry::builder(); + registry.register(BlockMacro::new("logo", move || { + let invalid = invalid.clone(); + move |_: &MacroInvocation<'_>, _: &mut MacroExecutionContext| Ok(invalid.clone().into()) + }))?; + let error = registry + .build() + .parse("include::branding.adoc[]", &options) + .err() + .ok_or("expected invalid builder to fail")?; + let Error::Extension(origin, _) = error else { + return Err(error.into()); + }; + assert_eq!(origin.file.as_deref(), Some(included.as_path())); + assert_eq!(origin.location.start.line, 3); + } + Ok(()) +} From 6f32f9def1b7e02a1d7f6e02b4794b601d8cb315 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Thu, 19 Nov 2026 21:48:20 +0100 Subject: [PATCH 33/55] feat(parser): register raw styles for listing and literal blocks Dispatch a document-local processor at the committed delimiter before body substitutions. Preserve raw text, title, source spans, and source-position arguments, and construct the returned block through the same host path as a block macro. Refs: SC-547 --- acdc-parser/CHANGELOG.md | 2 + acdc-parser/README.adoc | 13 ++ acdc-parser/README.md | 13 ++ acdc-parser/src/extensions/block_style.rs | 129 ++++++++++++ acdc-parser/src/extensions/builder.rs | 12 +- acdc-parser/src/extensions/deferred.rs | 45 +++- acdc-parser/src/extensions/editor.rs | 4 +- acdc-parser/src/extensions/mod.rs | 3 + acdc-parser/src/extensions/recognition.rs | 36 +++- acdc-parser/src/extensions/registry.rs | 60 +++++- acdc-parser/src/extensions/session.rs | 118 +++++++---- .../src/grammar/document/construction.rs | 39 ++++ .../grammar/document/construction/tests.rs | 66 +++--- .../src/grammar/document/coordinator.rs | 12 +- acdc-parser/src/grammar/document/delimited.rs | 14 ++ acdc-parser/src/grammar/document/generated.rs | 4 +- .../src/grammar/document/table/streaming.rs | 10 +- acdc-parser/src/source_tests.rs | 5 +- acdc-parser/tests/extensions.rs | 3 + acdc-parser/tests/extensions/raw_styles.rs | 194 ++++++++++++++++++ 20 files changed, 672 insertions(+), 110 deletions(-) create mode 100644 acdc-parser/src/extensions/block_style.rs create mode 100644 acdc-parser/tests/extensions/raw_styles.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 8b28cdc7b..703606983 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. + - Block macro handlers can return a `BlockBuilder` directly with `.into()`. Tree processors see the resulting block with the invocation’s title, ID, roles, and source location. - Include processors can supply virtual content. They see attributes set by earlier block macros and follow the caller's include permissions, selection options, and expansion limits. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index db0e7b088..317d80348 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2070,6 +2070,19 @@ The image inherits the invocation's title, ID, roles, and source location. Tree processors see the image as soon as they run. Use `BlockMacroOutput::Deferred` when construction needs the rest of the document. +Register a raw block style with `RegistryBuilder::register_block_style` and +`BlockStyle::raw`. Select `RawBlockContext::Listing`, `RawBlockContext::Literal`, +or both. The handler receives `RawBlockInput` after include and conditional processing, +with whitespace and the final newline before the closing delimiter preserved. +It can read the original title, body and block locations, source-position +attributes, and the substitutions declared for the body. Positional arguments +can be named with `with_positional_attributes`. Named values take precedence, +and `with_defaults` fills missing values. + +Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume +the invocation. The output inherits the title, ID, and roles. The input style +has been consumed. Other delimiters keep their ordinary behavior. + `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 0cb6a8856..e024a57ec 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1714,6 +1714,19 @@ The image inherits the invocation's title, ID, roles, and source location. Tree processors see the image as soon as they run. Use `BlockMacroOutput::Deferred` when construction needs the rest of the document. +Register a raw block style with `RegistryBuilder::register_block_style` and +`BlockStyle::raw`. Select `RawBlockContext::Listing`, `RawBlockContext::Literal`, +or both. The handler receives `RawBlockInput` after include and conditional processing, +with whitespace and the final newline before the closing delimiter preserved. +It can read the original title, body and block locations, source-position +attributes, and the substitutions declared for the body. Positional arguments +can be named with `with_positional_attributes`. Named values take precedence, +and `with_defaults` fills missing values. + +Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume +the invocation. The output inherits the title, ID, and roles. The input style +has been consumed. Other delimiters keep their ordinary behavior. + `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects diff --git a/acdc-parser/src/extensions/block_style.rs b/acdc-parser/src/extensions/block_style.rs new file mode 100644 index 000000000..c2da48b6c --- /dev/null +++ b/acdc-parser/src/extensions/block_style.rs @@ -0,0 +1,129 @@ +//! Registered styles that consume the preprocessed text of a delimited block. + +use std::sync::Arc; + +use crate::{ + BlockMetadata, ElementAttributes, SourceLocation, Substitution, ast::DocumentAttributesRef, +}; + +use super::{BlockBuilder, TitleSource, source::SourceRegistration}; + +/// Delimited source forms supported by a raw block style. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum RawBlockContext { + Listing, + Literal, +} + +/// Input borrowed by a [`RawBlockProcessor`] before the host interprets the block body. +#[derive(Debug)] +#[non_exhaustive] +pub struct RawBlockInput<'a> { + pub context: RawBlockContext, + /// Text between the delimiter lines, including its final newline when present. + pub body: &'a str, + pub body_location: &'a SourceLocation, + /// The entire invocation, starting at its first metadata line. + pub location: &'a SourceLocation, + pub title: Option<&'a TitleSource<'a>>, + pub metadata: &'a BlockMetadata<'a>, + pub document_attributes: DocumentAttributesRef<'a>, +} + +impl RawBlockInput<'_> { + /// Ordered substitutions the source block would apply to its body. + #[must_use] + pub fn substitutions(&self) -> Vec { + self.metadata.substitutions.as_ref().map_or_else( + || crate::VERBATIM.to_vec(), + |spec| spec.resolve(crate::VERBATIM), + ) + } +} + +/// A document-local handler for a registered raw block style. +pub trait RawBlockProcessor { + /// Return an ordinary block, or `None` to consume this invocation. + /// + /// # Errors + /// An error stops parsing at the styled block's source location. + fn process(&mut self, block: RawBlockInput<'_>) -> Result, String>; +} + +impl RawBlockProcessor for F +where + F: FnMut(RawBlockInput<'_>) -> Result, String>, +{ + fn process(&mut self, block: RawBlockInput<'_>) -> Result, String> { + self(block) + } +} + +/// A named block style, its supported source forms, and its per-document factory. +#[derive(Clone, Debug)] +pub struct BlockStyle { + pub(super) handler: SourceRegistration, + pub(super) contexts: Vec, + positional: Vec, + defaults: ElementAttributes<'static>, +} + +impl BlockStyle { + /// Consume a raw body once its listing or literal delimiter has committed. + /// + /// ``` + /// use acdc_parser::{Options, extensions::{BlockBuilder, BlockStyle, RawBlockContext, RawBlockInput, Registry}}; + /// + /// let mut registry = Registry::builder(); + /// registry.register_block_style(BlockStyle::raw("sketch", [RawBlockContext::Listing], || { + /// |input: RawBlockInput<'_>| Ok(Some(BlockBuilder::literal(input.body))) + /// }))?; + /// let parsed = registry.build().parse("[sketch]\n----\n{x} *raw*\n----", &Options::default())?.finish()?; + /// assert_eq!(parsed.document().blocks().count(), 1); + /// # Ok::<(), Box>(()) + /// ``` + pub fn raw( + name: impl Into, + contexts: impl IntoIterator, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Self { + Self { + handler: SourceRegistration { + name: name.into(), + factory: Arc::new(move || Box::new(factory())), + }, + contexts: contexts.into_iter().collect(), + positional: Vec::new(), + defaults: ElementAttributes::default(), + } + } + + /// Name positional arguments after the style. Explicit named arguments win. + #[must_use] + pub fn with_positional_attributes( + mut self, + names: impl IntoIterator>, + ) -> Self { + self.positional = names.into_iter().map(Into::into).collect(); + self + } + + /// Supply fallback values for missing processor arguments. + #[must_use] + pub fn with_defaults(mut self, defaults: ElementAttributes<'static>) -> Self { + self.defaults = defaults; + self + } + + pub(crate) fn bind_arguments(&self, metadata: &mut BlockMetadata<'_>) { + let mut attributes = std::mem::take(&mut metadata.attributes); + super::recognition::bind_arguments( + &mut attributes, + &self.positional, + metadata.positional_attributes(), + &self.defaults, + ); + metadata.attributes = attributes; + } +} diff --git a/acdc-parser/src/extensions/builder.rs b/acdc-parser/src/extensions/builder.rs index 6f2010321..35c88bc40 100644 --- a/acdc-parser/src/extensions/builder.rs +++ b/acdc-parser/src/extensions/builder.rs @@ -195,18 +195,18 @@ impl BlockBuilder { self } - pub(super) fn build_at_macro<'a>( + pub(super) fn build_at_invocation<'a>( self, extension: &mut ExtensionBlock<'a>, state: &ParserState<'a>, ) -> Result, Error> { if self.id.as_deref() == Some("") { return Err(Error::Extension( - Box::new(extension.invocation.location.clone()), + Box::new(extension.invocation.location().clone()), "output ID must not be empty".into(), )); } - let prepared = state.prepare_macro_output(&self, extension)?; + let prepared = state.prepare_block_output(&self, extension)?; let mut metadata = prepared.metadata; for warning in prepared.warnings { state.add_warning(warning); @@ -214,7 +214,9 @@ impl BlockBuilder { if let Some(kind) = self.caption_kind(metadata.style) { metadata.caption = Some(Caption::resolve( &metadata, - &extension.invocation.document_attributes, + extension + .invocation + .document_attributes(&state.document_attributes), kind, )); } @@ -227,7 +229,7 @@ impl BlockBuilder { |inline| { inline.build(state.arena, location, |_, _| { Err(Error::Extension( - Box::new(extension.invocation.location.clone()), + Box::new(extension.invocation.location().clone()), "captured displays require a tree processor".into(), )) }) diff --git a/acdc-parser/src/extensions/deferred.rs b/acdc-parser/src/extensions/deferred.rs index 4cd4c4475..836196fe0 100644 --- a/acdc-parser/src/extensions/deferred.rs +++ b/acdc-parser/src/extensions/deferred.rs @@ -1,8 +1,8 @@ use serde::{Serialize, Serializer, ser::SerializeMap}; -use crate::{BlockMetadata, Location, Title}; +use crate::{BlockMetadata, DocumentAttributes, Location, SourceLocation, Title}; -use super::{MacroInvocation, TargetId}; +use super::{MacroInvocation, RawBlockContext, TargetId}; /// An opaque identity valid only in the document session that allocated it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -25,6 +25,36 @@ impl DeferredBlock { } } +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Invocation<'a> { + Macro(MacroInvocation<'a>), + Style { + context: RawBlockContext, + body: &'a str, + body_location: SourceLocation, + location: SourceLocation, + }, +} + +impl<'a> Invocation<'a> { + pub(crate) fn location(&self) -> &SourceLocation { + match self { + Self::Macro(call) => &call.location, + Self::Style { location, .. } => location, + } + } + + pub(crate) fn document_attributes<'b>( + &'b self, + current: &'b DocumentAttributes<'a>, + ) -> &'b DocumentAttributes<'a> { + match self { + Self::Macro(call) => &call.document_attributes, + Self::Style { .. } => current, + } + } +} + /// A deferred block that must be resolved before conversion. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -33,7 +63,7 @@ pub struct ExtensionBlock<'a> { pub(crate) title: Title<'a>, pub(crate) location: Location, pub(crate) processor: usize, - pub(crate) invocation: MacroInvocation<'a>, + pub(crate) invocation: Invocation<'a>, pub(crate) placeholder: Option, } @@ -49,9 +79,12 @@ impl Serialize for ExtensionBlock<'_> { let mut map = serializer.serialize_map(None)?; map.serialize_entry("name", "extension")?; map.serialize_entry("type", "block")?; - map.serialize_entry("macro", &self.invocation.name)?; - map.serialize_entry("target", &self.invocation.target)?; - map.serialize_entry("attributes", &self.invocation.attributes)?; + let Invocation::Macro(call) = &self.invocation else { + return Err(serde::ser::Error::custom("unprocessed raw block style")); + }; + map.serialize_entry("macro", &call.name)?; + map.serialize_entry("target", &call.target)?; + map.serialize_entry("attributes", &call.attributes)?; map.serialize_entry("metadata", &self.metadata)?; map.serialize_entry("title", &self.title)?; map.serialize_entry("location", &self.location)?; diff --git a/acdc-parser/src/extensions/editor.rs b/acdc-parser/src/extensions/editor.rs index 6a6c501cd..5cb382aee 100644 --- a/acdc-parser/src/extensions/editor.rs +++ b/acdc-parser/src/extensions/editor.rs @@ -170,7 +170,9 @@ impl<'doc> DocumentEditor<'doc> { target: &TargetId, block: &super::ExtensionBlock<'_>, ) -> Result<(), Error> { - if self.owner == Some(block.invocation.name.as_ref()) { + if let super::Invocation::Macro(call) = &block.invocation + && self.owner == Some(call.name.as_ref()) + { Ok(()) } else { Err(self.error( diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 90056eee4..dce47dac5 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -189,6 +189,9 @@ //! blocks in both profiles and compatibility modes. mod block_macro; +mod block_style; +pub use block_style::{BlockStyle, RawBlockContext, RawBlockInput, RawBlockProcessor}; +pub(crate) use deferred::Invocation; mod builder; mod deferred; mod display; diff --git a/acdc-parser/src/extensions/recognition.rs b/acdc-parser/src/extensions/recognition.rs index ae85dd867..b10a02718 100644 --- a/acdc-parser/src/extensions/recognition.rs +++ b/acdc-parser/src/extensions/recognition.rs @@ -71,19 +71,16 @@ pub(crate) fn recognize<'a>( positional.push((!empty_slot).then_some(value)); } } - for (name, value) in descriptor.positional.iter().zip(&positional) { - if let Some(value) = value { - attributes.insert_if_absent( - Cow::Borrowed(state.intern_str(name)), - AttributeValue::String(Cow::Borrowed(value)), - ); - } - } - attributes.merge_defaults(descriptor.defaults.clone()); + bind_arguments( + &mut attributes, + &descriptor.positional, + positional.iter().copied(), + &descriptor.defaults, + ); Ok(Block::Extension(Box::new(ExtensionBlock { metadata, title, - invocation: MacroInvocation { + invocation: super::Invocation::Macro(MacroInvocation { name: Cow::Borrowed(name), source: Cow::Owned(source), target: Cow::Borrowed(target), @@ -94,9 +91,26 @@ pub(crate) fn recognize<'a>( attributes, document_attributes: DocumentAttributes::clone(&state.document_attributes), location: state.create_error_source_location(location.clone()), - }, + }), location, processor, placeholder: None, }))) } + +pub(super) fn bind_arguments<'a>( + attributes: &mut ElementAttributes<'a>, + names: &[String], + positions: impl Iterator>, + defaults: &ElementAttributes<'static>, +) { + for (name, value) in names.iter().zip(positions) { + if let Some(value) = value { + attributes.insert_if_absent( + Cow::Owned(name.clone()), + AttributeValue::String(Cow::Borrowed(value)), + ); + } + } + attributes.merge_defaults(defaults.clone()); +} diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 4d1c6b09e..087a3560c 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -3,8 +3,9 @@ use std::{collections::HashMap, path::Path, sync::Arc}; use crate::{Error, Options, ParseResult}; use super::{ - BlockMacro, DocumentEditor, ExtensionParseResult, IncludeProcessor, IncludeProcessors, Session, - SourcePreprocessor, TreeProcessorRegistration, source::SourceRegistration, + BlockMacro, BlockStyle, DocumentEditor, ExtensionParseResult, IncludeProcessor, + IncludeProcessors, RawBlockContext, Session, SourcePreprocessor, TreeProcessorRegistration, + source::SourceRegistration, }; /// A registration rejected before any document is parsed. @@ -19,6 +20,8 @@ pub enum RegistrationError { DuplicateName(String), #[error("block macro is not registered: {0}")] UnknownName(String), + #[error("block style is already registered: {0}")] + DuplicateBlockStyle(String), #[error("tree processor is already registered: {0}")] DuplicateTreeProcessor(String), #[error("source preprocessor is already registered: {0}")] @@ -32,6 +35,7 @@ pub enum RegistrationError { /// Builds a registry without modifying existing registry snapshots. #[derive(Debug, Default)] pub struct RegistryBuilder { + styles: Vec, macros: Vec, names: HashMap, trees: Vec, @@ -45,6 +49,9 @@ impl RegistryBuilder { /// # Errors /// Rejects duplicate registrations without changing this builder. pub fn extend(&mut self, registry: &Registry) -> Result<&mut Self, RegistrationError> { + for style in ®istry.0.styles { + self.check_style_name(&style.handler.name)?; + } for descriptor in ®istry.0.macros { if self.names.contains_key(&descriptor.name) { return Err(RegistrationError::DuplicateName(descriptor.name.clone())); @@ -69,6 +76,7 @@ impl RegistryBuilder { } self.preprocessors .extend_from_slice(®istry.0.preprocessors); + self.styles.extend_from_slice(®istry.0.styles); self.includes.extend_from_slice(®istry.0.includes); let offset = self.macros.len(); self.names.extend( @@ -84,6 +92,28 @@ impl RegistryBuilder { Ok(self) } + /// Register a style for the selected raw delimited block contexts. + /// Each document gets a fresh processor. Style names are independent of macro names. + /// + /// # Errors + /// Rejects invalid identifiers and duplicate style names. + pub fn register_block_style( + &mut self, + style: BlockStyle, + ) -> Result<&mut Self, RegistrationError> { + self.check_style_name(&style.handler.name)?; + self.styles.push(style); + Ok(self) + } + + fn check_style_name(&self, name: &str) -> Result<(), RegistrationError> { + validate_identifier(name)?; + if self.styles.iter().any(|style| style.handler.name == name) { + return Err(RegistrationError::DuplicateBlockStyle(name.to_owned())); + } + Ok(()) + } + /// Append an entry-source preprocessor in registration order. /// /// # Errors @@ -201,6 +231,7 @@ impl RegistryBuilder { #[must_use] pub fn build(self) -> Registry { Registry(Arc::new(RegistryData { + styles: self.styles, macros: self.macros, names: self.names, trees: self.trees, @@ -245,6 +276,7 @@ fn validate_identifier(name: &str) -> Result<(), RegistrationError> { #[derive(Debug, Default)] struct RegistryData { + styles: Vec, macros: Vec, names: HashMap, trees: Vec, @@ -268,7 +300,10 @@ impl Registry { } fn has_input_processors(&self) -> bool { - !(self.0.macros.is_empty() && self.0.preprocessors.is_empty() && self.0.includes.is_empty()) + !(self.0.styles.is_empty() + && self.0.macros.is_empty() + && self.0.preprocessors.is_empty() + && self.0.includes.is_empty()) } pub(crate) fn preprocessors(&self) -> impl Iterator> + '_ { @@ -366,10 +401,24 @@ impl Registry { .map(|descriptor| (index, descriptor)) } + pub(crate) fn raw_style( + &self, + name: &str, + context: RawBlockContext, + ) -> Option<(usize, &BlockStyle)> { + self.0 + .styles + .iter() + .enumerate() + .find(|(_, style)| style.handler.name == name && style.contexts.contains(&context)) + } + /// A conservative dispatch filter, not a syntax recognizer. Includes can /// introduce registered names that are absent from the entry source. pub(crate) fn may_execute(&self, source: &str) -> bool { !self.0.preprocessors.is_empty() + || (!self.0.styles.is_empty() + && (source.contains("----") || source.contains("....") || source.contains("```"))) || source.match_indices("::").any(|(end, _)| { let name = source[..end] .rsplit(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-') @@ -386,6 +435,11 @@ impl Registry { .iter() .map(|entry| (entry.factory)()) .collect(), + self.0 + .styles + .iter() + .map(|entry| (entry.handler.factory)()) + .collect(), self.0.trees.iter().map(|entry| (entry.factory)()).collect(), ) } diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index b25f66328..24ea4b85b 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -3,12 +3,14 @@ use std::{cell::OnceCell, fmt}; use crate::{Block, Error, ParseResult, grammar::ParserState}; use super::{ - BlockBuilder, BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, - PlaceholderId, TargetId, TreeProcessor, query::TargetIndex, target::DocumentIdentity, + BlockBuilder, BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, Invocation, + PlaceholderId, RawBlockInput, RawBlockProcessor, TargetId, TreeProcessor, query::TargetIndex, + target::DocumentIdentity, }; pub(crate) struct Session { processors: Vec>, + styles: Box<[Box]>, pub(super) tree_processors: Vec>, pub(super) deferred: Vec, pub(super) processed_blocks: bool, @@ -110,10 +112,12 @@ impl ExtensionParseResult { impl Session { pub(super) fn new( processors: Vec>, + styles: Box<[Box]>, tree_processors: Vec>, ) -> Self { Self { processors, + styles, tree_processors, deferred: Vec::new(), processed_blocks: false, @@ -133,49 +137,77 @@ impl Session { ) -> Result { if let Block::Extension(extension) = block { self.processed_blocks = true; - let output = self - .processors - .get_mut(extension.processor) - .ok_or_else(|| { - Error::Extension( - Box::new(extension.invocation.location.clone()), - "processor is absent from the document session".into(), - ) - })? - .process(&extension.invocation, context) - .map_err(|message| { - Error::Extension(Box::new(extension.invocation.location.clone()), message) - })?; - let builder = match output { - BlockMacroOutput::Paragraph(text) => BlockBuilder::paragraph(text), - BlockMacroOutput::Block(builder) => builder, - BlockMacroOutput::None => return Ok(false), - BlockMacroOutput::Deferred => { - let placeholder = PlaceholderId(self.deferred.len()); - extension.placeholder = Some(placeholder); - self.deferred.push(DeferredBlock { - placeholder, - invocation: extension.invocation.to_owned_invocation(), - target: TargetId { - document: self.identity().clone(), - slot: placeholder.0, - }, - }); - return Ok(true); + let origin = extension.invocation.location(); + let fail = |message| Error::Extension(Box::new(origin.clone()), message); + let builder = match &extension.invocation { + Invocation::Style { + context, + body, + body_location, + .. + } => { + let processor = self.styles.get_mut(extension.processor).ok_or_else(|| { + fail("style processor is absent from the document session".into()) + })?; + let raw = RawBlockInput { + context: *context, + body, + body_location, + location: origin, + document_attributes: state.document_attributes.as_ref().into(), + metadata: &extension.metadata, + title: extension.title.source(), + }; + let Some(builder) = processor.process(raw).map_err(fail)? else { + return Ok(false); + }; + // The handler consumes the input style. + extension.metadata.style = None; + builder } - }; - *block = builder.build_at_macro(extension, state).map_err(|error| { - if matches!(error, Error::Extension(..)) { - return error; + Invocation::Macro(call) => { + let output = self + .processors + .get_mut(extension.processor) + .ok_or_else(|| { + fail("processor is absent from the document session".into()) + })? + .process(call, context) + .map_err(fail)?; + match output { + BlockMacroOutput::Paragraph(text) => BlockBuilder::paragraph(text), + BlockMacroOutput::Block(builder) => builder, + BlockMacroOutput::None => return Ok(false), + BlockMacroOutput::Deferred => { + let placeholder = PlaceholderId(self.deferred.len()); + extension.placeholder = Some(placeholder); + self.deferred.push(DeferredBlock { + placeholder, + invocation: call.to_owned_invocation(), + target: TargetId { + document: self.identity().clone(), + slot: placeholder.0, + }, + }); + return Ok(true); + } + } } - let message = if let Error::Parse(_, message) | Error::PegParse(_, message) = error - { - message - } else { - error.to_string() - }; - Error::Extension(Box::new(extension.invocation.location.clone()), message) - })?; + }; + *block = builder + .build_at_invocation(extension, state) + .map_err(|error| { + if matches!(error, Error::Extension(..)) { + return error; + } + let message = + if let Error::Parse(_, message) | Error::PegParse(_, message) = error { + message + } else { + error.to_string() + }; + Error::Extension(Box::new(extension.invocation.location().clone()), message) + })?; } Ok(true) } diff --git a/acdc-parser/src/grammar/document/construction.rs b/acdc-parser/src/grammar/document/construction.rs index 844655e76..52eeb56e6 100644 --- a/acdc-parser/src/grammar/document/construction.rs +++ b/acdc-parser/src/grammar/document/construction.rs @@ -2,6 +2,7 @@ use crate::{ Block, Error, + extensions::{ExtensionBlock, Invocation}, grammar::{ParserState, helpers::BlockParsingMetadata}, }; @@ -96,6 +97,44 @@ impl<'a> DelimitedConstruction<'a> { self, state: &mut ParserState<'a>, ) -> Result<(Block<'a>, Option>), Error> { + let p = &self.params; + if let Some(style) = self.metadata.metadata.style + && let Some(registry) = &state.options.extensions + && let Some(context) = p.kind.raw_context() + && let Some((processor, descriptor)) = registry.raw_style(style, context) + { + let mut metadata = self.metadata.metadata; + descriptor.bind_arguments(&mut metadata); + super::delimited::resolve_delimited_close(state, p)?; + let location = state.create_block_location(p.start, p.end, p.offset); + let body_start = p.content_start + p.offset; + let body_location = if p.source_text.is_empty() { + state.create_location(body_start, body_start) + } else { + state.create_block_location( + p.content_start, + p.content_start + p.source_text.len(), + p.offset, + ) + }; + metadata.move_positional_attributes_to_attributes(); + return Ok(( + Block::Extension(Box::new(ExtensionBlock { + processor, + invocation: Invocation::Style { + context, + body: p.source_text, + body_location: state.create_error_source_location(body_location), + location: state.create_error_source_location(location.clone()), + }, + title: self.metadata.title, + metadata, + location, + placeholder: None, + })), + None, + )); + } let mut content = CaptureContent::default(); let block = build_delimited_block_with_parser(state, &self.metadata, &self.params, &mut content)?; diff --git a/acdc-parser/src/grammar/document/construction/tests.rs b/acdc-parser/src/grammar/document/construction/tests.rs index 699c23d9f..26647951a 100644 --- a/acdc-parser/src/grammar/document/construction/tests.rs +++ b/acdc-parser/src/grammar/document/construction/tests.rs @@ -236,6 +236,16 @@ impl crate::extensions::BlockMacroProcessor for UnusedProcessor { } } +fn macro_call<'b, 'a>(block: &'b Block<'a>) -> Option<&'b crate::extensions::MacroInvocation<'a>> { + if let Block::Extension(extension) = block + && let crate::extensions::Invocation::Macro(call) = &extension.invocation + { + Some(call) + } else { + None + } +} + fn probe_options(mode: CompatibilityMode) -> Result, Box> { let mut registry = crate::extensions::Registry::builder(); registry.register(crate::extensions::BlockMacro::new("probe", || { @@ -259,9 +269,9 @@ fn table_driver_commits_each_duplicate_with_isolated_attributes() -> TestResult &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { + if let Some(call) = macro_call(block) { calls.push(( - extension.invocation.target.to_string(), + call.target.to_string(), state.document_attributes.text("value").map(str::to_owned), )); let value = state.intern_str(&calls.len().to_string()); @@ -316,8 +326,8 @@ fn table_driver_ignores_macros_in_plain_literal_header_and_rejected_cells() -> T &mut state, ConstructionMode::Ordered, &mut |block, _| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); } Ok(()) }, @@ -349,8 +359,8 @@ fn table_driver_restores_cell_scope_after_handler_failure() -> TestResult { &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); assert_eq!(state.document_attributes.text("cell-only"), Some("local")); return Err(Error::Parse( Box::new(state.create_error_source_location(block.location().clone())), @@ -417,10 +427,10 @@ fn ordinary_list_driver_runs_attached_macros_before_later_principals() -> TestRe &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); Rc::make_mut(&mut state.document_attributes) - .set_text("value".into(), extension.invocation.target.clone()); + .set_text("value".into(), call.target.clone()); } Ok(()) }, @@ -482,8 +492,8 @@ fn ordinary_list_driver_restores_scopes_when_an_attached_handler_fails() -> Test &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); return Err(Error::Parse( Box::new(state.create_error_source_location(block.location().clone())), "stop".into(), @@ -532,10 +542,10 @@ fn callout_list_driver_commits_attached_macros_before_later_items() -> TestResul &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); Rc::make_mut(&mut state.document_attributes) - .set_text("value".into(), extension.invocation.target.clone()); + .set_text("value".into(), call.target.clone()); } Ok(()) }, @@ -574,8 +584,8 @@ fn callout_list_driver_restores_scope_after_handler_failure() -> TestResult { &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); assert!(state.callout_list_offset.is_some()); return Err(Error::Parse( Box::new(state.create_error_source_location(block.location().clone())), @@ -643,10 +653,10 @@ fn description_list_driver_runs_attachments_before_later_principals() -> TestRes &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); Rc::make_mut(&mut state.document_attributes) - .set_text("value".into(), extension.invocation.target.clone()); + .set_text("value".into(), call.target.clone()); } Ok(()) }, @@ -692,8 +702,8 @@ fn description_list_driver_does_not_recover_handler_failure(#[case] input: &str) &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); return Err(Error::Parse( Box::new(state.create_error_source_location(block.location().clone())), "stop".into(), @@ -739,8 +749,8 @@ fn description_list_driver_preserves_native_macro_recovery(#[case] input: &str) &mut ordered_state, ConstructionMode::Ordered, &mut |block, _| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); } Ok(()) }, @@ -787,10 +797,10 @@ fn abbreviated_quote_driver_commits_children_in_source_order(#[case] input: &str &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); Rc::make_mut(&mut state.document_attributes) - .set_text("value".into(), extension.invocation.target.clone()); + .set_text("value".into(), call.target.clone()); } if let Block::Paragraph(paragraph) = block { paragraphs.push( @@ -833,8 +843,8 @@ fn abbreviated_quote_driver_stops_after_handler_failure(#[case] input: &str) -> &mut state, ConstructionMode::Ordered, &mut |block, state| { - if let Block::Extension(extension) = block { - calls.push(extension.invocation.target.to_string()); + if let Some(call) = macro_call(block) { + calls.push(call.target.to_string()); return Err(Error::Parse( Box::new(state.create_error_source_location(block.location().clone())), "stop".into(), diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index 57f04b473..5bd94ca2f 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -28,7 +28,7 @@ use super::{ pub(super) struct Execution<'handler, F> { callback: &'handler mut F, failed: bool, - macro_callbacks: usize, + block_callbacks: usize, } impl<'handler, F> Execution<'handler, F> { @@ -36,7 +36,7 @@ impl<'handler, F> Execution<'handler, F> { Self { callback, failed: false, - macro_callbacks: 0, + block_callbacks: 0, } } #[inline] @@ -49,14 +49,14 @@ impl<'handler, F> Execution<'handler, F> { where F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, { - self.macro_callbacks += usize::from(matches!(block, Block::Extension(_))); + self.block_callbacks += usize::from(matches!(block, Block::Extension(_))); let result = (self.callback)(block, state, output); self.failed |= result.is_err(); result } - pub(super) const fn macro_callbacks(&self) -> usize { - self.macro_callbacks + pub(super) const fn block_callbacks(&self) -> usize { + self.block_callbacks } pub(super) fn failed(&self) -> bool { @@ -301,6 +301,8 @@ impl BlockCursor { Ok(started) => started, Err(error) => return Ok(Err(error)), }; + // Extension output resolves its own caption at the invocation. + let needs_caption = needs_caption && !matches!(block, Block::Extension(_)); let child = if let Block::Section(section) = &block && self.mode == ConstructionMode::Ordered { diff --git a/acdc-parser/src/grammar/document/delimited.rs b/acdc-parser/src/grammar/document/delimited.rs index e90a61079..a96a3c1dd 100644 --- a/acdc-parser/src/grammar/document/delimited.rs +++ b/acdc-parser/src/grammar/document/delimited.rs @@ -182,6 +182,20 @@ impl DelimitedKind { ) && !matches!(style, Some("comment" | "verse")) } + pub(super) fn raw_context(self) -> Option { + use crate::extensions::RawBlockContext; + match self { + Self::Listing => Some(RawBlockContext::Listing), + Self::Literal => Some(RawBlockContext::Literal), + Self::Comment + | Self::Example + | Self::Open + | Self::Sidebar + | Self::Passthrough + | Self::Quote => None, + } + } + pub(super) fn with_style(self, style: Option<&str>) -> Self { match (self, style) { (Self::Open | Self::Literal, Some("source" | "listing")) => Self::Listing, diff --git a/acdc-parser/src/grammar/document/generated.rs b/acdc-parser/src/grammar/document/generated.rs index 1843e6905..794537d5d 100644 --- a/acdc-parser/src/grammar/document/generated.rs +++ b/acdc-parser/src/grammar/document/generated.rs @@ -48,7 +48,7 @@ pub(crate) struct Prepared<'a> { } impl<'a> ParserState<'a> { - pub(crate) fn prepare_macro_output( + pub(crate) fn prepare_block_output( &self, builder: &BlockBuilder, extension: &mut ExtensionBlock<'a>, @@ -71,7 +71,7 @@ impl<'a> ParserState<'a> { builder, metadata, title, - &extension.invocation.location, + extension.invocation.location(), &extension.location, |input| Ok(Self::for_inline_parsing(input, self, self.inline_ctx)), ) diff --git a/acdc-parser/src/grammar/document/table/streaming.rs b/acdc-parser/src/grammar/document/table/streaming.rs index d2e03832a..3c33010e0 100644 --- a/acdc-parser/src/grammar/document/table/streaming.rs +++ b/acdc-parser/src/grammar/document/table/streaming.rs @@ -95,7 +95,7 @@ where struct CommittedCell<'a> { cell: TableCell<'a>, warnings: Vec, - macro_callbacks: usize, + block_callbacks: usize, used: bool, location: SourceLocation, } @@ -169,7 +169,7 @@ impl<'a> TableReader<'a> { where F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, { - let before = accepted.macro_callbacks(); + let before = accepted.block_callbacks(); input.begin_cell(self.separator, self.delimiter, start); let mut warnings = Vec::new(); let result = if spec.style == Some(ColumnStyle::AsciiDoc) { @@ -230,7 +230,7 @@ impl<'a> TableReader<'a> { CommittedCell { cell, warnings, - macro_callbacks: accepted.macro_callbacks() - before, + block_callbacks: accepted.block_callbacks() - before, used: false, location: state.create_error_source_location(state.create_location(key, key)), }, @@ -365,12 +365,12 @@ impl BlockCursor { if let Some(discarded) = parser .cells .values() - .filter(|cell| !cell.used && cell.macro_callbacks > 0) + .filter(|cell| !cell.used && cell.block_callbacks > 0) .min_by_key(|cell| cell.location.location.absolute_start) { return Err(Error::Extension( Box::new(discarded.location.clone()), - "table layout discarded a cell after its block macro executed".into(), + "table layout discarded a cell after its block processor executed".into(), )); } match accepted.run(&mut block, state, output) { diff --git a/acdc-parser/src/source_tests.rs b/acdc-parser/src/source_tests.rs index 20f3481d1..153324166 100644 --- a/acdc-parser/src/source_tests.rs +++ b/acdc-parser/src/source_tests.rs @@ -635,7 +635,10 @@ impl SourceHandler for Configure { let Block::Extension(extension) = block else { return Ok(Vec::new()); }; - self.events.push(extension.invocation.target.to_string()); + let crate::extensions::Invocation::Macro(call) = &extension.invocation else { + return Ok(Vec::new()); + }; + self.events.push(call.target.to_string()); Ok(vec![( "enabled".into(), DocumentAttributeAssignment::Set("yes".into()), diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index 438351ff8..5099870c8 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -534,3 +534,6 @@ fn invalid_direct_macro_output_reports_the_included_invocation() -> TestResult { } Ok(()) } + +#[path = "extensions/raw_styles.rs"] +mod raw_styles; diff --git a/acdc-parser/tests/extensions/raw_styles.rs b/acdc-parser/tests/extensions/raw_styles.rs new file mode 100644 index 000000000..239da85e3 --- /dev/null +++ b/acdc-parser/tests/extensions/raw_styles.rs @@ -0,0 +1,194 @@ +use acdc_parser::{ + CompatibilityMode, ElementAttributes, Error, Options, SafeMode, Substitution, + ast::{BlockKind, BlockRef}, + extensions::{ + BlockBuilder, BlockContext, BlockStyle, RawBlockContext, RawBlockInput, RegistrationError, + Registry, TreeProcessorRegistration, + }, +}; + +use super::{ObserveLogo, TestResult}; + +fn sketch() -> BlockStyle { + let mut defaults = ElementAttributes::default(); + defaults.set("format".into(), "png".into()); + defaults.set("theme".into(), "light".into()); + BlockStyle::raw("sketch", [RawBlockContext::Listing], || { + let mut calls = 0; + move |block: RawBlockInput<'_>| { + calls += 1; + assert_eq!(calls, 1); + assert_eq!(block.context, RawBlockContext::Listing); + assert_eq!(block.body, " {label} *raw* <1>\n\nfootnote:[from body]\n"); + assert_eq!(block.metadata.style, Some("sketch")); + assert_eq!( + block.title.map(super::TitleSource::raw_source), + Some("{label} *sketch*") + ); + assert_eq!( + block + .document_attributes + .get("label") + .and_then(acdc_parser::DocumentAttributeValue::text), + Some("Early") + ); + assert_eq!(block.location.location.start.line, 1); + assert_eq!(block.body_location.file, block.location.file); + assert_eq!(block.body_location.location.start.line, 4); + assert!(block.substitutions().contains(&Substitution::Macros)); + for (name, expected) in [("target", "brand"), ("format", "svg"), ("theme", "light")] { + assert_eq!( + block + .metadata + .attributes + .get(name) + .map(ToString::to_string) + .as_deref(), + Some(expected) + ); + } + Ok(Some(BlockBuilder::image("brand.svg"))) + } + }) + .with_positional_attributes(["target", "format"]) + .with_defaults(defaults) +} + +#[test] +fn style_builds_an_image_from_raw_included_source_before_tree_processing() -> TestResult { + let dir = tempfile::tempdir()?; + let file = dir.path().join("sketch.adoc"); + std::fs::write( + &file, + ".{label} *sketch*\n[sketch#brand.wide,brand,pdf,format=svg,subs=normal]\n----\n {label} *raw* <1>\n\nfootnote:[from body]\n----", + )?; + let mut package = Registry::builder(); + package.register_block_style(sketch())?; + let mut builder = Registry::builder(); + builder.extend(&package.build())?; + builder.register_tree_processor(TreeProcessorRegistration::new("observe", || ObserveLogo))?; + let registry = builder.build(); + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder() + .with_base_dir(dir.path()) + .with_safe_mode(SafeMode::Safe) + .with_compatibility_mode(mode) + .build()?; + let result = registry.parse( + ":label: Early\n\n====\ninclude::sketch.adoc[]\n====\n\n:label: Late", + &options, + )?; + let view = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("missing image")?; + assert_eq!(view.output_id(), Some("brand")); + assert_eq!(view.source_location().file.as_deref(), Some(file.as_path())); + assert_eq!(view.source_location().location.end.line, 7); + let BlockKind::Image(image) = view.block().kind() else { + return Err("missing image".into()); + }; + assert!(image.roles().contains("wide")); + assert_eq!(image.source().to_string(), "brand.svg"); + assert_eq!( + view.title_source().map(super::TitleSource::raw_source), + Some("{label} *sketch*") + ); + let parsed = result.finish()?; + assert_eq!(parsed.document().footnotes().count(), 0); + assert_eq!(parsed.warnings(), []); + } + Ok(()) +} + +#[test] +fn only_registered_delimiters_are_consumed_and_empty_bodies_are_located() -> TestResult { + let style = BlockStyle::raw("consume", [RawBlockContext::Literal], || { + |block: RawBlockInput<'_>| { + assert_eq!(block.body, ""); + assert_eq!(block.body_location.location.start.line, 3); + Ok(None) + } + }); + let mut builder = Registry::builder(); + builder.register_block_style(style.clone())?; + assert!( + matches!(builder.register_block_style(style), Err(RegistrationError::DuplicateBlockStyle(name)) if name == "consume") + ); + let registry = builder.build(); + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let opts = Options::builder().with_compatibility_mode(mode).build()?; + let result = registry.parse("[consume]\n....\n....\n\n[consume]\n----\nstill a listing\n----\n\n[other]\n....\nstill literal\n....", &opts)?.finish()?; + let kinds: Vec<_> = result.document().blocks().map(BlockRef::kind).collect(); + assert!(matches!( + kinds.as_slice(), + [BlockKind::Listing(_), BlockKind::Literal(_)] + )); + } + Ok(()) +} + +#[test] +fn unterminated_style_runs_once_and_handler_failures_keep_the_block_location() -> TestResult { + let mut builder = Registry::builder(); + builder.register_block_style(BlockStyle::raw("check", [RawBlockContext::Listing], || { + |block: RawBlockInput<'_>| { + if block.body == "invalid" { + return Err("invalid sketch".into()); + } + Ok(Some(BlockBuilder::literal(block.body))) + } + }))?; + let registry = builder.build(); + let result = registry + .parse("[check]\n----\nvalid", &Options::default())? + .finish()?; + assert_eq!(result.warnings().len(), 1); + assert!(matches!( + result.document().blocks().next().map(BlockRef::kind), + Some(BlockKind::Literal(_)) + )); + let failed = registry.parse("Intro.\n\n[check]\n----\ninvalid", &Options::default()); + assert!( + matches!(failed, Err(Error::Extension(origin, msg)) if msg == "invalid sketch" && origin.location.start.line == 3) + ); + Ok(()) +} + +#[test] +fn style_selection_and_inactive_styles_match_across_entry_points() -> TestResult { + let mut builder = Registry::builder(); + builder.register_block_style(BlockStyle::raw("stamp", [RawBlockContext::Literal], || { + |raw: RawBlockInput<'_>| Ok(Some(BlockBuilder::paragraph(raw.body.trim_end()))) + }))?; + let registry = builder.build(); + let options = Options::default(); + let source = ":selected: stamp\n\n[{selected}]\n....\nSeal\n...."; + let dir = tempfile::tempdir()?; + let path = dir.path().join("entry.adoc"); + std::fs::write(&path, source)?; + for parsed in [ + registry.parse(source, &options)?, + registry.parse_file(&path, &options)?, + registry.parse_from_reader(source.as_bytes(), &options)?, + ] { + let parsed = parsed.finish()?; + assert!( + parsed + .document() + .blocks() + .any(|block| matches!(block.kind(), BlockKind::Paragraph(_))) + ); + } + + let ordinary = ".Code\n[source,rust]\n----\nfn main() {}\n----\n\n[other]\n....\nliteral\n...."; + let native = acdc_parser::parse(ordinary, &options)?; + let inactive = registry.parse(ordinary, &options)?.finish()?; + assert_eq!( + serde_json::to_value(inactive.document())?, + serde_json::to_value(native.document())? + ); + assert_eq!(inactive.warnings(), native.warnings()); + Ok(()) +} From e3a2be19d5b23ae69b7d8da447e83f0b8fc4c370 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Fri, 20 Nov 2026 11:00:01 +0100 Subject: [PATCH 34/55] feat(parser): parse child blocks requested by registered styles Let a style hand its preprocessed body back to the document parser after its callback returns. Nested handlers share their document-local state and source locations. Limit active style requests and report excess nesting at the invocation. Refs SC-547 --- acdc-parser/CHANGELOG.md | 2 +- acdc-parser/README.adoc | 10 + acdc-parser/README.md | 10 + acdc-parser/src/extensions/block_style.rs | 62 +++++- acdc-parser/src/extensions/deferred.rs | 1 + acdc-parser/src/extensions/mod.rs | 5 +- acdc-parser/src/extensions/session.rs | 34 ++-- .../src/grammar/document/construction.rs | 13 +- .../src/grammar/document/coordinator.rs | 64 ++++++- acdc-parser/tests/extensions.rs | 3 + .../tests/extensions/compound_styles.rs | 178 ++++++++++++++++++ 11 files changed, 351 insertions(+), 31 deletions(-) create mode 100644 acdc-parser/tests/extensions/compound_styles.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 703606983..f33a1d71b 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. +- Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. A style registered with `BlockStyle::compound` can also request that its body be parsed as children of an open block. - Block macro handlers can return a `BlockBuilder` directly with `.into()`. Tree processors see the resulting block with the invocation’s title, ID, roles, and source location. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 317d80348..fa8df8c33 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2083,6 +2083,16 @@ Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume the invocation. The output inherits the title, ID, and roles. The input style has been consumed. Other delimiters keep their ordinary behavior. +Use `BlockStyle::compound` for a listing or literal style that can choose how +to handle its body. Returning `BlockStyleOutput::ParseChildren` creates an open +block with the invocation's title and metadata. Once the handler returns, +the parser reads the preprocessed body as AsciiDoc blocks and invokes nested +handlers in source order. Preprocessing runs once. A child macro can affect +directives the reader encounters after the enclosing body. Returning +`BlockStyleOutput::Block(builder)` or `BlockStyleOutput::None` skips child parsing. +Up to eight requested child parses can be active at once (`MAX_STYLE_NESTING`). +A further request reports an extension error at that invocation. + `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects diff --git a/acdc-parser/README.md b/acdc-parser/README.md index e024a57ec..6285d85ae 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1727,6 +1727,16 @@ Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume the invocation. The output inherits the title, ID, and roles. The input style has been consumed. Other delimiters keep their ordinary behavior. +Use `BlockStyle::compound` for a listing or literal style that can choose how +to handle its body. Returning `BlockStyleOutput::ParseChildren` creates an open +block with the invocation's title and metadata. Once the handler returns, +the parser reads the preprocessed body as AsciiDoc blocks and invokes nested +handlers in source order. Preprocessing runs once. A child macro can affect +directives the reader encounters after the enclosing body. Returning +`BlockStyleOutput::Block(builder)` or `BlockStyleOutput::None` skips child parsing. +Up to eight requested child parses can be active at once (`MAX_STYLE_NESTING`). +A further request reports an extension error at that invocation. + `Registry::parse`, `parse_file`, and `parse_from_reader` share these stages. Reader input preserves ordinary reader attributes and include-origin policy. `RegistryBuilder::extend` composes immutable registries in order and rejects diff --git a/acdc-parser/src/extensions/block_style.rs b/acdc-parser/src/extensions/block_style.rs index c2da48b6c..85a3400b9 100644 --- a/acdc-parser/src/extensions/block_style.rs +++ b/acdc-parser/src/extensions/block_style.rs @@ -42,20 +42,35 @@ impl RawBlockInput<'_> { } } +/// Result of a style callback registered with [`BlockStyle::compound`]. +#[derive(Debug)] +#[non_exhaustive] +pub enum BlockStyleOutput { + /// Parse this invocation's body as child blocks of an ordinary open block. + ParseChildren, + /// Emit the builder at the invocation's source location. + Block(BlockBuilder), + /// Consume the invocation and its body. + None, +} + +/// Maximum number of simultaneously active style-requested child parses. +pub const MAX_STYLE_NESTING: usize = 8; + /// A document-local handler for a registered raw block style. -pub trait RawBlockProcessor { - /// Return an ordinary block, or `None` to consume this invocation. +pub trait RawBlockProcessor> { + /// Select the output of the registered style. /// /// # Errors /// An error stops parsing at the styled block's source location. - fn process(&mut self, block: RawBlockInput<'_>) -> Result, String>; + fn process(&mut self, block: RawBlockInput<'_>) -> Result; } -impl RawBlockProcessor for F +impl RawBlockProcessor for F where - F: FnMut(RawBlockInput<'_>) -> Result, String>, + F: FnMut(RawBlockInput<'_>) -> Result, { - fn process(&mut self, block: RawBlockInput<'_>) -> Result, String> { + fn process(&mut self, block: RawBlockInput<'_>) -> Result { self(block) } } @@ -63,7 +78,7 @@ where /// A named block style, its supported source forms, and its per-document factory. #[derive(Clone, Debug)] pub struct BlockStyle { - pub(super) handler: SourceRegistration, + pub(super) handler: SourceRegistration>, pub(super) contexts: Vec, positional: Vec, defaults: ElementAttributes<'static>, @@ -87,6 +102,39 @@ impl BlockStyle { name: impl Into, contexts: impl IntoIterator, factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Self { + Self::compound(name, contexts, move || { + let mut handler = factory(); + move |input: RawBlockInput<'_>| { + handler + .process(input) + .map(|block| block.map_or(BlockStyleOutput::None, BlockStyleOutput::Block)) + } + }) + } + + /// Register a processor that may ask the host to parse this body's blocks. + /// Like [`Self::raw`], the processor receives the complete preprocessed body. + /// Child callbacks run in source order after this callback returns. + /// + /// ``` + /// use acdc_parser::{Options, ast::BlockKind, extensions::{ + /// BlockStyle, BlockStyleOutput, RawBlockContext, RawBlockInput, Registry, + /// }}; + /// + /// let mut registry = Registry::builder(); + /// registry.register_block_style(BlockStyle::compound("panel", [RawBlockContext::Listing], || { + /// |_: RawBlockInput<'_>| Ok(BlockStyleOutput::ParseChildren) + /// }))?; + /// let parsed = registry.build().parse("[panel]\n----\nA paragraph.\n----", &Options::default())?.finish()?; + /// let block = parsed.document().blocks().next().unwrap(); + /// assert!(matches!(block.kind(), BlockKind::Open(panel) if panel.blocks().count() == 1)); + /// # Ok::<(), Box>(()) + /// ``` + pub fn compound + 'static>( + name: impl Into, + contexts: impl IntoIterator, + factory: impl Fn() -> P + Send + Sync + 'static, ) -> Self { Self { handler: SourceRegistration { diff --git a/acdc-parser/src/extensions/deferred.rs b/acdc-parser/src/extensions/deferred.rs index 836196fe0..8892e9821 100644 --- a/acdc-parser/src/extensions/deferred.rs +++ b/acdc-parser/src/extensions/deferred.rs @@ -30,6 +30,7 @@ pub(crate) enum Invocation<'a> { Macro(MacroInvocation<'a>), Style { context: RawBlockContext, + parse_children: bool, body: &'a str, body_location: SourceLocation, location: SourceLocation, diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index dce47dac5..71999a606 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -190,7 +190,10 @@ mod block_macro; mod block_style; -pub use block_style::{BlockStyle, RawBlockContext, RawBlockInput, RawBlockProcessor}; +pub use block_style::{ + BlockStyle, BlockStyleOutput, MAX_STYLE_NESTING, RawBlockContext, RawBlockInput, + RawBlockProcessor, +}; pub(crate) use deferred::Invocation; mod builder; mod deferred; diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index 24ea4b85b..7f19b751b 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -3,14 +3,14 @@ use std::{cell::OnceCell, fmt}; use crate::{Block, Error, ParseResult, grammar::ParserState}; use super::{ - BlockBuilder, BlockMacroOutput, BlockMacroProcessor, DeferredBlock, DocumentQuery, Invocation, - PlaceholderId, RawBlockInput, RawBlockProcessor, TargetId, TreeProcessor, query::TargetIndex, - target::DocumentIdentity, + BlockBuilder, BlockMacroOutput, BlockMacroProcessor, BlockStyleOutput, DeferredBlock, + DocumentQuery, Invocation, PlaceholderId, RawBlockInput, RawBlockProcessor, TargetId, + TreeProcessor, query::TargetIndex, target::DocumentIdentity, }; pub(crate) struct Session { processors: Vec>, - styles: Box<[Box]>, + styles: Box<[Box>]>, pub(super) tree_processors: Vec>, pub(super) deferred: Vec, pub(super) processed_blocks: bool, @@ -112,7 +112,7 @@ impl ExtensionParseResult { impl Session { pub(super) fn new( processors: Vec>, - styles: Box<[Box]>, + styles: Box<[Box>]>, tree_processors: Vec>, ) -> Self { Self { @@ -137,15 +137,16 @@ impl Session { ) -> Result { if let Block::Extension(extension) = block { self.processed_blocks = true; - let origin = extension.invocation.location(); - let fail = |message| Error::Extension(Box::new(origin.clone()), message); - let builder = match &extension.invocation { + + let builder = match &mut extension.invocation { Invocation::Style { context, body, body_location, - .. + location: origin, + parse_children, } => { + let fail = |message| Error::Extension(Box::new(origin.clone()), message); let processor = self.styles.get_mut(extension.processor).ok_or_else(|| { fail("style processor is absent from the document session".into()) })?; @@ -158,14 +159,19 @@ impl Session { metadata: &extension.metadata, title: extension.title.source(), }; - let Some(builder) = processor.process(raw).map_err(fail)? else { - return Ok(false); - }; - // The handler consumes the input style. + let output = processor.process(raw).map_err(fail)?; extension.metadata.style = None; - builder + match output { + BlockStyleOutput::ParseChildren => { + *parse_children = true; + return Ok(true); + } + BlockStyleOutput::None => return Ok(false), + BlockStyleOutput::Block(builder) => builder, + } } Invocation::Macro(call) => { + let fail = |message| Error::Extension(Box::new(call.location.clone()), message); let output = self .processors .get_mut(extension.processor) diff --git a/acdc-parser/src/grammar/document/construction.rs b/acdc-parser/src/grammar/document/construction.rs index 52eeb56e6..f391383fe 100644 --- a/acdc-parser/src/grammar/document/construction.rs +++ b/acdc-parser/src/grammar/document/construction.rs @@ -9,7 +9,8 @@ use crate::{ use super::{ coordinator::BlockStepKind, delimited::{ - ContentParser, ContentRequest, DelimitedParams, build_delimited_block_with_parser, + ContentKind, ContentParser, ContentRequest, DelimitedParams, + build_delimited_block_with_parser, }, metadata::assign_block_caption, quotes::{QuoteParams, build_quote_with_parser}, @@ -123,6 +124,7 @@ impl<'a> DelimitedConstruction<'a> { processor, invocation: Invocation::Style { context, + parse_children: false, body: p.source_text, body_location: state.create_error_source_location(body_location), location: state.create_error_source_location(location.clone()), @@ -132,7 +134,14 @@ impl<'a> DelimitedConstruction<'a> { location, placeholder: None, })), - None, + Some(ContentRequest { + source: p.source_text, + offset: body_start, + parent_section_level: self.metadata.parent_section_level, + kind: ContentKind::Compound, + context: crate::grammar::state::BlockContext::Compound, + error_context: "Error parsing a block style's children", + }), )); } let mut content = CaptureContent::default(); diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index 5bd94ca2f..a778d51d9 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -1,7 +1,8 @@ //! Ordered construction at accepted block boundaries. use crate::{ - Block, Document, DocumentAttributes, Error, + Block, DelimitedBlock, DelimitedBlockType, Document, DocumentAttributes, Error, + extensions::{Invocation, MAX_STYLE_NESTING}, grammar::{ParserState, helpers::PositionWithOffset}, model::{SectionKind, SectionLevel}, }; @@ -29,6 +30,7 @@ pub(super) struct Execution<'handler, F> { callback: &'handler mut F, failed: bool, block_callbacks: usize, + style_depth: usize, } impl<'handler, F> Execution<'handler, F> { @@ -37,6 +39,7 @@ impl<'handler, F> Execution<'handler, F> { callback, failed: false, block_callbacks: 0, + style_depth: 0, } } #[inline] @@ -302,7 +305,8 @@ impl BlockCursor { Err(error) => return Ok(Err(error)), }; // Extension output resolves its own caption at the invocation. - let needs_caption = needs_caption && !matches!(block, Block::Extension(_)); + let style = matches!(block, Block::Extension(_)); + let needs_caption = needs_caption && !style; let child = if let Block::Section(section) = &block && self.mode == ConstructionMode::Ordered { @@ -325,10 +329,15 @@ impl BlockCursor { section.location = state.create_block_location(section.location.absolute_start, end, 0); state.finish_section_warnings(section.heading_location.absolute_start); } - if let Some(request) = request - && let Err(error) = construct_requested_content(&mut block, state, request, accepted) - { - return Ok(Err(error)); + if let Some(request) = request { + let result = if style { + construct_style_content(&mut block, state, request, accepted) + } else { + construct_requested_content(&mut block, state, request, accepted) + }; + if let Err(error) = result { + return Ok(Err(error)); + } } if needs_caption { if let Some(content) = table_content @@ -378,6 +387,49 @@ fn start_block<'a>( }) } +fn construct_style_content<'a, F>( + block: &mut Block<'a>, + state: &mut ParserState<'a>, + request: ContentRequest<'a>, + accepted: &mut Execution<'_, F>, +) -> Result<(), Error> +where + F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, +{ + let Block::Extension(extension) = block else { + return Ok(()); + }; + let Invocation::Style { + parse_children: true, + location, + .. + } = &extension.invocation + else { + return Ok(()); + }; + if accepted.style_depth >= MAX_STYLE_NESTING { + accepted.failed = true; + return Err(Error::Extension( + Box::new(location.clone()), + format!("block style child parsing exceeds the nesting limit of {MAX_STYLE_NESTING}"), + )); + } + let mut parent = DelimitedBlock::new( + DelimitedBlockType::DelimitedOpen(Vec::new()), + "--", + extension.location.clone(), + ); + parent.title = std::mem::take(&mut extension.title); + parent.metadata = std::mem::take(&mut extension.metadata); + parent.source_text = Some(request.source); + *block = Block::DelimitedBlock(parent); + + accepted.style_depth += 1; + let result = construct_requested_content(block, state, request, accepted); + accepted.style_depth -= 1; + result +} + fn construct_requested_content<'a, F>( block: &mut Block<'a>, state: &mut ParserState<'a>, diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index 5099870c8..8b3c541fa 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -537,3 +537,6 @@ fn invalid_direct_macro_output_reports_the_included_invocation() -> TestResult { #[path = "extensions/raw_styles.rs"] mod raw_styles; + +#[path = "extensions/compound_styles.rs"] +mod compound_styles; diff --git a/acdc-parser/tests/extensions/compound_styles.rs b/acdc-parser/tests/extensions/compound_styles.rs new file mode 100644 index 000000000..7fa0aca7f --- /dev/null +++ b/acdc-parser/tests/extensions/compound_styles.rs @@ -0,0 +1,178 @@ +use std::sync::{Arc, Mutex}; + +use acdc_parser::{ + CompatibilityMode, Error, Options, SafeMode, + ast::{BlockKind, BlockRef}, + extensions::{ + BlockBuilder, BlockMacro, BlockStyle, BlockStyleOutput, MAX_STYLE_NESTING, + MacroExecutionContext, MacroInvocation, RawBlockContext, RawBlockInput, Registry, + }, +}; + +use super::TestResult; + +#[test] +fn same_style_reenters_after_return_and_child_macros_keep_their_source() -> TestResult { + let directory = tempfile::tempdir()?; + let snippet = directory.path().join("panel.adoc"); + std::fs::write( + &snippet, + ".Outer\n[panel#outer.wide]\n-----\n[panel#inner]\n----\nlogo::acme[]\n----\n-----", + )?; + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let events = Arc::new(Mutex::new(Vec::new())); + let mut registry = Registry::builder(); + let style_events = Arc::clone(&events); + registry.register_block_style(BlockStyle::compound( + "panel", + [RawBlockContext::Listing], + move || { + let events = Arc::clone(&style_events); + let mut count = 0; + move |_: RawBlockInput<'_>| { + count += 1; + events + .lock() + .map_err(|e| e.to_string())? + .push(format!("panel {count}")); + Ok(BlockStyleOutput::ParseChildren) + } + }, + ))?; + let macro_events = Arc::clone(&events); + registry.register(BlockMacro::new("logo", move || { + let events = Arc::clone(¯o_events); + move |call: &MacroInvocation<'_>, ctx: &mut MacroExecutionContext| { + events + .lock() + .map_err(|e| e.to_string())? + .push(call.target.to_string()); + assert_eq!(call.location.location.start.line, 6); + ctx.set_attribute("seen", "yes"); + Ok(BlockBuilder::image("acme.svg").into()) + } + }))?; + let options = Options::builder() + .with_compatibility_mode(mode) + .with_base_dir(directory.path()) + .with_safe_mode(SafeMode::Safe) + .build()?; + let parsed = registry + .build() + .parse( + "include::panel.adoc[]\n\nifdef::seen[]\nAfter.\nendif::[]", + &options, + )? + .finish()?; + assert_eq!( + *events.lock().map_err(|e| e.to_string())?, + ["panel 1", "panel 2", "acme"] + ); + let mut top = parsed.document().blocks(); + let Some(BlockKind::Open(outer)) = top.next().map(BlockRef::kind) else { + return Err("missing outer open block".into()); + }; + assert_eq!(outer.id().ok_or("outer ID")?.as_str(), "outer"); + assert!(outer.roles().contains("wide")); + assert!(outer.title().is_some()); + let Some(BlockKind::Open(inner)) = outer.blocks().next().map(BlockRef::kind) else { + return Err("missing inner open block".into()); + }; + assert_eq!(inner.id().ok_or("inner ID")?.as_str(), "inner"); + let mut children = inner.blocks().map(BlockRef::kind); + assert!(matches!( + children.next(), + Some(BlockKind::DocumentAttribute(_)) + )); + let Some(BlockKind::Image(image)) = children.next() else { + return Err("missing nested logo".into()); + }; + assert_eq!(image.source().to_string(), "acme.svg"); + assert_eq!( + parsed.resolve_location(image.location()).file.as_deref(), + Some(snippet.as_path()) + ); + assert!(top.any(|block| matches!(block.kind(), BlockKind::Paragraph(_)))); + assert_eq!(parsed.warnings(), []); + } + Ok(()) +} + +fn nested(depth: usize) -> String { + let mut body = "Text.".to_owned(); + for level in 0..depth { + let delimiter = ".".repeat(4 + level); + body = format!("[panel]\n{delimiter}\n{body}\n{delimiter}"); + } + body +} + +#[test] +fn nesting_limit_is_per_active_child_parse_and_errors_at_the_included_invocation() -> TestResult { + let mut builder = Registry::builder(); + builder.register_block_style(BlockStyle::compound( + "panel", + [RawBlockContext::Literal], + || |_: RawBlockInput<'_>| Ok(BlockStyleOutput::ParseChildren), + ))?; + let registry = builder.build(); + let allowed = nested(MAX_STYLE_NESTING); + let parsed = registry + .parse(&format!("{allowed}\n\n{allowed}"), &Options::default())? + .finish()?; + assert_eq!(parsed.document().blocks().count(), 2); + let directory = tempfile::tempdir()?; + let file = directory.path().join("nested.adoc"); + let options = Options::builder() + .with_base_dir(directory.path()) + .with_safe_mode(SafeMode::Safe) + .build()?; + let excessive = nested(MAX_STYLE_NESTING + 1); + for prefix in ["", "* Item\n+\n"] { + std::fs::write(&file, format!("{prefix}{excessive}"))?; + let Err(Error::Extension(origin, msg)) = registry.parse("include::nested.adoc[]", &options) + else { + return Err("expected a located depth error".into()); + }; + assert!(msg.contains("nesting limit")); + assert_eq!(origin.file.as_deref(), Some(file.as_path())); + assert_eq!( + origin.location.start.line as usize, + prefix.lines().count() + MAX_STYLE_NESTING * 2 + 1 + ); + } + Ok(()) +} + +#[test] +fn only_requested_bodies_execute_children() -> TestResult { + let mut builder = Registry::builder(); + builder.register_block_style(BlockStyle::compound( + "panel", + [RawBlockContext::Listing], + || { + |input: RawBlockInput<'_>| { + Ok(match input.metadata.positional_attribute(0) { + Some("replace") => { + BlockStyleOutput::Block(BlockBuilder::paragraph("Replacement")) + } + Some("drop") => BlockStyleOutput::None, + _ => BlockStyleOutput::ParseChildren, + }) + } + }, + ))?; + builder.register(BlockMacro::new("fail", || { + |_: &MacroInvocation<'_>, _: &mut MacroExecutionContext| Err("child ran".into()) + }))?; + let registry = builder.build(); + let parsed = registry.parse("[panel,drop]\n----\nfail::[]\n----\n\n[panel,replace]\n----\nfail::[]\n----\n\n[panel]\n----\n----", &Options::default())?.finish()?; + let kinds: Vec<_> = parsed.document().blocks().map(BlockRef::kind).collect(); + assert!( + matches!(kinds.as_slice(), [BlockKind::Paragraph(_), BlockKind::Open(empty)] if empty.blocks().count() == 0) + ); + assert!( + matches!(registry.parse("[panel]\n----\nfail::[]\n----", &Options::default()), Err(Error::Extension(origin, msg)) if origin.location.start.line == 3 && msg == "child ran") + ); + Ok(()) +} From c24e569134b6967475ce9f1d21eb6eaddbb172a4 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Fri, 20 Nov 2026 12:16:00 +0100 Subject: [PATCH 35/55] test(parser): cover tree edits to compound style children Exercise paragraph source replacement through a registered tree processor in both compatibility modes. Check source-position attributes, warning repair, and exactly one style callback per document. Refs SC-547 --- .../tests/extensions/compound_styles.rs | 94 ++++++++++++++++++- 1 file changed, 89 insertions(+), 5 deletions(-) diff --git a/acdc-parser/tests/extensions/compound_styles.rs b/acdc-parser/tests/extensions/compound_styles.rs index 7fa0aca7f..52fa33957 100644 --- a/acdc-parser/tests/extensions/compound_styles.rs +++ b/acdc-parser/tests/extensions/compound_styles.rs @@ -1,11 +1,15 @@ -use std::sync::{Arc, Mutex}; +use std::sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, +}; use acdc_parser::{ - CompatibilityMode, Error, Options, SafeMode, - ast::{BlockKind, BlockRef}, + CompatibilityMode, Error, Options, SafeMode, WarningKind, + ast::{BlockKind, BlockRef, InlineKind, InlineRef}, extensions::{ - BlockBuilder, BlockMacro, BlockStyle, BlockStyleOutput, MAX_STYLE_NESTING, - MacroExecutionContext, MacroInvocation, RawBlockContext, RawBlockInput, Registry, + BlockBuilder, BlockContext, BlockMacro, BlockStyle, BlockStyleOutput, DocumentEditor, + MAX_STYLE_NESTING, MacroExecutionContext, MacroInvocation, RawBlockContext, RawBlockInput, + Registry, TreeProcessor, TreeProcessorRegistration, }, }; @@ -98,6 +102,86 @@ fn same_style_reenters_after_return_and_child_macros_keep_their_source() -> Test Ok(()) } +struct RewriteParagraph; + +impl TreeProcessor for RewriteParagraph { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let targets: Vec<_> = editor + .query() + .select(BlockContext::Paragraph) + .map(|view| view.target().clone()) + .collect(); + assert_eq!(targets.len(), 1); + for target in targets { + editor.replace_source(&target, "*{label}*")?; + } + Ok(()) + } +} + +#[test] +fn tree_edit_of_compound_child_uses_local_attributes_and_clears_stale_warning() -> TestResult { + let source = "= Document\n:label: Header\n\n:label: Early\n\n[panel]\n----\n<>\n----\n\n:label: Late"; + let calls = Arc::new(AtomicUsize::new(0)); + let panel_calls = Arc::clone(&calls); + let mut builder = Registry::builder(); + builder.register_block_style(BlockStyle::compound( + "panel", + [RawBlockContext::Listing], + move || { + let calls = Arc::clone(&panel_calls); + move |_: RawBlockInput<'_>| { + calls.fetch_add(1, Ordering::Relaxed); + Ok(BlockStyleOutput::ParseChildren) + } + }, + ))?; + let panel = builder.build(); + let mut builder = Registry::builder(); + builder.extend(&panel)?; + builder.register_tree_processor(TreeProcessorRegistration::new("rewrite", || { + RewriteParagraph + }))?; + let with_edit = builder.build(); + + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let original = panel.parse(source, &options)?.finish()?; + assert_eq!(calls.swap(0, Ordering::Relaxed), 1); + assert!(original.warnings().iter().any(|warning| matches!( + &warning.kind, WarningKind::UnresolvedReference { target } if target == "missing" + ))); + + let edited = with_edit.parse(source, &options)?.finish()?; + assert_eq!(calls.swap(0, Ordering::Relaxed), 1); + assert_eq!(edited.warnings(), []); + let open = edited + .document() + .blocks() + .find_map(|block| { + if let BlockKind::Open(open) = block.kind() { + Some(open) + } else { + None + } + }) + .ok_or("missing panel")?; + let Some(BlockKind::Paragraph(paragraph)) = open.blocks().next().map(BlockRef::kind) else { + return Err("missing panel paragraph".into()); + }; + assert_eq!(paragraph.source_text(), Some("*{label}*")); + let mut inlines = paragraph.content().inlines().map(InlineRef::kind); + let Some(InlineKind::Bold(bold)) = inlines.next() else { + return Err("expected bold replacement".into()); + }; + assert_eq!(inlines.len(), 0); + let mut content = bold.content().inlines().map(InlineRef::kind); + assert!(matches!(content.next(), Some(InlineKind::Plain(text)) if text.text() == "Early")); + assert_eq!(content.len(), 0); + } + Ok(()) +} + fn nested(depth: usize) -> String { let mut body = "Text.".to_owned(); for level in 0..depth { From b4ad3829526a8a21d4804b932078ca7af80cbe03 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 11:12:34 +0100 Subject: [PATCH 36/55] fix(parser): keep ordinary parsing unchanged with extensions active - key deferred out-of-sequence section warnings by the preprocessed heading offset, so they survive includes and conditionals - apply a caller-supplied leveloffset in extension sessions - match registered block macros like asciidoctor: no whitespace in the target and nothing but whitespace after the closing bracket - drop an unquoted `None` macro argument only in Asciidoctor mode Co-Authored-By: Claude Opus 5.5 --- acdc-parser/CHANGELOG.md | 7 ++ acdc-parser/src/extensions/recognition.rs | 2 +- acdc-parser/src/grammar/attributes.rs | 6 +- acdc-parser/src/grammar/document/peg.rs | 18 +-- acdc-parser/src/grammar/document/source.rs | 3 +- acdc-parser/src/preprocessor/cursor.rs | 6 + acdc-parser/src/preprocessor/source.rs | 19 ++- acdc-parser/tests/extensions.rs | 3 + acdc-parser/tests/extensions/parity.rs | 139 +++++++++++++++++++++ 9 files changed, 181 insertions(+), 22 deletions(-) create mode 100644 acdc-parser/tests/extensions/parity.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index f33a1d71b..5162fc115 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Registered block macros follow asciidoctor's line rules: the target has no + whitespace and only whitespace may follow the closing bracket. Other lines + stay paragraphs or description-list items. With extensions active, a + caller-supplied `leveloffset` and out-of-sequence section warnings behave as + in an ordinary parse, and an unquoted `None` macro argument is dropped only in + Asciidoctor mode. + - Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. A style registered with `BlockStyle::compound` can also request that its body be parsed as children of an open block. - Block macro handlers can return a `BlockBuilder` directly with `.into()`. Tree processors see the resulting block with the invocation’s title, ID, roles, and source location. diff --git a/acdc-parser/src/extensions/recognition.rs b/acdc-parser/src/extensions/recognition.rs index b10a02718..6f55cbcdb 100644 --- a/acdc-parser/src/extensions/recognition.rs +++ b/acdc-parser/src/extensions/recognition.rs @@ -56,7 +56,7 @@ pub(crate) fn recognize<'a>( let mut positional = Vec::new(); let mut attributes = ElementAttributes::default(); for (slot, argument) in scanned.into_iter().enumerate() { - if argument.name.is_some() && argument.is_unset() { + if argument.is_ignored(state.options.compatibility_mode) { continue; } let empty_slot = argument.is_empty_slot(); diff --git a/acdc-parser/src/grammar/attributes.rs b/acdc-parser/src/grammar/attributes.rs index 9f3b3690b..252967918 100644 --- a/acdc-parser/src/grammar/attributes.rs +++ b/acdc-parser/src/grammar/attributes.rs @@ -120,10 +120,6 @@ impl ScannedAttribute { self.quote == AttributeQuote::Unquoted && self.value.is_empty() } - pub(crate) fn is_unset(&self) -> bool { - self.quote == AttributeQuote::Unquoted && self.value == "None" - } - pub(super) fn resolve_content<'a>( &self, text: &'a str, @@ -180,7 +176,7 @@ impl ScannedAttribute { .map(crate::model::canonical_attribute_name) } - pub(super) fn is_ignored(&self, mode: CompatibilityMode) -> bool { + pub(crate) fn is_ignored(&self, mode: CompatibilityMode) -> bool { mode == CompatibilityMode::Asciidoctor && self.name.is_some() && self.quote == AttributeQuote::Unquoted diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index c0c9cd4d6..826698512 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -1159,10 +1159,11 @@ peg::parser! { // is "out of sequence". asciidoctor warns but still renders it at // its literal level rather than aborting, so we do the same. if section_level.1 > parent_level { - let location = state.create_error_source_location( - state.create_block_location(section_level_start, section_level_end, offset), - ); - let start = location.location.absolute_start; + let heading = state.create_block_location(section_level_start, section_level_end, offset); + // Key by the preprocessed offset that `heading_location` also uses; + // the reported location is remapped to the original source. + let start = heading.absolute_start; + let location = state.create_error_source_location(heading); let warning = Warning::new( WarningKind::SectionLevelOutOfSequence { expected: parent_level, @@ -1948,17 +1949,16 @@ peg::parser! { } else { Err("registered block macro") } } + // Like asciidoctor, a target has no whitespace and the line ends at + // the closing bracket; anything else stays ordinary content. rule extension_macro_source() -> (&'input str, &'input str, &'input str, usize) - = name:registered_macro_name() target:$([^'[' | '\n' | '\r']*) - "[" arguments:attribute_list_content(BlockAttributeMode::Macro) end:position!() trailing:$([^'\n']*) + = name:registered_macro_name() target:$([^'[' | ' ' | '\t' | '\n' | '\r']*) + "[" arguments:attribute_list_content(BlockAttributeMode::Macro) end:position!() block_macro_end() { (name, target, arguments, end) } rule extension_macro(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> = source:extension_macro_source() { let (name, target, arguments, end) = source; - if state.source_slice(end + offset..span_end + offset).is_some_and(|trailing| !trailing.trim().is_empty()) { - state.add_warning(Warning::new(WarningKind::ContentRecovery { message: format!("trailing content after block macro {name}").into() }, Some(state.create_error_source_location(state.create_location(end + offset, span_end + offset))))); - } crate::extensions::recognize(state, name, target, arguments, block_metadata.metadata.clone(), block_metadata.title.clone(), state.create_block_location(start, end, offset)) } diff --git a/acdc-parser/src/grammar/document/source.rs b/acdc-parser/src/grammar/document/source.rs index 73ba7f3c2..80e2531d5 100644 --- a/acdc-parser/src/grammar/document/source.rs +++ b/acdc-parser/src/grammar/document/source.rs @@ -921,7 +921,8 @@ pub(crate) fn document_from_source<'a>( conditionals: &mut Vec, finish_source: impl FnOnce(Cow<'a, str>) -> &'a str, ) -> Result, Error> { - if let Some(result) = reader.take_pass_through() { + if let Some(mut result) = reader.take_pass_through() { + state.leveloffset_ranges = std::mem::take(&mut result.leveloffset_ranges); let source = finish_source(result.text); if !std::ptr::eq(state.input, source) { state.set_source_view(SourceView { diff --git a/acdc-parser/src/preprocessor/cursor.rs b/acdc-parser/src/preprocessor/cursor.rs index dbc240c39..8425cf079 100644 --- a/acdc-parser/src/preprocessor/cursor.rs +++ b/acdc-parser/src/preprocessor/cursor.rs @@ -152,6 +152,12 @@ impl Emission<'_> { } impl<'input> InputCursor<'input> { + /// Ranges recorded so far. Before the first advance this is only the + /// caller-supplied `leveloffset`, which no emission carries. + pub(super) fn leveloffset_ranges(&self) -> &[crate::model::LeveloffsetRange] { + &self.out.leveloffset_ranges + } + pub(super) fn table_header_lookahead(&self) -> Vec<&'input str> { if let Some(include) = &self.include { include.cursor.table_header_lookahead() diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs index d03c50adb..d0764f2f3 100644 --- a/acdc-parser/src/preprocessor/source.rs +++ b/acdc-parser/src/preprocessor/source.rs @@ -36,6 +36,9 @@ pub(crate) struct SourceReader<'a> { unchanged: Option<&'a str>, result: Option>, pending: VecDeque>, + /// Caller-supplied `leveloffset`, recorded before any line is read. The + /// first chunk carries it so the parser sees it while blocks commit. + initial_leveloffset_ranges: Vec, pub(crate) options: Rc>, } @@ -128,15 +131,14 @@ impl<'a> SourceReader<'a> { &options, ) { + let initial_leveloffset_ranges = + Preprocessor::initial_leveloffset_ranges(normalized.len(), &options); return Ok(Self { cursor: None, unchanged: Some(normalized), result: Some(PreprocessorResult { text: Cow::Borrowed(normalized), - leveloffset_ranges: Preprocessor::initial_leveloffset_ranges( - normalized.len(), - &options, - ), + leveloffset_ranges: initial_leveloffset_ranges.clone(), leveloffset_scopes: Vec::new(), source_ranges: Vec::new(), included_files: HashSet::default(), @@ -145,6 +147,7 @@ impl<'a> SourceReader<'a> { comment_context: scanner.block_context(), }), pending: VecDeque::new(), + initial_leveloffset_ranges, options, }); } @@ -158,6 +161,7 @@ impl<'a> SourceReader<'a> { arena, ); Ok(Self { + initial_leveloffset_ranges: cursor.leveloffset_ranges().to_vec(), cursor: Some(cursor), unchanged: None, result: None, @@ -193,17 +197,20 @@ impl<'a> SourceReader<'a> { start: 0, text, source_ranges: Vec::new(), - leveloffset_ranges: Vec::new(), + leveloffset_ranges: std::mem::take(&mut self.initial_leveloffset_ranges), leveloffset_scopes: Vec::new(), })); } loop { if let Some(emission) = self.pending.pop_front() { + // Later ranges take precedence, so the caller's value comes first. + let mut leveloffset_ranges = std::mem::take(&mut self.initial_leveloffset_ranges); + leveloffset_ranges.extend(emission.leveloffset_ranges); return Ok(Some(SourceChunk { start: emission.start, text: emission.text, source_ranges: emission.source_ranges, - leveloffset_ranges: emission.leveloffset_ranges, + leveloffset_ranges, leveloffset_scopes: emission.leveloffset_scopes, })); } diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index 8b3c541fa..24c99c130 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -540,3 +540,6 @@ mod raw_styles; #[path = "extensions/compound_styles.rs"] mod compound_styles; + +#[path = "extensions/parity.rs"] +mod parity; diff --git a/acdc-parser/tests/extensions/parity.rs b/acdc-parser/tests/extensions/parity.rs new file mode 100644 index 000000000..d4fc34020 --- /dev/null +++ b/acdc-parser/tests/extensions/parity.rs @@ -0,0 +1,139 @@ +//! An active registry must not change how ordinary content parses. + +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +use acdc_parser::{ + CompatibilityMode, Options, WarningKind, + ast::{BlockKind, BlockRef}, + extensions::{BlockBuilder, BlockMacro, MacroExecutionContext, MacroInvocation, Registry}, +}; + +use super::TestResult; + +fn greet_registry(calls: &Arc) -> Result> { + let calls = Arc::clone(calls); + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("greet", move || { + let calls = Arc::clone(&calls); + move |_: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { + calls.fetch_add(1, Ordering::SeqCst); + Ok(BlockBuilder::paragraph("hello").into()) + } + }))?; + Ok(builder.build()) +} + +fn section_levels<'doc>(blocks: impl Iterator>, levels: &mut Vec) { + for block in blocks { + if let BlockKind::Section(section) = block.kind() { + levels.push(section.level()); + section_levels(section.blocks(), levels); + } + } +} + +fn out_of_sequence(warnings: &[acdc_parser::Warning]) -> usize { + warnings + .iter() + .filter(|warning| matches!(warning.kind, WarningKind::SectionLevelOutOfSequence { .. })) + .count() +} + +#[test] +fn out_of_sequence_warnings_survive_preprocessor_offset_shifts() -> TestResult { + let source = "greet::x[]\n\nifdef::nothing[]\nhidden\nendif::[]\n\n== A\n\n==== B\n"; + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let ordinary = acdc_parser::parse(source, &options)?; + assert_eq!(out_of_sequence(ordinary.warnings()), 1); + let calls = Arc::new(AtomicUsize::new(0)); + let extended = greet_registry(&calls)?.parse(source, &options)?.finish()?; + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(out_of_sequence(extended.warnings()), 1, "{mode:?}"); + } + Ok(()) +} + +#[test] +fn caller_leveloffset_applies_in_extension_sessions() -> TestResult { + for source in [ + "greet::x[]\n\n== Section\n", + "ifdef::nothing[]\nhidden\nendif::[]\ngreet::x[]\n\n== Section\n", + ] { + let options = Options::builder() + .with_attribute("leveloffset", "1") + .build()?; + let mut ordinary = Vec::new(); + section_levels( + acdc_parser::parse(source, &options)?.document().blocks(), + &mut ordinary, + ); + assert_eq!(ordinary, [2]); + let calls = Arc::new(AtomicUsize::new(0)); + let extended = greet_registry(&calls)?.parse(source, &options)?.finish()?; + let mut levels = Vec::new(); + section_levels(extended.document().blocks(), &mut levels); + assert_eq!(levels, ordinary, "{source:?}"); + } + Ok(()) +} + +#[test] +fn macro_lines_with_trailing_text_or_spaced_targets_stay_ordinary_content() -> TestResult { + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for source in ["greet::World[] says hello", "greet:: some term[x]"] { + let calls = Arc::new(AtomicUsize::new(0)); + let extended = greet_registry(&calls)?.parse(source, &options)?.finish()?; + assert_eq!(calls.load(Ordering::SeqCst), 0, "{source:?}"); + let ordinary = acdc_parser::parse(source, &options)?; + let kinds = |blocks: Vec>| { + blocks + .into_iter() + .map(|block| format!("{:?}", std::mem::discriminant(&block.kind()))) + .collect::>() + }; + assert_eq!( + kinds(extended.document().blocks().collect()), + kinds(ordinary.document().blocks().collect()), + "{source:?}" + ); + assert_eq!(extended.warnings(), ordinary.warnings(), "{source:?}"); + } + } + Ok(()) +} + +#[test] +fn unquoted_none_arguments_follow_compatibility_mode() -> TestResult { + for (mode, expected) in [ + (CompatibilityMode::Draft, Some("None".to_owned())), + (CompatibilityMode::Asciidoctor, None), + ] { + let seen = Arc::new(std::sync::Mutex::new(None)); + let mut builder = Registry::builder(); + let record = Arc::clone(&seen); + builder.register(BlockMacro::new("greet", move || { + let record = Arc::clone(&record); + move |call: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { + *record.lock().map_err(|e| e.to_string())? = + Some(call.attributes.get("mode").map(ToString::to_string)); + Ok(BlockBuilder::paragraph("hello").into()) + } + }))?; + let options = Options::builder().with_compatibility_mode(mode).build()?; + let _parsed = builder + .build() + .parse("greet::x[mode=None]", &options)? + .finish()?; + assert_eq!( + seen.lock().map_err(|e| e.to_string())?.clone(), + Some(expected), + "{mode:?}" + ); + } + Ok(()) +} From 84061d6c5ff922d1c17ac21d9453551fe51b8bef Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 11:12:40 +0100 Subject: [PATCH 37/55] fix(parser): fail instead of discarding content after a block macro ran Recovery used to drop quote bodies, Markdown blockquotes, and list or description-list attachments even when a block processor had already run inside them. Its attribute changes and deferred requests outlived the dropped blocks, so finish() or a tree processor failed at a location no longer in the document, and list recovery could run a macro twice. Report an extension error at the first such invocation instead. Content without executed processors still recovers as before. Streamed compound blocks get the same check, though no known input reaches that path. Co-Authored-By: Claude Opus 5.5 --- acdc-parser/CHANGELOG.md | 8 ++ acdc-parser/src/grammar/document/compound.rs | 15 +- .../src/grammar/document/coordinator.rs | 34 ++++- .../grammar/document/lists/construction.rs | 8 +- .../src/grammar/document/lists/description.rs | 14 +- acdc-parser/tests/extensions.rs | 3 + acdc-parser/tests/extensions/recovery.rs | 132 ++++++++++++++++++ 7 files changed, 203 insertions(+), 11 deletions(-) create mode 100644 acdc-parser/tests/extensions/recovery.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 5162fc115..77414519b 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -14,6 +14,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 in an ordinary parse, and an unquoted `None` macro argument is dropped only in Asciidoctor mode. +- When native recovery would drop a quote body, Markdown blockquote, or list + attachment after a registered block macro or style in it already ran, parsing + now fails with an extension error at that invocation. Previously the content + was silently dropped while the macro's attribute changes and deferred request + survived, so `finish()` or a tree processor failed at a location no longer in + the document. Content without executed extensions still recovers with a + warning. + - Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. A style registered with `BlockStyle::compound` can also request that its body be parsed as children of an open block. - Block macro handlers can return a `BlockBuilder` directly with `.into()`. Tree processors see the resulting block with the invocation’s title, ID, roles, and source location. diff --git a/acdc-parser/src/grammar/document/compound.rs b/acdc-parser/src/grammar/document/compound.rs index d0a8456fe..5f19e1765 100644 --- a/acdc-parser/src/grammar/document/compound.rs +++ b/acdc-parser/src/grammar/document/compound.rs @@ -50,13 +50,22 @@ impl BlockCursor { ); input.push_boundary(params.open_delim); let mut body = Vec::new(); + let callbacks = accepted.block_callbacks(); let result = child.collect(input, state, &mut body, accepted); input.pop_boundary(); state.block_context = previous_context; state.source_scope_offset = previous_scope; - let mut end = match result? { - Ok(end) => end, - Err(error) => return Ok(Err(error)), + let mut end = match result { + Ok(Ok(end)) => end, + Ok(Err(error)) => return Ok(Err(error)), + // Compound children cannot stop at a section heading, so no known + // input reaches this. Still report executed processors first. + Err(error) => { + return match accepted.discarded_callback(callbacks, "Compound block content") { + Some(error) => Ok(Err(error)), + None => Err(error), + }; + } }; while let Some(line) = source_tail(state, end).and_then(|tail| tail.split_inclusive('\n').next()) diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index a778d51d9..bde1fa8fc 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -1,7 +1,7 @@ //! Ordered construction at accepted block boundaries. use crate::{ - Block, DelimitedBlock, DelimitedBlockType, Document, DocumentAttributes, Error, + Block, DelimitedBlock, DelimitedBlockType, Document, DocumentAttributes, Error, SourceLocation, extensions::{Invocation, MAX_STYLE_NESTING}, grammar::{ParserState, helpers::PositionWithOffset}, model::{SectionKind, SectionLevel}, @@ -29,7 +29,8 @@ use super::{ pub(super) struct Execution<'handler, F> { callback: &'handler mut F, failed: bool, - block_callbacks: usize, + /// Invocation locations of executed block processors, in execution order. + block_callbacks: Vec, style_depth: usize, } @@ -38,7 +39,7 @@ impl<'handler, F> Execution<'handler, F> { Self { callback, failed: false, - block_callbacks: 0, + block_callbacks: Vec::new(), style_depth: 0, } } @@ -52,14 +53,30 @@ impl<'handler, F> Execution<'handler, F> { where F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, { - self.block_callbacks += usize::from(matches!(block, Block::Extension(_))); + if let Block::Extension(extension) = block { + self.block_callbacks + .push(extension.invocation.location().clone()); + } let result = (self.callback)(block, state, output); self.failed |= result.is_err(); result } pub(super) const fn block_callbacks(&self) -> usize { - self.block_callbacks + self.block_callbacks.len() + } + + /// Native recovery may discard content only when no block processor ran + /// in it. Otherwise their effects would outlive the discarded blocks, so + /// return a fatal error at the first such invocation. `before` is the + /// [`Self::block_callbacks`] count taken when the content started. + pub(super) fn discarded_callback(&mut self, before: usize, context: &str) -> Option { + let location = self.block_callbacks.get(before)?.clone(); + self.failed = true; + Some(Error::Extension( + Box::new(location), + format!("{context}: recovery would discard content after its block processor executed"), + )) } pub(super) fn failed(&self) -> bool { @@ -474,6 +491,7 @@ where }; let mut blocks = Vec::new(); let toc_start = state.toc_entries.len(); + let callbacks = self.accepted.block_callbacks(); let result = cursor .collect( &mut TextInput(request.source), @@ -491,6 +509,12 @@ where match result { Ok(result) => result, Err(error) => { + if let Some(error) = self + .accepted + .discarded_callback(callbacks, request.error_context) + { + return Err(error); + } // Recovery discards this child tree. Retain no provisional TOC // entries for headings that cannot survive in the document. state.toc_entries.truncate(toc_start); diff --git a/acdc-parser/src/grammar/document/lists/construction.rs b/acdc-parser/src/grammar/document/lists/construction.rs index 3ee3ef6d3..05d4a244f 100644 --- a/acdc-parser/src/grammar/document/lists/construction.rs +++ b/acdc-parser/src/grammar/document/lists/construction.rs @@ -214,6 +214,7 @@ impl BlockCursor { phase, )?; self.offset = step.end; + let callbacks = accepted.block_callbacks(); let child = match step.kind { ListStepKind::List(entry) => { self.construct_list_into(input, state, &entry, metadata, &mut blocks, accepted)? @@ -233,7 +234,12 @@ impl BlockCursor { Err(_) if !accepted.failed() && !input.failed() - && matches!(kind, ListKind::Unordered(_) | ListKind::Ordered(_)) => {} + && matches!(kind, ListKind::Unordered(_) | ListKind::Ordered(_)) => + { + if let Some(error) = accepted.discarded_callback(callbacks, "List attachment") { + return Ok(Err(error)); + } + } Err(error) => return Ok(Err(error)), } phase = ListPhase::Attachments; diff --git a/acdc-parser/src/grammar/document/lists/description.rs b/acdc-parser/src/grammar/document/lists/description.rs index e905c3d27..08243f142 100644 --- a/acdc-parser/src/grammar/document/lists/description.rs +++ b/acdc-parser/src/grammar/document/lists/description.rs @@ -184,6 +184,7 @@ impl BlockCursor { let Some(child) = step.child else { return Ok(Ok(children)); }; + let callbacks = accepted.block_callbacks(); let child = match child { Ok(BlockStepKind::List(entry)) => self.construct_list_into( input, @@ -200,8 +201,17 @@ impl BlockCursor { }; match child { Err(error) if accepted.failed() || input.failed() => return Ok(Err(error)), - Err(error) if step.warn_on_error => children.errors.push(error), - Ok(()) | Err(_) => {} + Err(error) => { + if let Some(error) = + accepted.discarded_callback(callbacks, "Description list attachment") + { + return Ok(Err(error)); + } + if step.warn_on_error { + children.errors.push(error); + } + } + Ok(()) => {} } } } diff --git a/acdc-parser/tests/extensions.rs b/acdc-parser/tests/extensions.rs index 24c99c130..626ffab1f 100644 --- a/acdc-parser/tests/extensions.rs +++ b/acdc-parser/tests/extensions.rs @@ -543,3 +543,6 @@ mod compound_styles; #[path = "extensions/parity.rs"] mod parity; + +#[path = "extensions/recovery.rs"] +mod recovery; diff --git a/acdc-parser/tests/extensions/recovery.rs b/acdc-parser/tests/extensions/recovery.rs new file mode 100644 index 000000000..dda5bed04 --- /dev/null +++ b/acdc-parser/tests/extensions/recovery.rs @@ -0,0 +1,132 @@ +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +use acdc_parser::{ + CompatibilityMode, Error, Options, WarningKind, + extensions::{ + BlockBuilder, BlockMacro, BlockMacroOutput, DocumentEditor, MacroExecutionContext, + MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, + }, +}; + +use super::TestResult; + +/// Native parsing recovers each source by dropping the content that holds +/// `greet::[]` at the given line. +const DISCARDED: [(&str, u32); 6] = [ + // A `[quote]` body inherits the section context and stops at `== B`. + ( + "= Doc\n\n== A\n\n[quote]\n____\ngreet::[]\n\n== B\n\ntext\n____\n\nAfter.", + 7, + ), + ("= Doc\n\n== A\n\n> greet::[]\n> \n> == B\n\nAfter.", 5), + ( + "= Doc\n\n== A\n\n* item\n+\n[quote]\n____\ngreet::[]\n\n== B\n____\n\nAfter.", + 9, + ), + ( + "= Doc\n\n== A\n\nterm:: def\n+\n[quote]\n____\ngreet::[]\n\n== B\n____\n\nAfter.", + 9, + ), + // The conditional makes the attached example stream. List recovery then + // drops the attachment after its child macro has executed. + ( + "* item\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n|===\n|===\n====\n\nAfter.", + 7, + ), + ( + "term:: def\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n|===\n|===\n====\n\nAfter.", + 7, + ), +]; + +fn greet_registry(calls: &Arc) -> Result> { + struct Resolve; + impl TreeProcessor for Resolve { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let targets: Vec<_> = editor + .deferred_blocks() + .map(|request| request.target().clone()) + .collect(); + for target in targets { + editor.replace_placeholder(&target, BlockBuilder::paragraph("Hello"))?; + } + Ok(()) + } + } + + let counter = Arc::clone(calls); + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("greet", move || { + let counter = Arc::clone(&counter); + move |_: &MacroInvocation<'_>, ctx: &mut MacroExecutionContext| { + counter.fetch_add(1, Ordering::Relaxed); + ctx.set_attribute("seen", "yes"); + Ok(BlockMacroOutput::Deferred) + } + }))?; + builder.register_tree_processor(TreeProcessorRegistration::for_macro("greet", || Resolve))?; + Ok(builder.build()) +} + +#[test] +fn recovery_reports_content_discarded_after_a_block_macro_ran() -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let registry = greet_registry(&calls)?; + let mut failures = Vec::new(); + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (source, line) in DISCARDED { + // Native parsing recovers and keeps the document. + let _recovered = acdc_parser::parse(source, &options)?; + calls.store(0, Ordering::Relaxed); + let outcome = registry.parse(source, &options).and_then(|parsed| { + let pending = parsed.deferred_blocks().len(); + parsed.finish().map(|_| pending) + }); + let ran = calls.load(Ordering::Relaxed); + match outcome { + Err(Error::Extension(location, message)) + if location.location.start.line == line && ran == 1 => + { + assert!(message.contains("block processor executed"), "{message}"); + } + other => failures.push(format!("{mode:?} {source:?}: ran={ran} {other:?}")), + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); + Ok(()) +} + +#[test] +fn recovery_without_executed_macros_keeps_native_content_recovery() -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let registry = greet_registry(&calls)?; + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (source, _) in DISCARDED.into_iter().take(4) { + // An escaped macro selects the registry reader without a callback. + let source = source.replace("greet::[]", "\\greet::[]"); + let native = acdc_parser::parse(&source, &options)?; + let parsed = registry.parse(&source, &options)?.finish()?; + assert_eq!(calls.load(Ordering::Relaxed), 0); + for warnings in [native.warnings(), parsed.warnings()] { + assert!( + warnings + .iter() + .any(|warning| matches!(warning.kind, WarningKind::ContentRecovery { .. })), + "{mode:?} {source:?}: {warnings:?}" + ); + } + assert_eq!( + serde_json::to_value(parsed.document())?, + serde_json::to_value(native.document())?, + "{mode:?}: {source}" + ); + } + } + Ok(()) +} From 5061e4a1c6bf3da270e407ea9c0f67890df03fce Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 11:12:40 +0100 Subject: [PATCH 38/55] fix(parser): keep anchors and footnotes out of generated display links Display links copied the captured title or custom caption verbatim, so an inline anchor registered twice and a footnote made preparation fail with "belongs to multiple retained scopes". The copy now drops anchors, footnotes, and concealed index terms, keeps only the text of visible index terms, and clears span and link IDs. Co-Authored-By: Claude Opus 5.5 --- acdc-parser/CHANGELOG.md | 6 + acdc-parser/src/extensions/display.rs | 81 +++++++++- .../src/extensions/display/prepared.rs | 6 +- acdc-parser/src/extensions/tests/display.rs | 143 +++++++++++++++++- 4 files changed, 229 insertions(+), 7 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 77414519b..03bb4491c 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -45,6 +45,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 and grouped fragments through `InlineSpec` in generated paragraphs and list items. +- Generated display links that copy a captured title or custom caption no + longer duplicate its identity. Inline anchors, footnotes, and concealed index + terms are left out of the copy, visible index terms keep only their text, and + span and link IDs are removed. A cross reference to an anchor in the title still + reaches the original block, and footnotes keep their number and body there. + - Registered block macros retain their accepted call text, including quoted arguments and unexpanded targets, for literal recovery. Tree processors can also report source-located recoverable warnings. diff --git a/acdc-parser/src/extensions/display.rs b/acdc-parser/src/extensions/display.rs index 2b77c97de..ad9676149 100644 --- a/acdc-parser/src/extensions/display.rs +++ b/acdc-parser/src/extensions/display.rs @@ -94,7 +94,7 @@ impl DisplayRequest { )))); if intent == DisplayIntent::CaptionAndTitle && selection.title.is_present() { nodes.push(plain(" ", &origin.location)); - nodes.extend(selection.title.as_inlines().iter().cloned()); + nodes.extend(display_copy(selection.title.as_inlines())); } Ok(()) } @@ -376,3 +376,82 @@ fn resolve_targets<'a>( fn failure(origin: &SourceLocation, message: &str) -> Error { Error::Extension(Box::new(origin.clone()), message.into()) } + +/// Copy captured inlines into generated content without duplicating identity. +/// +/// A copy must not register targets or own notes: inline anchors and footnotes +/// are dropped, span and link IDs are cleared, concealed index terms are dropped, +/// and visible index terms keep only their text. Otherwise reference and footnote +/// repair let the first occurrence, often the generated copy, own the ID or note. +fn display_copy<'a>(nodes: &[InlineNode<'a>]) -> Vec> { + macro_rules! span { + ($variant:ident, $span:expr) => {{ + let mut span = $span.clone(); + span.id = None; + span.content = display_copy(&span.content); + InlineNode::$variant(span) + }}; + } + macro_rules! link { + ($variant:ident, $link:expr) => {{ + let mut link = $link.clone(); + link.metadata.id = None; + link.text = display_copy(&link.text); + InlineNode::Macro(InlineMacro::$variant(link)) + }}; + } + let mut copied = Vec::with_capacity(nodes.len()); + for node in nodes { + let node = match node { + InlineNode::InlineAnchor(_) | InlineNode::Macro(InlineMacro::Footnote(_)) => continue, + InlineNode::Macro(InlineMacro::IndexTerm(term)) => { + if term.is_visible() { + copied.extend(display_copy(term.term())); + } + continue; + } + InlineNode::BoldText(span) => span!(BoldText, span), + InlineNode::ItalicText(span) => span!(ItalicText, span), + InlineNode::MonospaceText(span) => span!(MonospaceText, span), + InlineNode::HighlightText(span) => span!(HighlightText, span), + InlineNode::SubscriptText(span) => span!(SubscriptText, span), + InlineNode::SuperscriptText(span) => span!(SuperscriptText, span), + InlineNode::DoubleQuotedSpan(span) => span!(DoubleQuotedSpan, span), + InlineNode::SingleQuotedSpan(span) => span!(SingleQuotedSpan, span), + InlineNode::Macro(InlineMacro::Link(node)) => link!(Link, node), + InlineNode::Macro(InlineMacro::UrlMacro(node)) => link!(UrlMacro, node), + InlineNode::Macro(InlineMacro::Mailto(node)) => link!(Mailto, node), + InlineNode::Macro(InlineMacro::CrossReference(xref)) => { + let mut xref = xref.clone(); + xref.text = display_copy(&xref.text); + InlineNode::Macro(InlineMacro::CrossReference(xref)) + } + InlineNode::RawText(raw) => { + let mut raw = raw.clone(); + if let Some(metadata) = &mut raw.metadata { + metadata.id = None; + } + InlineNode::RawText(raw) + } + InlineNode::PlainText(_) + | InlineNode::Symbol(_) + | InlineNode::CharacterReference(_) + | InlineNode::VerbatimText(_) + | InlineNode::StandaloneCurvedApostrophe(_) + | InlineNode::LineBreak(_) + | InlineNode::CalloutMarker(_) + | InlineNode::Macro( + InlineMacro::Icon(_) + | InlineMacro::Image(_) + | InlineMacro::KeyboardShortcut(_) + | InlineMacro::Button(_) + | InlineMacro::MenuPath(_) + | InlineMacro::Autolink(_) + | InlineMacro::Passthrough(_) + | InlineMacro::Stem(_), + ) => node.clone(), + }; + copied.push(node); + } + copied +} diff --git a/acdc-parser/src/extensions/display/prepared.rs b/acdc-parser/src/extensions/display/prepared.rs index c76afab77..ff5de232d 100644 --- a/acdc-parser/src/extensions/display/prepared.rs +++ b/acdc-parser/src/extensions/display/prepared.rs @@ -7,7 +7,7 @@ use crate::{ grammar::try_walk_document_inline_nodes_mut, }; -use super::{DisplayState, GeneratedDisplay, GeneratedDisplayRef, failure, plain}; +use super::{DisplayState, GeneratedDisplay, GeneratedDisplayRef, display_copy, failure, plain}; /// A converter's label decision, lowered by parser-owned constructors. #[derive(Clone, Debug)] @@ -118,7 +118,7 @@ fn build_label<'a>( match label { DisplayLabel::Title => { if display.selection.title.is_present() { - display.selection.title.as_inlines().to_vec() + display_copy(display.selection.title.as_inlines()) } else { vec![plain( arena.alloc_str(&format!("[{}]", GeneratedDisplayRef(display).target())), @@ -134,7 +134,7 @@ fn build_label<'a>( .and_then(|target| target.caption.as_ref()) .and_then(|caption| { if let Caption::CustomContent(content) = caption { - Some(content.as_inlines().to_vec()) + Some(display_copy(content.as_inlines())) } else { None } diff --git a/acdc-parser/src/extensions/tests/display.rs b/acdc-parser/src/extensions/tests/display.rs index 533a00019..307a9bd99 100644 --- a/acdc-parser/src/extensions/tests/display.rs +++ b/acdc-parser/src/extensions/tests/display.rs @@ -1,10 +1,10 @@ use super::{TestResult, support}; use acdc_parser::{ CompatibilityMode, Options, WarningKind, - ast::{BlockKind, InlineKind}, + ast::{BlockKind, ContentRef, DocumentRef, InlineKind}, extensions::{ - BlockBuilder, BlockContext, DisplayIntent, DisplayLabel, DocumentEditor, InlineSpec, - PreparedDocument, TitleSource, + BlockBuilder, BlockContext, DisplayIntent, DisplayLabel, DocumentEditor, + ExtensionParseResult, InlineSpec, PreparedDocument, TitleSource, }, }; @@ -341,6 +341,143 @@ fn extensions_display_distinguishes_absent_and_present_empty_titles() -> TestRes Ok(()) } +/// Record every ID-bearing inline, recursing into spans and cross-reference labels. +fn collect_id_bearing(content: ContentRef<'_>, found: &mut Vec) { + for inline in content.inlines() { + let kind = inline.kind(); + if let InlineKind::Anchor(anchor) = kind { + found.push(format!("anchor {}", anchor.id())); + } else if let InlineKind::Footnote(note) = kind { + found.push(format!("footnote {}", note.number())); + } else if let InlineKind::Bold(span) = kind { + if let Some(id) = span.id() { + found.push(format!("span {}", id.as_str())); + } + collect_id_bearing(span.content(), found); + } else if let InlineKind::Italic(span) = kind { + if let Some(id) = span.id() { + found.push(format!("span {}", id.as_str())); + } + collect_id_bearing(span.content(), found); + } else if let InlineKind::CrossReference(xref) = kind { + collect_id_bearing(xref.text(), found); + } + } +} + +/// A generated list using both title-copying intents, ahead of the captured image. +fn display_list_before_image( + title: &str, + mode: CompatibilityMode, +) -> Result> { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut result = support::registry().parse( + &format!("[#output]\nOutput.\n\n.{title}\n[#figure]\nimage::r.svg[]\n\nSee <>."), + &options, + )?; + let image = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")? + .target() + .clone(); + let output = result + .query() + .select(BlockContext::Paragraph) + .next() + .ok_or("output")? + .target() + .clone(); + let mut editor = DocumentEditor::new(&mut result, None); + let captured = editor.capture(&image)?; + editor.replace_block( + &output, + BlockBuilder::unordered_list([ + vec![captured.display(DisplayIntent::Title)], + vec![captured.display(DisplayIntent::CaptionAndTitle)], + ]), + )?; + Ok(result) +} + +fn generated_list_ids( + document: DocumentRef<'_>, +) -> Result, Box> { + let BlockKind::UnorderedList(list) = document.blocks().next().ok_or("list")?.kind() else { + return Err("list kind".into()); + }; + let mut found = Vec::new(); + for item in list.items() { + collect_id_bearing(item.principal(), &mut found); + } + Ok(found) +} + +fn image_title_ids(document: DocumentRef<'_>) -> Result, Box> { + let block = document + .blocks() + .find(|block| matches!(block.kind(), BlockKind::Image(_))) + .ok_or("image")?; + let mut found = Vec::new(); + collect_id_bearing(block.title().ok_or("image title")?, &mut found); + Ok(found) +} + +#[test] +fn extensions_display_title_copies_drop_inline_anchors() -> TestResult { + for mode in modes() { + let result = display_list_before_image("Results [[res]] *bold [[inner]]*", mode)?; + let parsed = result.finish()?; + assert!( + !parsed + .warnings() + .iter() + .any(|warning| matches!(warning.kind, WarningKind::DuplicateId { .. })), + "{:?}", + parsed.warnings() + ); + let prepared = PreparedDocument::new(parsed.document(), |_| DisplayLabel::Title)?; + let document = prepared.document(); + assert_eq!(generated_list_ids(document)?, Vec::::new()); + assert_eq!(image_title_ids(document)?, ["anchor res", "anchor inner"]); + assert!(document.references().contains("res")); + assert!(document.references().contains("inner")); + } + Ok(()) +} + +#[test] +fn extensions_display_title_copies_leave_footnotes_with_the_original() -> TestResult { + for mode in modes() { + let result = display_list_before_image("Results footnote:[note]", mode)?; + let parsed = result.finish()?; + let prepared = PreparedDocument::new(parsed.document(), |_| DisplayLabel::Title)?; + let document = prepared.document(); + assert_eq!(generated_list_ids(document)?, Vec::::new()); + assert_eq!(image_title_ids(document)?, ["footnote 1"]); + let block = document + .blocks() + .find(|block| matches!(block.kind(), BlockKind::Image(_))) + .ok_or("image")?; + let note = block + .title() + .ok_or("image title")? + .inlines() + .find_map(|inline| { + if let InlineKind::Footnote(note) = inline.kind() { + Some(note) + } else { + None + } + }) + .ok_or("original footnote")?; + assert!(note.content().is_some_and(|content| !content.is_empty())); + assert_eq!(document.footnotes().count(), 1); + } + Ok(()) +} + #[cfg(feature = "asg")] #[test] fn extensions_symbolic_display_requires_lowering_before_checked_asg() -> TestResult { From 8f37c6ae1ffe64b84c7989c48b6b05f73c78dc8b Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 17:46:02 +0100 Subject: [PATCH 39/55] feat(parser): let block styles report located warnings A style can warn at its invocation and still return fallback content or ask the parser to read its children. Preserve the original location through includes and expose the warning in the parse result. --- acdc-parser/CHANGELOG.md | 1 + acdc-parser/README.adoc | 4 ++ acdc-parser/README.md | 4 ++ acdc-parser/src/extensions/block_style.rs | 7 +++ acdc-parser/src/extensions/session.rs | 10 +++- acdc-parser/tests/extensions/raw_styles.rs | 70 +++++++++++++++++++++- 6 files changed, 92 insertions(+), 4 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 03bb4491c..ddad077ee 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 warning. - Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. A style registered with `BlockStyle::compound` can also request that its body be parsed as children of an open block. +- Block styles can report a warning at the styled block's source location and continue parsing with fallback content. - Block macro handlers can return a `BlockBuilder` directly with `.into()`. Tree processors see the resulting block with the invocation’s title, ID, roles, and source location. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index fa8df8c33..05c3d4441 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2083,6 +2083,10 @@ Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume the invocation. The output inherits the title, ID, and roles. The input style has been consumed. Other delimiters keep their ordinary behavior. +Both raw and compound handlers can call `input.warn(message)` and return their +usual output. The warning points to the start of the styled block in its +original file. Return `Err(message)` to stop parsing there. + Use `BlockStyle::compound` for a listing or literal style that can choose how to handle its body. Returning `BlockStyleOutput::ParseChildren` creates an open block with the invocation's title and metadata. Once the handler returns, diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 6285d85ae..4eece9c79 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1727,6 +1727,10 @@ Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume the invocation. The output inherits the title, ID, and roles. The input style has been consumed. Other delimiters keep their ordinary behavior. +Both raw and compound handlers can call `input.warn(message)` and return their +usual output. The warning points to the start of the styled block in its +original file. Return `Err(message)` to stop parsing there. + Use `BlockStyle::compound` for a listing or literal style that can choose how to handle its body. Returning `BlockStyleOutput::ParseChildren` creates an open block with the invocation's title and metadata. Once the handler returns, diff --git a/acdc-parser/src/extensions/block_style.rs b/acdc-parser/src/extensions/block_style.rs index 85a3400b9..dff0696fb 100644 --- a/acdc-parser/src/extensions/block_style.rs +++ b/acdc-parser/src/extensions/block_style.rs @@ -29,9 +29,16 @@ pub struct RawBlockInput<'a> { pub title: Option<&'a TitleSource<'a>>, pub metadata: &'a BlockMetadata<'a>, pub document_attributes: DocumentAttributesRef<'a>, + pub(super) warnings: &'a mut Vec, } impl RawBlockInput<'_> { + /// Report a nonfatal warning at the invocation's source location. + /// The handler can still return any output supported by the style. + pub fn warn(&mut self, message: impl Into) { + self.warnings.push(message.into()); + } + /// Ordered substitutions the source block would apply to its body. #[must_use] pub fn substitutions(&self) -> Vec { diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index 7f19b751b..c3ac973a6 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -1,6 +1,6 @@ use std::{cell::OnceCell, fmt}; -use crate::{Block, Error, ParseResult, grammar::ParserState}; +use crate::{Block, Error, ParseResult, Warning, WarningKind, grammar::ParserState}; use super::{ BlockBuilder, BlockMacroOutput, BlockMacroProcessor, BlockStyleOutput, DeferredBlock, @@ -150,6 +150,7 @@ impl Session { let processor = self.styles.get_mut(extension.processor).ok_or_else(|| { fail("style processor is absent from the document session".into()) })?; + let mut warnings = Vec::new(); let raw = RawBlockInput { context: *context, body, @@ -158,8 +159,15 @@ impl Session { document_attributes: state.document_attributes.as_ref().into(), metadata: &extension.metadata, title: extension.title.source(), + warnings: &mut warnings, }; let output = processor.process(raw).map_err(fail)?; + for message in warnings { + state.add_warning(Warning::new( + WarningKind::Other(message.into()), + Some(origin.clone()), + )); + } extension.metadata.style = None; match output { BlockStyleOutput::ParseChildren => { diff --git a/acdc-parser/tests/extensions/raw_styles.rs b/acdc-parser/tests/extensions/raw_styles.rs index 239da85e3..4d5ed5c24 100644 --- a/acdc-parser/tests/extensions/raw_styles.rs +++ b/acdc-parser/tests/extensions/raw_styles.rs @@ -1,9 +1,9 @@ use acdc_parser::{ - CompatibilityMode, ElementAttributes, Error, Options, SafeMode, Substitution, + CompatibilityMode, ElementAttributes, Error, Options, SafeMode, Substitution, WarningKind, ast::{BlockKind, BlockRef}, extensions::{ - BlockBuilder, BlockContext, BlockStyle, RawBlockContext, RawBlockInput, RegistrationError, - Registry, TreeProcessorRegistration, + BlockBuilder, BlockContext, BlockStyle, BlockStyleOutput, RawBlockContext, RawBlockInput, + RegistrationError, Registry, TreeProcessorRegistration, }, }; @@ -102,6 +102,70 @@ fn style_builds_an_image_from_raw_included_source_before_tree_processing() -> Te Ok(()) } +#[test] +fn style_warnings_keep_the_included_invocation_location_and_allow_fallback() -> TestResult { + let dir = tempfile::tempdir()?; + let file = dir.path().join("styles.adoc"); + std::fs::write( + &file, + "[panel]\n----\n.Fallback\n[sketch]\n....\n{x} *raw*\n....\n----", + )?; + let mut builder = Registry::builder(); + builder.register_block_style(BlockStyle::compound( + "panel", + [RawBlockContext::Listing], + || { + |mut input: RawBlockInput<'_>| { + input.warn("parsing children"); + Ok(BlockStyleOutput::ParseChildren) + } + }, + ))?; + builder.register_block_style(BlockStyle::raw( + "sketch", + [RawBlockContext::Literal], + || { + |mut input: RawBlockInput<'_>| { + input.warn("using source"); + Ok(Some(BlockBuilder::literal(input.body))) + } + }, + ))?; + let registry = builder.build(); + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder() + .with_base_dir(dir.path()) + .with_safe_mode(SafeMode::Safe) + .with_compatibility_mode(mode) + .build()?; + let result = registry.parse("Before.\n\ninclude::styles.adoc[]\n\nAfter.", &options)?; + assert_eq!(result.warnings().len(), 2); + let parsed = result.finish()?; + let warnings = parsed.warnings(); + assert_eq!(warnings.len(), 2); + for (warning, (message, line)) in warnings + .iter() + .zip([("parsing children", 1), ("using source", 3)]) + { + assert!(matches!(&warning.kind, WarningKind::Other(text) if text == message)); + let location = warning + .source_location() + .ok_or("missing warning location")?; + assert_eq!(location.file.as_deref(), Some(file.as_path())); + assert_eq!(location.location.start.line, line); + } + let mut blocks = parsed.document().blocks().map(BlockRef::kind); + assert!(matches!(blocks.next(), Some(BlockKind::Paragraph(_)))); + let Some(BlockKind::Open(panel)) = blocks.next() else { + return Err("missing panel".into()); + }; + assert!(matches!(panel.blocks().next().map(BlockRef::kind), + Some(BlockKind::Literal(literal)) if literal.source_text() == Some("{x} *raw*\n"))); + assert!(matches!(blocks.next(), Some(BlockKind::Paragraph(_)))); + } + Ok(()) +} + #[test] fn only_registered_delimiters_are_consumed_and_empty_bodies_are_located() -> TestResult { let style = BlockStyle::raw("consume", [RawBlockContext::Literal], || { From eb18b704f78ad276a5955ad01a50becdc435fb89 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 18:20:20 +0100 Subject: [PATCH 40/55] fix(parser): preserve authored alt text for images returned by block styles --- acdc-parser/CHANGELOG.md | 1 + acdc-parser/README.adoc | 3 +- acdc-parser/README.md | 3 +- acdc-parser/src/extensions/session.rs | 3 + acdc-parser/src/grammar/document/generated.rs | 9 ++- acdc-parser/src/grammar/document/metadata.rs | 19 ++++++ acdc-parser/src/grammar/document/peg.rs | 2 + acdc-parser/tests/extensions/raw_styles.rs | 64 ++++++++++++++++++- 8 files changed, 100 insertions(+), 4 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index ddad077ee..6f0cc1885 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -24,6 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. A style registered with `BlockStyle::compound` can also request that its body be parsed as children of an open block. - Block styles can report a warning at the styled block's source location and continue parsing with fallback content. +- Images returned by block styles inherit the block's named `alt` text, including an explicitly empty value. An authored alternative overrides the extension's default. - Block macro handlers can return a `BlockBuilder` directly with `.into()`. Tree processors see the resulting block with the invocation’s title, ID, roles, and source location. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 05c3d4441..6de0ec8c5 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2080,7 +2080,8 @@ can be named with `with_positional_attributes`. Named values take precedence, and `with_defaults` fills missing values. Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume -the invocation. The output inherits the title, ID, and roles. The input style +the invocation. The output inherits the title, ID, and roles. An image also +inherits a named `alt` value, including `alt=""`, ahead of builder defaults. The input style has been consumed. Other delimiters keep their ordinary behavior. Both raw and compound handlers can call `input.warn(message)` and return their diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 4eece9c79..3dadbfcab 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1724,7 +1724,8 @@ can be named with `with_positional_attributes`. Named values take precedence, and `with_defaults` fills missing values. Return `Ok(Some(builder))` to emit an ordinary block or `Ok(None)` to consume -the invocation. The output inherits the title, ID, and roles. The input style +the invocation. The output inherits the title, ID, and roles. An image also +inherits a named `alt` value, including `alt=""`, ahead of builder defaults. The input style has been consumed. Other delimiters keep their ordinary behavior. Both raw and compound handlers can call `input.warn(message)` and return their diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index c3ac973a6..d3486e77d 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -169,6 +169,9 @@ impl Session { )); } extension.metadata.style = None; + if !matches!(&output, BlockStyleOutput::Block(builder) if builder.is_image()) { + extension.metadata.alt_source = None; + } match output { BlockStyleOutput::ParseChildren => { *parse_children = true; diff --git a/acdc-parser/src/grammar/document/generated.rs b/acdc-parser/src/grammar/document/generated.rs index 794537d5d..426a4baac 100644 --- a/acdc-parser/src/grammar/document/generated.rs +++ b/acdc-parser/src/grammar/document/generated.rs @@ -56,7 +56,10 @@ impl<'a> ParserState<'a> { let metadata = std::mem::take(&mut extension.metadata); let title = std::mem::take(&mut extension.title); // The invocation's metadata has already been interpreted in source order. - if builder.defaults.is_none() && builder.attributes.is_empty() && builder.unsets.is_empty() + if builder.defaults.is_none() + && builder.attributes.is_empty() + && builder.unsets.is_empty() + && !(builder.is_image() && metadata.alt_source.is_some()) { return Ok(Prepared { metadata, @@ -117,6 +120,10 @@ pub(crate) fn prepare<'a>( if title.is_present() { attributes.title = None; } + if builder.is_image() && inherited.alt_source.is_some() { + // An authored alt also overrides the first positional image default. + attributes.metadata.first_source = None; + } // Attribute positions and pending reftext belong to the parsed source. // Generated lists have their own input and positions. inherited.attribute_positions = None; diff --git a/acdc-parser/src/grammar/document/metadata.rs b/acdc-parser/src/grammar/document/metadata.rs index e66e684be..3cce58632 100644 --- a/acdc-parser/src/grammar/document/metadata.rs +++ b/acdc-parser/src/grammar/document/metadata.rs @@ -118,6 +118,25 @@ impl<'a> QuoteSources<'a> { } impl<'a> ParsedAttributeList<'a> { + /// A registered style chooses its output after the prefix has been parsed. + /// Keep the authored alt input until we know whether it produced an image. + pub(super) fn take_style_alt( + &mut self, + state: &ParserState<'a>, + form: AttributeBlockForm<'_>, + ) -> Option>> { + self.metadata.alt_source.as_ref()?; + let AttributeBlockForm::Delimited(kind, _) = form else { + return None; + }; + state + .options + .extensions + .as_ref()? + .raw_style(self.metadata.style?, kind.raw_context()?)?; + self.metadata.alt_source.take() + } + pub(super) fn overlay_prepared( &mut self, metadata: BlockMetadata<'a>, diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 826698512..32215c20f 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -1384,7 +1384,9 @@ peg::parser! { ); } let image_ahead = media_ahead && state.source_tail(block_start + offset).is_some_and(|tail| tail.starts_with("image::")); + let style_alt = attributes.take_style_alt(state, form); let image_alt = resolve_block_content_attributes(state, &mut attributes, media_attributes.as_deref(), image_ahead)?; + attributes.metadata.alt_source = style_alt; // Titles use the completed metadata attributes, including entries // after the title line. Only the last authored title is displayed. let title = if let Some(source) = attributes.title.take().filter(|_| parse_title) { diff --git a/acdc-parser/tests/extensions/raw_styles.rs b/acdc-parser/tests/extensions/raw_styles.rs index 4d5ed5c24..8d919d7aa 100644 --- a/acdc-parser/tests/extensions/raw_styles.rs +++ b/acdc-parser/tests/extensions/raw_styles.rs @@ -1,6 +1,6 @@ use acdc_parser::{ CompatibilityMode, ElementAttributes, Error, Options, SafeMode, Substitution, WarningKind, - ast::{BlockKind, BlockRef}, + ast::{BlockKind, BlockRef, InlineKind}, extensions::{ BlockBuilder, BlockContext, BlockStyle, BlockStyleOutput, RawBlockContext, RawBlockInput, RegistrationError, Registry, TreeProcessorRegistration, @@ -166,6 +166,68 @@ fn style_warnings_keep_the_included_invocation_location_and_allow_fallback() -> Ok(()) } +#[test] +fn image_styles_resolve_authored_alt_before_builder_defaults() -> TestResult { + let mut builder = Registry::builder(); + builder.register_block_style(BlockStyle::raw( + "picture", + [RawBlockContext::Literal], + || { + |input: RawBlockInput<'_>| { + let image = BlockBuilder::image("clock.svg"); + Ok(Some(match input.body.trim() { + "default" => image.with_default_attributes("alt=Default"), + "positional" => image.with_default_attributes("Default"), + "override" => image.with_attributes("alt=Override"), + "position-override" => image.with_attributes("Override"), + _ => image, + })) + } + }, + ))?; + let registry = builder.build(); + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (attribute, body, expected) in [ + ("", "plain", None), + ("", "default", Some("Default")), + (",alt={label}", "plain", Some("Clock")), + (",alt={label}", "default", Some("Clock")), + (",alt={label}", "positional", Some("Clock")), + (",alt=\"\"", "default", Some("")), + (",alt=Clock", "override", Some("Override")), + (",alt=Clock", "position-override", Some("Override")), + ] { + let source = format!(":label: Clock\n\n[picture{attribute}]\n....\n{body}\n...."); + let parsed = registry.parse(&source, &options)?.finish()?; + let Some(BlockKind::Image(image)) = + parsed.document().blocks().last().map(BlockRef::kind) + else { + return Err("expected generated image".into()); + }; + let alt = image + .alt() + .map(|content| { + content + .inlines() + .map(|inline| { + if let InlineKind::Plain(value) = inline.kind() { + Ok(value.text()) + } else if let InlineKind::Raw(value) = inline.kind() { + Ok(value.text()) + } else { + Err("unexpected alt content") + } + }) + .collect::>() + }) + .transpose()?; + assert_eq!(alt.as_deref(), expected, "{mode:?} {source}"); + } + } + Ok(()) +} + #[test] fn only_registered_delimiters_are_consumed_and_empty_bodies_are_located() -> TestResult { let style = BlockStyle::raw("consume", [RawBlockContext::Literal], || { From a1c568bf91c559785eea46fcc00b271850048715 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 20:33:43 +0100 Subject: [PATCH 41/55] feat(parser): let block macros read local targets under the include policy --- acdc-parser/CHANGELOG.md | 2 + acdc-parser/README.adoc | 4 + acdc-parser/README.md | 4 + acdc-parser/src/extensions/block_macro.rs | 94 ++++++++++++++++++- acdc-parser/src/extensions/session.rs | 63 ++++++++++--- .../src/extensions/tests/invocations.rs | 78 +++++++++++++++ acdc-parser/src/grammar/document/source.rs | 29 +++++- acdc-parser/src/preprocessor/mod.rs | 12 ++- acdc-parser/src/preprocessor/source.rs | 4 + 9 files changed, 264 insertions(+), 26 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 6f0cc1885..e1ed8d69b 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- In unsafe mode, registered block macros can read relative local targets through the configured include loader and report recoverable warnings at the invocation. Target reads count toward the document’s include byte limit. + - Registered block macros follow asciidoctor's line rules: the target has no whitespace and only whitespace may follow the closing bracket. Other lines stay paragraphs or description-list items. With extensions active, a diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 6de0ec8c5..73a1c7b28 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2063,6 +2063,10 @@ under normal document assignment policy. The invocation retains the original source location and a read-only attribute snapshot. Both compatibility modes support registrations. Factories are shared; handlers may use document-local, non-`Send` state. Completed callback effects remain if later parsing fails. +In unsafe mode a block macro can read its relative local target with +`MacroExecutionContext::read_local_target`. The caller's include loader supplies +the bytes, decoded as UTF-8 or using a Unicode byte order mark. These reads share the include byte budget. Use `warn` to +report a recoverable problem at the invocation. A block macro can return an ordinary block directly. For example, a handler for `logo::acme[]` can return `Ok(BlockBuilder::image("acme.svg").into())`. diff --git a/acdc-parser/README.md b/acdc-parser/README.md index 3dadbfcab..a5729bf53 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1707,6 +1707,10 @@ under normal document assignment policy. The invocation retains the original source location and a read-only attribute snapshot. Both compatibility modes support registrations. Factories are shared; handlers may use document-local, non-`Send` state. Completed callback effects remain if later parsing fails. +In unsafe mode a block macro can read its relative local target with +`MacroExecutionContext::read_local_target`. The caller's include loader supplies +the bytes, decoded as UTF-8 or using a Unicode byte order mark. These reads share the include byte budget. Use `warn` to +report a recoverable problem at the invocation. A block macro can return an ordinary block directly. For example, a handler for `logo::acme[]` can return `Ok(BlockBuilder::image("acme.svg").into())`. diff --git a/acdc-parser/src/extensions/block_macro.rs b/acdc-parser/src/extensions/block_macro.rs index 94d2b9090..b3b7a2c1d 100644 --- a/acdc-parser/src/extensions/block_macro.rs +++ b/acdc-parser/src/extensions/block_macro.rs @@ -1,8 +1,15 @@ -use std::{borrow::Cow, fmt, sync::Arc}; +use std::{ + borrow::Cow, + cell::Cell, + fmt, + io::{self, Read}, + path::{Path, PathBuf}, + sync::Arc, +}; use crate::{ DocumentAttributeAssignment, DocumentAttributeValue, DocumentAttributes, ElementAttributes, - SourceLocation, + IncludeSourceTarget, Options, SafeMode, SourceLocation, }; /// The parser scope in which a block macro can be recognized. @@ -147,11 +154,90 @@ where /// normal document assignment policy, before advancing to subsequent source. /// Values are already resolved; literal attribute references are not expanded again. #[derive(Debug, Default)] -pub struct MacroExecutionContext { +pub struct MacroExecutionContext<'a> { + pub(super) file: Option>, + pub(super) warnings: Vec, pub(crate) assignments: Vec<(Cow<'static, str>, DocumentAttributeAssignment<'static>)>, } -impl MacroExecutionContext { +#[derive(Debug)] +pub(super) struct LocalTarget<'a> { + pub(super) call: &'a MacroInvocation<'a>, + pub(super) options: &'a Options<'a>, + pub(super) entry: Option<&'a Path>, + pub(super) budget: &'a Cell, +} + +impl MacroExecutionContext<'_> { + /// Read this invocation's relative local text target through the caller's + /// include loader. Return the resolved path alongside the text so processors + /// can resolve references within it. Reads share the document's include byte budget. + /// + /// # Errors + /// Requires unsafe mode, an enabled loader, and a local source origin. + /// Invalid targets, loader errors, invalid text encodings, and oversized files fail. + pub fn read_local_target(&self) -> io::Result<(PathBuf, String)> { + let input = self + .file + .as_ref() + .ok_or_else(|| io::Error::other("no active macro invocation"))?; + if input.options.safe_mode != SafeMode::Unsafe { + return Err(io::Error::other("local macro targets require unsafe mode")); + } + let provider = input + .options + .include_loader + .provider() + .ok_or_else(|| io::Error::other("include loading is disabled"))?; + let target = Path::new(input.call.target.as_ref()); + if target.as_os_str().is_empty() + || !target.is_relative() + || input.call.target.contains(':') + || input.call.target.starts_with('\\') + { + return Err(io::Error::other("expected a relative local macro target")); + } + let origin = input.call.location.file.as_deref(); + if origin.is_some_and(|p| p.to_string_lossy().contains("://")) { + return Err(io::Error::other( + "local macro target has a URI source origin", + )); + } + let from = origin.and_then(Path::parent); + let base = if origin == input.entry { + input.options.base_dir.as_deref().or(from) + } else { + from.or(input.options.base_dir.as_deref()) + }; + let path = + crate::preprocessor::absolute_normalized(&base.unwrap_or(Path::new(".")).join(target)) + .map_err(io::Error::other)?; + let source = provider + .open(&IncludeSourceTarget::File(path.clone())) + .map_err(io::Error::other)?; + let remaining = input.budget.get(); + let mut bytes = Vec::new(); + let result = source + .into_reader() + .take((remaining as u64).saturating_add(1)) + .read_to_end(&mut bytes); + input.budget.set(remaining.saturating_sub(bytes.len())); + result?; + if bytes.len() > remaining { + return Err(io::Error::other( + "macro target exceeds the remaining include byte budget", + )); + } + let text = crate::preprocessor::decode_bytes(&bytes, None, &path.to_string_lossy()) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + Ok((path, text)) + } + + /// Report a recoverable warning at the current macro invocation. + pub fn warn(&mut self, message: impl Into) { + self.warnings.push(message.into()); + } + pub fn set_attribute( &mut self, name: impl Into>, diff --git a/acdc-parser/src/extensions/session.rs b/acdc-parser/src/extensions/session.rs index d3486e77d..bd20e82e8 100644 --- a/acdc-parser/src/extensions/session.rs +++ b/acdc-parser/src/extensions/session.rs @@ -1,4 +1,7 @@ -use std::{cell::OnceCell, fmt}; +use std::{ + cell::{Cell, OnceCell}, + fmt, +}; use crate::{Block, Error, ParseResult, Warning, WarningKind, grammar::ParserState}; @@ -129,11 +132,49 @@ impl Session { self.identity.get_or_init(DocumentIdentity::default) } + fn process_macro<'a>( + &mut self, + processor: usize, + call: &super::MacroInvocation<'a>, + state: &ParserState<'a>, + assignments: &mut crate::grammar::SourceAssignments<'a>, + budget: &Cell, + ) -> Result { + let fail = |message| Error::Extension(Box::new(call.location.clone()), message); + let mut context = super::MacroExecutionContext { + file: Some(super::block_macro::LocalTarget { + call, + options: &state.options, + entry: state + .current_file + .as_deref() + .map(std::path::PathBuf::as_path), + budget, + }), + ..Default::default() + }; + let output = self + .processors + .get_mut(processor) + .ok_or_else(|| fail("processor is absent from the document session".into()))? + .process(call, &mut context) + .map_err(fail)?; + *assignments = context.assignments; + for message in context.warnings { + state.add_warning(Warning::new( + WarningKind::Other(message.into()), + Some(call.location.clone()), + )); + } + Ok(output) + } + fn block<'a>( &mut self, block: &mut Block<'a>, state: &ParserState<'a>, - context: &mut super::MacroExecutionContext, + assignments: &mut crate::grammar::SourceAssignments<'a>, + budget: &Cell, ) -> Result { if let Block::Extension(extension) = block { self.processed_blocks = true; @@ -182,15 +223,8 @@ impl Session { } } Invocation::Macro(call) => { - let fail = |message| Error::Extension(Box::new(call.location.clone()), message); - let output = self - .processors - .get_mut(extension.processor) - .ok_or_else(|| { - fail("processor is absent from the document session".into()) - })? - .process(call, context) - .map_err(fail)?; + let output = + self.process_macro(extension.processor, call, state, assignments, budget)?; match output { BlockMacroOutput::Paragraph(text) => BlockBuilder::paragraph(text), BlockMacroOutput::Block(builder) => builder, @@ -235,9 +269,10 @@ impl crate::grammar::SourceHandler for Session { &mut self, block: &mut Block<'a>, state: &mut ParserState<'a>, + budget: &Cell, ) -> Result<(bool, crate::grammar::SourceAssignments<'a>), Error> { - let mut context = super::MacroExecutionContext::default(); - let keep = self.block(block, state, &mut context)?; - Ok((keep, context.assignments)) + let mut assignments = Vec::new(); + let keep = self.block(block, state, &mut assignments, budget)?; + Ok((keep, assignments)) } } diff --git a/acdc-parser/src/extensions/tests/invocations.rs b/acdc-parser/src/extensions/tests/invocations.rs index ae3a1485d..19cf78dd9 100644 --- a/acdc-parser/src/extensions/tests/invocations.rs +++ b/acdc-parser/src/extensions/tests/invocations.rs @@ -63,3 +63,81 @@ fn extensions_deferred_source_keeps_quotes_slots_and_normal_cell_escapes() -> Te } Ok(()) } + +#[test] +fn local_macro_target_uses_include_provider_origin_and_shared_budget() -> TestResult { + use acdc_parser::{IncludeLoader, IncludeSource, IncludeSourceTarget, SafeMode}; + + let root = tempfile::tempdir()?; + let root_path = root.path().to_path_buf(); + let loader = IncludeLoader::custom(move |target: &IncludeSourceTarget| { + let IncludeSourceTarget::File(path) = target else { + panic!("expected file") + }; + let relative = path.strip_prefix(&root_path).expect("configured base"); + Ok(IncludeSource::from_string(match relative.to_str() { + Some("nested/part.adoc") => "read::data.txt[]", + Some("nested/data.txt") => "data", + Some("next.txt") => "again", + _ => panic!("unexpected target: {relative:?}"), + })) + }); + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("read", || { + |call: &MacroInvocation<'_>, ctx: &mut MacroExecutionContext| match ctx.read_local_target() + { + Ok((path, text)) => { + assert!(path.ends_with(call.target.as_ref())); + Ok(BlockMacroOutput::Paragraph(text)) + } + Err(err) => { + ctx.warn(err.to_string()); + Ok(BlockMacroOutput::None) + } + } + }))?; + let registry = builder.build(); + let mut options = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .with_include_loader(loader) + .with_base_dir(root.path()) + .with_max_total_include_bytes("read::data.txt[]\n".len() + 4) + .build()?; + let result = registry + .parse("include::nested/part.adoc[]\n\nread::next.txt[]", &options)? + .finish()?; + assert_eq!(paragraph_text(&result.document_storage().blocks[0]), "data"); + let [warning] = result.warnings() else { + panic!("{:?}", result.warnings()); + }; + assert!( + warning + .to_string() + .contains("remaining include byte budget") + ); + assert_eq!( + warning + .location + .as_ref() + .ok_or("missing warning location")? + .location + .start + .line, + 3 + ); + options.include_loader = IncludeLoader::Disabled; + let result = registry.parse("read::data.txt[]", &options)?.finish()?; + assert!( + result.warnings()[0] + .to_string() + .contains("loading is disabled") + ); + options.safe_mode = SafeMode::Secure; + let result = registry.parse("read::data.txt[]", &options)?.finish()?; + assert!( + result.warnings()[0] + .to_string() + .contains("require unsafe mode") + ); + Ok(()) +} diff --git a/acdc-parser/src/grammar/document/source.rs b/acdc-parser/src/grammar/document/source.rs index 80e2531d5..0cb1d43fe 100644 --- a/acdc-parser/src/grammar/document/source.rs +++ b/acdc-parser/src/grammar/document/source.rs @@ -1,6 +1,10 @@ //! Cooperate with the reader between committed construction steps. -use std::{borrow::Cow, cell::RefCell, rc::Rc}; +use std::{ + borrow::Cow, + cell::{Cell, RefCell}, + rc::Rc, +}; use crate::{ AttributeName, Block, Document, DocumentAttributeAssignment, DocumentAttributes, Error, @@ -44,6 +48,7 @@ pub(crate) trait SourceHandler { &mut self, block: &mut Block<'a>, state: &mut ParserState<'a>, + _remaining: &Cell, ) -> Result<(bool, Assignments<'a>), Error> { self.accepted(block, &state.document_attributes) .map(|assignments| (true, assignments)) @@ -921,6 +926,7 @@ pub(crate) fn document_from_source<'a>( conditionals: &mut Vec, finish_source: impl FnOnce(Cow<'a, str>) -> &'a str, ) -> Result, Error> { + let includes = Rc::clone(&reader.include_session); if let Some(mut result) = reader.take_pass_through() { state.leveloffset_ranges = std::mem::take(&mut result.leveloffset_ranges); let source = finish_source(result.text); @@ -933,7 +939,14 @@ pub(crate) fn document_from_source<'a>( } let mut callback = |block: &mut Block<'a>, state: &mut ParserState<'a>, output: &mut Vec>| { - execute_source_handler(handler, block, state, None, output) + execute_source_handler( + handler, + &includes.remaining_bytes, + block, + state, + None, + output, + ) }; let document = document_with_execution(source, state, ConstructionMode::Ordered, &mut callback) @@ -944,7 +957,14 @@ pub(crate) fn document_from_source<'a>( let updates = PendingAssignments::default(); let mut callback = |block: &mut Block<'a>, state: &mut ParserState<'a>, output: &mut Vec>| { - execute_source_handler(handler, block, state, Some(&updates), output) + execute_source_handler( + handler, + &includes.remaining_bytes, + block, + state, + Some(&updates), + output, + ) }; let index = state .input_origin @@ -998,12 +1018,13 @@ pub(crate) fn document_from_source<'a>( #[inline] fn execute_source_handler<'a>( handler: &mut dyn SourceHandler, + remaining: &Cell, block: &mut Block<'a>, state: &mut ParserState<'a>, updates: Option<&PendingAssignments<'a>>, output: &mut Vec>, ) -> Result { - let (keep, assignments) = handler.construct(block, state)?; + let (keep, assignments) = handler.construct(block, state, remaining)?; if !assignments.is_empty() { apply_assignments(assignments, block, state, updates, output); } diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index 4cf2afd45..f77d41fb2 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -239,8 +239,8 @@ struct IncludeContext { /// Sibling and nested scopes share one byte budget and one set of processors. #[derive(Debug)] -struct IncludeSession { - remaining_bytes: Cell, +pub(crate) struct IncludeSession { + pub(crate) remaining_bytes: Cell, processors: Option, } @@ -392,7 +392,7 @@ impl SourceLineOrigin { /// Make a path absolute and collapse `.` and `..` without resolving symlinks. /// For example, `/workspace/docs/chapters/../shared.adoc` becomes /// `/workspace/docs/shared.adoc`, even if `chapters` is a symlink. -fn absolute_normalized(path: &Path) -> Result { +pub(crate) fn absolute_normalized(path: &Path) -> Result { let absolute = std::path::absolute(path)?; let mut normalized = PathBuf::new(); for component in absolute.components() { @@ -711,7 +711,11 @@ pub(crate) fn read_and_decode_file( } /// Decode source bytes using an explicit encoding, BOM detection, or UTF-8. -fn decode_bytes(bytes: &[u8], encoding: Option<&str>, source: &str) -> Result { +pub(crate) fn decode_bytes( + bytes: &[u8], + encoding: Option<&str>, + source: &str, +) -> Result { // If there was an encoding specified, decode the entire file as that if let Some(enc_label) = encoding { if let Some(encoding) = Encoding::for_label(enc_label.as_bytes()) { diff --git a/acdc-parser/src/preprocessor/source.rs b/acdc-parser/src/preprocessor/source.rs index d0764f2f3..9f86526a3 100644 --- a/acdc-parser/src/preprocessor/source.rs +++ b/acdc-parser/src/preprocessor/source.rs @@ -39,6 +39,7 @@ pub(crate) struct SourceReader<'a> { /// Caller-supplied `leveloffset`, recorded before any line is read. The /// first chunk carries it so the parser sees it while blocks commit. initial_leveloffset_ranges: Vec, + pub(crate) include_session: Rc, pub(crate) options: Rc>, } @@ -109,6 +110,7 @@ impl<'a> SourceReader<'a> { warnings, include_context: super::IncludeContext::root(&options, includes), }; + let include_session = Rc::clone(&preprocessor.include_context.session); let normalized = match text { Cow::Borrowed(text) => text, Cow::Owned(text) => arena.alloc_str(&text), @@ -134,6 +136,7 @@ impl<'a> SourceReader<'a> { let initial_leveloffset_ranges = Preprocessor::initial_leveloffset_ranges(normalized.len(), &options); return Ok(Self { + include_session, cursor: None, unchanged: Some(normalized), result: Some(PreprocessorResult { @@ -162,6 +165,7 @@ impl<'a> SourceReader<'a> { ); Ok(Self { initial_leveloffset_ranges: cursor.leveloffset_ranges().to_vec(), + include_session, cursor: Some(cursor), unchanged: None, result: None, From c21a157919823f80ef4eda016551796ebfbd6878 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 20:36:25 +0100 Subject: [PATCH 42/55] feat(parser): preserve quoted macro arguments forwarded to generated blocks --- acdc-parser/CHANGELOG.md | 2 ++ acdc-parser/src/extensions/block_macro.rs | 15 +++++++++++ acdc-parser/src/extensions/recognition.rs | 1 + .../src/extensions/tests/invocations.rs | 8 ++++++ acdc-parser/src/grammar/attributes.rs | 26 +++++++++++++++++++ 5 files changed, 52 insertions(+) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index e1ed8d69b..15230ddb1 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Block macros can forward selected named arguments to generated blocks while preserving attribute quoting and escaping. + - In unsafe mode, registered block macros can read relative local targets through the configured include loader and report recoverable warnings at the invocation. Target reads count toward the document’s include byte limit. - Registered block macros follow asciidoctor's line rules: the target has no diff --git a/acdc-parser/src/extensions/block_macro.rs b/acdc-parser/src/extensions/block_macro.rs index b3b7a2c1d..b7fb703ef 100644 --- a/acdc-parser/src/extensions/block_macro.rs +++ b/acdc-parser/src/extensions/block_macro.rs @@ -109,6 +109,7 @@ impl BlockMacro { #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct MacroInvocation<'a> { + pub(super) mode: crate::CompatibilityMode, pub name: Cow<'a, str>, /// The accepted call from its name through the closing bracket, before /// target expansion and argument interpretation. Table-cell escapes follow @@ -276,8 +277,22 @@ impl From for BlockMacroOutput { } impl MacroInvocation<'_> { + /// Select authored named arguments to pass to [`super::BlockBuilder::with_attributes`]. + /// Preserves quoting, escapes, and source order. Positional bindings and + /// defaults are omitted. + #[must_use] + pub fn named_arguments_source(&self, keep: impl FnMut(&str) -> bool) -> String { + let arguments = self + .source + .split_once('[') + .and_then(|(_, tail)| tail.strip_suffix(']')) + .unwrap_or_default(); + crate::grammar::attributes::named_arguments_source(arguments, self.mode, keep) + } + pub(super) fn to_owned_invocation(&self) -> MacroInvocation<'static> { MacroInvocation { + mode: self.mode, name: Cow::Owned(self.name.to_string()), source: Cow::Owned(self.source.to_string()), target: Cow::Owned(self.target.to_string()), diff --git a/acdc-parser/src/extensions/recognition.rs b/acdc-parser/src/extensions/recognition.rs index 6f55cbcdb..5d9ff0790 100644 --- a/acdc-parser/src/extensions/recognition.rs +++ b/acdc-parser/src/extensions/recognition.rs @@ -81,6 +81,7 @@ pub(crate) fn recognize<'a>( metadata, title, invocation: super::Invocation::Macro(MacroInvocation { + mode: state.options.compatibility_mode, name: Cow::Borrowed(name), source: Cow::Owned(source), target: Cow::Borrowed(target), diff --git a/acdc-parser/src/extensions/tests/invocations.rs b/acdc-parser/src/extensions/tests/invocations.rs index 19cf78dd9..1c0de83d9 100644 --- a/acdc-parser/src/extensions/tests/invocations.rs +++ b/acdc-parser/src/extensions/tests/invocations.rs @@ -12,6 +12,14 @@ fn extensions_invocations_preserve_source_before_target_expansion() -> TestResul builder.register(BlockMacro::new("source", || { |invocation: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { assert_eq!(invocation.source, CALL); + assert_eq!( + invocation.named_arguments_source(|name| matches!(name, "path" | "custom")), + r#"custom="x,y",path='a\b'"# + ); + assert_eq!( + invocation.named_arguments_source(|name| name == "first"), + "" + ); assert_eq!(invocation.target, "expanded"); assert_eq!( invocation diff --git a/acdc-parser/src/grammar/attributes.rs b/acdc-parser/src/grammar/attributes.rs index 252967918..8f6e5ea0e 100644 --- a/acdc-parser/src/grammar/attributes.rs +++ b/acdc-parser/src/grammar/attributes.rs @@ -486,6 +486,32 @@ pub(super) fn decode_anchor_shorthand_reftext(value: &str) -> String { decode_attribute_escapes(value, ']', CompatibilityMode::Draft, true).0 } +/// Copy selected named arguments to a new macro attribute list, preserving +/// quote choice, escapes and authored references for native output processing. +pub(crate) fn named_arguments_source( + source: &str, + mode: CompatibilityMode, + mut keep: impl FnMut(&str) -> bool, +) -> String { + let mut result = String::new(); + for slot in scan_block_attribute_list(source, mode, BlockAttributeMode::Macro) { + let Some(name) = slot.name.as_deref() else { + continue; + }; + if !keep(name) || slot.is_ignored(mode) { + continue; + } + let quote = usize::from(slot.quote != AttributeQuote::Unquoted); + if !result.is_empty() { + result.push(','); + } + result.push_str(name); + result.push('='); + result.push_str(&source[slot.value_start - quote..slot.value_end + quote]); + } + result +} + pub(crate) fn extension_attributes( state: &crate::grammar::ParserState<'_>, arguments: &str, From ff502deb00bd809a4a7cfdb02559cec33d9b3563 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:32:55 +0100 Subject: [PATCH 43/55] feat(parser): normalize registered cross-reference targets before resolution Refs SC-548. --- acdc-parser/CHANGELOG.md | 2 + acdc-parser/README.adoc | 8 + acdc-parser/README.md | 8 + acdc-parser/src/extensions/block_style.rs | 6 +- acdc-parser/src/extensions/mod.rs | 1 + acdc-parser/src/extensions/registry.rs | 115 +++++++++-- acdc-parser/src/extensions/source.rs | 27 +-- acdc-parser/src/grammar/document/finish.rs | 34 ++-- acdc-parser/src/grammar/inlines.rs | 1 - acdc-parser/src/grammar/inlines/links.rs | 32 +-- acdc-parser/src/grammar/inlines/peg.rs | 11 +- acdc-parser/src/grammar/location_mapping.rs | 3 - acdc-parser/src/grammar/mod.rs | 1 + .../src/grammar/reference_normalization.rs | 125 ++++++++++++ acdc-parser/src/lib.rs | 1 + acdc-parser/src/preprocessor/include.rs | 8 +- acdc-parser/src/preprocessor/mod.rs | 1 + acdc-parser/tests/references/main.rs | 1 + acdc-parser/tests/references/normalization.rs | 184 ++++++++++++++++++ 19 files changed, 466 insertions(+), 103 deletions(-) create mode 100644 acdc-parser/src/grammar/reference_normalization.rs create mode 100644 acdc-parser/tests/references/normalization.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 15230ddb1..3534bddfc 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Registered extensions can rewrite cross-reference targets before resolution in both xref syntaxes, with access to the original source location. + - Block macros can forward selected named arguments to generated blocks while preserving attribute quoting and escaping. - In unsafe mode, registered block macros can read relative local targets through the configured include loader and report recoverable warnings at the invocation. Target reads count toward the document’s include byte limit. diff --git a/acdc-parser/README.adoc b/acdc-parser/README.adoc index 73a1c7b28..7ede69a61 100644 --- a/acdc-parser/README.adoc +++ b/acdc-parser/README.adoc @@ -2068,6 +2068,14 @@ In unsafe mode a block macro can read its relative local target with the bytes, decoded as UTF-8 or using a Unicode byte order mark. These reads share the include byte budget. Use `warn` to report a recoverable problem at the invocation. +Use `RegistryBuilder::register_reference_normalizer` to rewrite the destination of +a cross-reference before local or external resolution. Both xref forms pass the +restored target and original source location to each normalizer in registration order. +Return `Ok(None)` to pass the target through, `Ok(Some(target))` to replace it, +or an error message to stop parsing at the reference. URI schemes and network paths +bypass normalization. The built-in `with_force_local_file_xrefs()` option applies +to the resulting target. Explicit labels keep their authored text and formatting. + A block macro can return an ordinary block directly. For example, a handler for `logo::acme[]` can return `Ok(BlockBuilder::image("acme.svg").into())`. The image inherits the invocation's title, ID, roles, and source location. diff --git a/acdc-parser/README.md b/acdc-parser/README.md index a5729bf53..021e7de77 100644 --- a/acdc-parser/README.md +++ b/acdc-parser/README.md @@ -1712,6 +1712,14 @@ In unsafe mode a block macro can read its relative local target with the bytes, decoded as UTF-8 or using a Unicode byte order mark. These reads share the include byte budget. Use `warn` to report a recoverable problem at the invocation. +Use `RegistryBuilder::register_reference_normalizer` to rewrite the destination of +a cross-reference before local or external resolution. Both xref forms pass the +restored target and original source location to each normalizer in registration order. +Return `Ok(None)` to pass the target through, `Ok(Some(target))` to replace it, +or an error message to stop parsing at the reference. URI schemes and network paths +bypass normalization. The built-in `with_force_local_file_xrefs()` option applies +to the resulting target. Explicit labels keep their authored text and formatting. + A block macro can return an ordinary block directly. For example, a handler for `logo::acme[]` can return `Ok(BlockBuilder::image("acme.svg").into())`. The image inherits the invocation's title, ID, roles, and source location. diff --git a/acdc-parser/src/extensions/block_style.rs b/acdc-parser/src/extensions/block_style.rs index dff0696fb..4e69cd19a 100644 --- a/acdc-parser/src/extensions/block_style.rs +++ b/acdc-parser/src/extensions/block_style.rs @@ -6,7 +6,7 @@ use crate::{ BlockMetadata, ElementAttributes, SourceLocation, Substitution, ast::DocumentAttributesRef, }; -use super::{BlockBuilder, TitleSource, source::SourceRegistration}; +use super::{BlockBuilder, TitleSource, registry::ProcessorFactory}; /// Delimited source forms supported by a raw block style. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -85,7 +85,7 @@ where /// A named block style, its supported source forms, and its per-document factory. #[derive(Clone, Debug)] pub struct BlockStyle { - pub(super) handler: SourceRegistration>, + pub(super) handler: ProcessorFactory>, pub(super) contexts: Vec, positional: Vec, defaults: ElementAttributes<'static>, @@ -144,7 +144,7 @@ impl BlockStyle { factory: impl Fn() -> P + Send + Sync + 'static, ) -> Self { Self { - handler: SourceRegistration { + handler: ProcessorFactory { name: name.into(), factory: Arc::new(move || Box::new(factory())), }, diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 71999a606..2146e654b 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -229,6 +229,7 @@ pub(crate) use display::{DisplayState, GeneratedDisplay}; pub use editor::DocumentEditor; pub use inline::InlineSpec; pub use query::{BlockContext, BlockView, DocumentQuery}; +pub(crate) use registry::ReferenceNormalizer; pub use registry::{RegistrationError, Registry, RegistryBuilder}; pub use session::ExtensionParseResult; pub use target::{TargetError, TargetId}; diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 087a3560c..6b7b35088 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -1,13 +1,35 @@ -use std::{collections::HashMap, path::Path, sync::Arc}; +use std::{collections::HashMap, fmt, path::Path, sync::Arc}; use crate::{Error, Options, ParseResult}; use super::{ BlockMacro, BlockStyle, DocumentEditor, ExtensionParseResult, IncludeProcessor, IncludeProcessors, RawBlockContext, Session, SourcePreprocessor, TreeProcessorRegistration, - source::SourceRegistration, }; +pub(super) struct ProcessorFactory { + pub(super) name: String, + pub(super) factory: Arc Box

+ Send + Sync>, +} + +impl Clone for ProcessorFactory

{ + fn clone(&self) -> Self { + Self { + name: self.name.clone(), + factory: Arc::clone(&self.factory), + } + } +} + +impl fmt::Debug for ProcessorFactory

{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("ProcessorFactory").field(&self.name).finish() + } +} + +pub(crate) type ReferenceNormalizer = + dyn FnMut(&str, &crate::SourceLocation) -> Result, String>; + /// A registration rejected before any document is parsed. #[derive(Debug, thiserror::Error, PartialEq, Eq)] #[non_exhaustive] @@ -26,6 +48,8 @@ pub enum RegistrationError { DuplicateTreeProcessor(String), #[error("source preprocessor is already registered: {0}")] DuplicatePreprocessor(String), + #[error("reference normalizer is already registered: {0}")] + DuplicateReferenceNormalizer(String), #[error("include processor is already registered: {0}")] DuplicateIncludeProcessor(String), #[error("deferred processor already registered for block macro: {0}")] @@ -39,8 +63,9 @@ pub struct RegistryBuilder { macros: Vec, names: HashMap, trees: Vec, - preprocessors: Vec>, - includes: Vec>, + preprocessors: Vec>, + includes: Vec>, + normalizers: Vec>, } impl RegistryBuilder { @@ -61,19 +86,27 @@ impl RegistryBuilder { self.check_tree_name(descriptor)?; } for entry in ®istry.0.preprocessors { - check_source_name( + check_processor_name( &self.preprocessors, &entry.name, RegistrationError::DuplicatePreprocessor, )?; } for entry in ®istry.0.includes { - check_source_name( + check_processor_name( &self.includes, &entry.name, RegistrationError::DuplicateIncludeProcessor, )?; } + for entry in ®istry.0.normalizers { + check_processor_name( + &self.normalizers, + &entry.name, + RegistrationError::DuplicateReferenceNormalizer, + )?; + } + self.normalizers.extend_from_slice(®istry.0.normalizers); self.preprocessors .extend_from_slice(®istry.0.preprocessors); self.styles.extend_from_slice(®istry.0.styles); @@ -124,12 +157,56 @@ impl RegistryBuilder { factory: impl Fn() -> P + Send + Sync + 'static, ) -> Result<&mut Self, RegistrationError> { let name = name.into(); - check_source_name( + check_processor_name( &self.preprocessors, &name, RegistrationError::DuplicatePreprocessor, )?; - self.preprocessors.push(SourceRegistration { + self.preprocessors.push(ProcessorFactory { + name, + factory: Arc::new(move || Box::new(factory())), + }); + Ok(self) + } + + /// Normalize restored cross-reference targets before the parser resolves them. + /// Each document gets fresh callbacks, applied in registration order. A callback + /// receives the current target and the authored reference's source location. + /// Return `Ok(Some(target))` to rewrite it or `Ok(None)` to keep it. + /// URI schemes and network paths bypass the remaining normalizers. The + /// built-in file-to-local option runs last. Display text stays independent. + /// + /// ``` + /// use acdc_parser::{Options, SourceLocation, extensions::Registry}; + /// + /// let mut builder = Registry::builder(); + /// builder.register_reference_normalizer("chapter-move", || { + /// |target: &str, _: &SourceLocation| { + /// Ok(target.strip_prefix("old.adoc#").map(|id| format!("new.adoc#{id}"))) + /// } + /// })?; + /// let parsed = builder.build().parse("xref:old.adoc#intro[Introduction]", &Options::default())?.finish()?; + /// # Ok::<(), Box>(()) + /// ``` + /// + /// # Errors + /// Registration rejects invalid or duplicate names. A callback error stops + /// parsing with a located [`Error::Extension`]. + pub fn register_reference_normalizer( + &mut self, + name: impl Into, + factory: impl Fn() -> N + Send + Sync + 'static, + ) -> Result<&mut Self, RegistrationError> + where + N: FnMut(&str, &crate::SourceLocation) -> Result, String> + 'static, + { + let name = name.into(); + check_processor_name( + &self.normalizers, + &name, + RegistrationError::DuplicateReferenceNormalizer, + )?; + self.normalizers.push(ProcessorFactory { name, factory: Arc::new(move || Box::new(factory())), }); @@ -146,12 +223,12 @@ impl RegistryBuilder { factory: impl Fn() -> P + Send + Sync + 'static, ) -> Result<&mut Self, RegistrationError> { let name = name.into(); - check_source_name( + check_processor_name( &self.includes, &name, RegistrationError::DuplicateIncludeProcessor, )?; - self.includes.push(SourceRegistration { + self.includes.push(ProcessorFactory { name, factory: Arc::new(move || Box::new(factory())), }); @@ -237,12 +314,13 @@ impl RegistryBuilder { trees: self.trees, preprocessors: self.preprocessors, includes: self.includes, + normalizers: self.normalizers, })) } } -fn check_source_name( - entries: &[SourceRegistration

], +fn check_processor_name( + entries: &[ProcessorFactory

], name: &str, duplicate: fn(String) -> RegistrationError, ) -> Result<(), RegistrationError> { @@ -280,8 +358,9 @@ struct RegistryData { macros: Vec, names: HashMap, trees: Vec, - preprocessors: Vec>, - includes: Vec>, + preprocessors: Vec>, + includes: Vec>, + normalizers: Vec>, } /// A cheap-to-clone, immutable collection of extension factories. @@ -296,7 +375,7 @@ impl Registry { #[must_use] pub fn is_empty(&self) -> bool { - !self.has_input_processors() && self.0.trees.is_empty() + !self.has_input_processors() && self.0.trees.is_empty() && self.0.normalizers.is_empty() } fn has_input_processors(&self) -> bool { @@ -306,6 +385,12 @@ impl Registry { && self.0.includes.is_empty()) } + pub(crate) fn reference_normalizers( + &self, + ) -> impl Iterator> + '_ { + self.0.normalizers.iter().map(|entry| (entry.factory)()) + } + pub(crate) fn preprocessors(&self) -> impl Iterator> + '_ { self.0.preprocessors.iter().map(|entry| (entry.factory)()) } diff --git a/acdc-parser/src/extensions/source.rs b/acdc-parser/src/extensions/source.rs index 76620434d..70ad4a84d 100644 --- a/acdc-parser/src/extensions/source.rs +++ b/acdc-parser/src/extensions/source.rs @@ -1,7 +1,8 @@ //! Document-local hooks for the entry source and resolved includes. -use std::{cell::RefCell, fmt, path::Path, sync::Arc}; +use std::{cell::RefCell, fmt, path::Path}; +use super::registry::ProcessorFactory; use crate::{ DocumentAttributes, Error, IncludeSource, IncludeSourceTarget, Position, SourceLocation, Warning, WarningKind, warning::WarningCollection, @@ -124,33 +125,11 @@ where } } -pub(super) struct SourceRegistration { - pub(super) name: String, - pub(super) factory: Arc Box

+ Send + Sync>, -} - -impl Clone for SourceRegistration

{ - fn clone(&self) -> Self { - Self { - name: self.name.clone(), - factory: Arc::clone(&self.factory), - } - } -} - -impl fmt::Debug for SourceRegistration

{ - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("SourceRegistration") - .field(&self.name) - .finish() - } -} - /// Nested include scopes share the active document's processor instances. pub(crate) struct IncludeProcessors(RefCell]>>); impl IncludeProcessors { - pub(super) fn new(registrations: &[SourceRegistration]) -> Option { + pub(super) fn new(registrations: &[ProcessorFactory]) -> Option { (!registrations.is_empty()).then(|| { Self(RefCell::new( registrations.iter().map(|r| (r.factory)()).collect(), diff --git a/acdc-parser/src/grammar/document/finish.rs b/acdc-parser/src/grammar/document/finish.rs index b17053195..86df06314 100644 --- a/acdc-parser/src/grammar/document/finish.rs +++ b/acdc-parser/src/grammar/document/finish.rs @@ -45,18 +45,6 @@ pub(super) fn finish<'a>( next_suffix: HashMap::new(), natural_targets: HashMap::new(), }; - let mut xrefs = Vec::new(); - if let Some(header) = &header { - collect_header_references(state, header, &attributes, &mut references, &mut xrefs); - } - collect_references(state, &mut blocks, &mut references, &mut xrefs); - section::number_parsed_sections( - &mut blocks, - &mut state.toc_entries, - &mut references.entries, - is_book_doctype(&attributes), - ); - let mut document = Document { generated_displays: crate::extensions::DisplayState::default(), header, @@ -66,8 +54,28 @@ pub(super) fn finish<'a>( blocks, footnotes: state.footnote_tracker.borrow().footnotes.clone(), toc_entries: state.toc_entries.clone(), - references: references.entries, + references: HashMap::new(), }; + crate::grammar::reference_normalization::normalize_document(state, &mut document)?; + let mut xrefs = Vec::new(); + if let Some(header) = &document.header { + collect_header_references( + state, + header, + &document.attributes, + &mut references, + &mut xrefs, + ); + } + collect_references(state, &mut document.blocks, &mut references, &mut xrefs); + section::number_parsed_sections( + &mut document.blocks, + &mut document.toc_entries, + &mut references.entries, + is_book_doctype(&document.attributes), + ); + + document.references = references.entries; register_document_references( state, &mut document, diff --git a/acdc-parser/src/grammar/inlines.rs b/acdc-parser/src/grammar/inlines.rs index fa2205034..0ad2c7ddd 100644 --- a/acdc-parser/src/grammar/inlines.rs +++ b/acdc-parser/src/grammar/inlines.rs @@ -12,5 +12,4 @@ mod text; pub(super) mod typography; mod ui; -pub(super) use links::force_local_file_xref; pub(crate) use peg::inline_parser; diff --git a/acdc-parser/src/grammar/inlines/links.rs b/acdc-parser/src/grammar/inlines/links.rs index c9c2dc7a8..090ba9814 100644 --- a/acdc-parser/src/grammar/inlines/links.rs +++ b/acdc-parser/src/grammar/inlines/links.rs @@ -1,7 +1,7 @@ //! Link attributes and cross-reference labels. use crate::{ - ContentAttribute, CrossReference, InlineMetadata, InlineNode, + ContentAttribute, InlineMetadata, InlineNode, grammar::{ ParserState, attributes::{AttributeQuote, ScannedAttribute}, @@ -15,38 +15,10 @@ use crate::{ }, }, }, - model::{MacroAttributes, XrefSourceSyntax}, + model::MacroAttributes, }; use std::{borrow::Cow, ops::Range}; -pub(in crate::grammar) fn force_local_file_xref(xref: &mut CrossReference<'_>) { - if let Some(fragment) = file_xref_fragment(xref.target) { - xref.target = fragment; - xref.target_is_local = true; - xref.source_syntax = XrefSourceSyntax::LocalFragment; - } -} - -fn file_xref_fragment(target: &str) -> Option<&str> { - // Restore protected text before checking whether the prefix is a URL. - if target.contains("���") { - return None; - } - let (path, fragment) = target.split_once('#')?; - let has_scheme = path.split_once(':').is_some_and(|(scheme, _)| { - let Some((first, rest)) = scheme.as_bytes().split_first() else { - return false; - }; - // A single letter is a Windows drive prefix, as it is for includes. - !rest.is_empty() - && first.is_ascii_alphabetic() - && rest - .iter() - .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')) - }); - (!fragment.is_empty() && !path.starts_with("//") && !has_scheme).then_some(fragment) -} - /// The label and controls in `xref:target[...]`. pub(super) struct XrefMacroText<'s> { /// The link text, empty for an automatic reference. diff --git a/acdc-parser/src/grammar/inlines/peg.rs b/acdc-parser/src/grammar/inlines/peg.rs index 2a6c53a7f..08d781c90 100644 --- a/acdc-parser/src/grammar/inlines/peg.rs +++ b/acdc-parser/src/grammar/inlines/peg.rs @@ -20,10 +20,7 @@ use crate::{ IndexTermForm, IndexTermSegment, expand_escaped_index_terms, parse_index_term, trimmed_index_term_segment, }, - links::{ - LinkContent, ProcessedLinkContent, force_local_file_xref, process_link_content, - xref_macro_text, - }, + links::{LinkContent, ProcessedLinkContent, process_link_content, xref_macro_text}, recognition::{ autolink_start, byte_came_from_attribute, catalog_escape_allowed, catalog_macro_allowed, check_code_opening_boundary, code_followed_by_attribute, @@ -1385,9 +1382,6 @@ peg::parser! { if xref.resolve_natural_target { xref.source_syntax = crate::model::XrefSourceSyntax::Shorthand; } - if state.options.force_local_file_xrefs() { - force_local_file_xref(&mut xref); - } xref.target_is_local = xref.source_syntax.target_is_local(xref.target); xref.xrefstyle = crate::XrefStyle::from_attribute( state @@ -1452,9 +1446,6 @@ peg::parser! { if !state.options.compatibility_mode.legacy_controls_enabled(&state.document_attributes) { xref.source_syntax = crate::model::XrefSourceSyntax::Macro; } - if state.options.force_local_file_xrefs() { - force_local_file_xref(&mut xref); - } xref.target_is_local = xref.source_syntax.target_is_local(xref.target); // A per-reference `xrefstyle=` wins over the document's, including // an unrecognized one, which Asciidoctor treats as `basic`. diff --git a/acdc-parser/src/grammar/location_mapping.rs b/acdc-parser/src/grammar/location_mapping.rs index 539d51f47..7f13448c6 100644 --- a/acdc-parser/src/grammar/location_mapping.rs +++ b/acdc-parser/src/grammar/location_mapping.rs @@ -699,9 +699,6 @@ fn map_inline_macro<'a>( xref.target = state.intern_str(&restored); xref.target_is_local = xref.source_syntax.target_is_local(xref.target); xref.resolve_natural_target = false; - if state.options.force_local_file_xrefs() { - super::inlines::force_local_file_xref(xref); - } } } } diff --git a/acdc-parser/src/grammar/mod.rs b/acdc-parser/src/grammar/mod.rs index 5b566c928..f69b86de4 100644 --- a/acdc-parser/src/grammar/mod.rs +++ b/acdc-parser/src/grammar/mod.rs @@ -20,6 +20,7 @@ mod location_walk; pub(crate) use location_walk::try_walk_document_inline_nodes_mut; mod marked_text; mod passthrough_processing; +pub(crate) mod reference_normalization; pub(crate) mod reference_text; pub(crate) mod reference_walk; pub(crate) mod setext; diff --git a/acdc-parser/src/grammar/reference_normalization.rs b/acdc-parser/src/grammar/reference_normalization.rs new file mode 100644 index 000000000..8d12beed7 --- /dev/null +++ b/acdc-parser/src/grammar/reference_normalization.rs @@ -0,0 +1,125 @@ +//! Normalize accepted reference uses before resolution and share their targets with catalog copies. + +use std::collections::{HashMap, hash_map::Entry}; + +use crate::{ + Document, Error, InlineMacro, InlineNode, Options, + extensions::{ReferenceNormalizer, Registry}, + model::XrefSourceSyntax, +}; + +use super::{ParserState, location_walk::try_walk_owned_inline_nodes_mut}; + +struct Normalization<'a> { + processors: Vec>, + force_local: bool, + // Diagnostics, the tree, and copied titles can all refer to the same occurrence. + rewritten: HashMap<(usize, usize, &'a str), &'a str>, +} + +impl<'a> Normalization<'a> { + fn new(options: &Options<'_>) -> Self { + Self { + processors: options + .extensions + .iter() + .flat_map(Registry::reference_normalizers) + .collect(), + force_local: options.force_local_file_xrefs(), + rewritten: HashMap::new(), + } + } + + fn is_active(&self) -> bool { + self.force_local || !self.processors.is_empty() + } + + fn normalize( + &mut self, + state: &ParserState<'a>, + node: &mut InlineNode<'a>, + ) -> Result<(), Error> { + let InlineNode::Macro(InlineMacro::CrossReference(xref)) = node else { + return Ok(()); + }; + let target = &mut xref.target; + let location = &xref.location; + if !self.processors.is_empty() && !excluded(target) { + let key = (location.absolute_start, location.absolute_end, *target); + *target = match self.rewritten.entry(key) { + Entry::Occupied(entry) => *entry.get(), + Entry::Vacant(entry) => { + let source = state.create_error_source_location(location.clone()); + let replacement = rewrite(&mut self.processors, target, &source) + .map_err(|message| Error::Extension(Box::new(source), message))?; + *entry.insert( + replacement + .as_deref() + .map_or(*target, |value| state.intern_str(value)), + ) + } + }; + } + if self.force_local + && let Some((path, fragment)) = target.split_once('#') + && !fragment.is_empty() + && !excluded(path) + { + *target = fragment; + xref.source_syntax = XrefSourceSyntax::LocalFragment; + } + xref.target_is_local = xref.source_syntax.target_is_local(xref.target); + Ok(()) + } +} + +fn rewrite( + processors: &mut [Box], + target: &str, + source: &crate::SourceLocation, +) -> Result, String> { + let mut replacement = None; + for processor in processors { + let current = replacement.as_deref().unwrap_or(target); + if excluded(current) { + break; + } + if let Some(next) = processor(current, source)? { + replacement = Some(next); + } + } + Ok(replacement) +} + +/// Preserve network paths and multi-letter URI schemes. A single letter can be a Windows drive. +fn excluded(target: &str) -> bool { + target.starts_with("//") || crate::preprocessor::uri_scheme(target).is_some() +} + +pub(super) fn normalize_document<'a>( + state: &ParserState<'a>, + document: &mut Document<'a>, +) -> Result<(), Error> { + let mut normalization = Normalization::new(&state.options); + if normalization.is_active() { + super::try_walk_document_inline_nodes_mut(document, &mut |node| { + normalization.normalize(state, node) + })?; + } + Ok(()) +} + +pub(crate) fn normalize_fragment<'a>( + state: &ParserState<'a>, + inlines: &mut [InlineNode<'a>], +) -> Result<(), Error> { + let mut normalization = Normalization::new(&state.options); + if normalization.is_active() { + for node in inlines { + try_walk_owned_inline_nodes_mut(node, &mut |node| { + normalization.normalize(state, node) + })?; + } + } + Ok(()) +} diff --git a/acdc-parser/src/lib.rs b/acdc-parser/src/lib.rs index 712bec434..568d4ebff 100644 --- a/acdc-parser/src/lib.rs +++ b/acdc-parser/src/lib.rs @@ -766,6 +766,7 @@ pub fn parse_inline(input: &str, options: &Options<'_>) -> Result Result { - if let Some(scheme) = include_uri_scheme(target) { + if let Some(scheme) = uri_scheme(target) { if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") { Url::parse(target)?; return Ok(Self::Url(target.to_string())); @@ -213,7 +213,7 @@ impl Target { /// Provenance: Claude investigated this behavior and wrote this function; this seems fine /// and I also looked at the asciidoctor source myself and _roughly_ matches. I'm not sure /// if I'm just carrying dead weight from asciidoctor though. -fn include_uri_scheme(target: &str) -> Option<&str> { +pub(crate) fn uri_scheme(target: &str) -> Option<&str> { let (scheme, _) = target.split_once(':')?; let (first, rest) = scheme.as_bytes().split_first()?; (!rest.is_empty() @@ -1655,7 +1655,7 @@ mod tests { ("ab:/path", "ab"), ("HTTP://example.test/path", "HTTP"), ] { - assert_eq!(include_uri_scheme(target), Some(expected), "{target}"); + assert_eq!(uri_scheme(target), Some(expected), "{target}"); } for target in [ @@ -1669,7 +1669,7 @@ mod tests { "ab¾:valeur", "ab①:valeur", ] { - assert_eq!(include_uri_scheme(target), None, "{target}"); + assert_eq!(uri_scheme(target), None, "{target}"); } let source_origin = SourceOrigin::File { diff --git a/acdc-parser/src/preprocessor/mod.rs b/acdc-parser/src/preprocessor/mod.rs index f77d41fb2..38926a31c 100644 --- a/acdc-parser/src/preprocessor/mod.rs +++ b/acdc-parser/src/preprocessor/mod.rs @@ -32,6 +32,7 @@ mod source; mod tag; use comment::CommentScanner; +pub(crate) use include::uri_scheme; use include::{Include, IncludeResult, LocationContext}; pub(crate) use source::SourceReader; diff --git a/acdc-parser/tests/references/main.rs b/acdc-parser/tests/references/main.rs index 05cbd4be0..2149a07eb 100644 --- a/acdc-parser/tests/references/main.rs +++ b/acdc-parser/tests/references/main.rs @@ -27,6 +27,7 @@ mod list_anchor_ownership; mod missing_footnote_recovery; mod named_index_delimiters; mod named_title_content; +mod normalization; mod reference_content; mod reference_identity; mod reference_typography; diff --git a/acdc-parser/tests/references/normalization.rs b/acdc-parser/tests/references/normalization.rs new file mode 100644 index 000000000..cbdee0e59 --- /dev/null +++ b/acdc-parser/tests/references/normalization.rs @@ -0,0 +1,184 @@ +//! Semantic reference extensions share the parser's identity and diagnostic rules. + +use acdc_parser::{ + CompatibilityMode, Options, SafeMode, SourceLocation, WarningKind, + ast::{BlockKind, BlockRef, InlineKind}, + extensions::{RegistrationError, Registry}, +}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +type TestResult = Result<(), Box>; + +fn missing_targets(warnings: &[acdc_parser::Warning]) -> Vec<&str> { + warnings + .iter() + .filter_map(|warning| { + let WarningKind::UnresolvedReference { target } = &warning.kind else { + return None; + }; + Some(target.as_str()) + }) + .collect() +} + +#[test] +fn normalized_targets_use_normal_resolution_and_preserve_authored_labels() -> TestResult { + let mut builder = Registry::builder(); + let calls = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&calls); + builder.register_reference_normalizer("aliases", move || { + let counter = Arc::clone(&counter); + move |target: &str, _: &SourceLocation| { + counter.fetch_add(1, Ordering::Relaxed); + Ok(Some( + match target { + "old#intro" => "step-two", + "elsewhere" => "other.adoc#intro", + "gone" => "missing", + other => return Err(format!("unexpected target {other}")), + } + .to_owned(), + )) + } + })?; + builder.register_reference_normalizer("anchors", || { + |target: &str, _: &SourceLocation| Ok((target == "step-two").then(|| "intro".to_owned())) + })?; + let registry = builder.build(); + let source = r"See <> and xref:old#intro[]. +xref:elsewhere[] <> xref:https://example.org/pass:[a]#b[Remote] <>. +\xref:escaped[] and \<>. + +[[intro]] +== Introduction"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let initial = calls.load(Ordering::Relaxed); + let ordinary = Registry::default().parse(source, &options)?.finish()?; + let Some(BlockKind::Paragraph(p)) = ordinary.document().blocks().next().map(BlockRef::kind) + else { + return Err("expected introductory paragraph".into()); + }; + assert!(p.content().inlines().any(|n| matches!(n.kind(), InlineKind::CrossReference(x) if x.target()=="old#intro" && !x.target_is_local()))); + let mut result = registry.parse(source, &options)?; + result.normalize()?; + result.normalize()?; + let parsed = result.finish()?; + assert_eq!(calls.load(Ordering::Relaxed) - initial, 4); + let Some(BlockKind::Paragraph(p)) = parsed.document().blocks().next().map(BlockRef::kind) + else { + return Err("expected introductory paragraph".into()); + }; + let targets: Vec<_> = p + .content() + .inlines() + .filter_map(|node| { + let InlineKind::CrossReference(xref) = node.kind() else { + return None; + }; + let label = xref.text().inlines().next().and_then(|node| { + let InlineKind::Plain(text) = node.kind() else { + return None; + }; + Some(text.text()) + }); + Some((xref.target(), xref.target_is_local(), label)) + }) + .collect(); + assert_eq!( + targets, + [ + ("intro", true, Some("Explicit")), + ("intro", true, None), + ("other.adoc#intro", false, None), + ("missing", true, None), + ("https://example.org/a#b", false, Some("Remote")), + ("//host/a#b", false, Some("Remote")) + ] + ); + assert_eq!(missing_targets(parsed.warnings()), ["missing"]); + } + Ok(()) +} + +#[test] +fn normalizer_failure_points_to_the_original_included_reference() -> TestResult { + let temp = tempfile::tempdir()?; + let main = temp.path().join("main.adoc"); + let child = temp.path().join("chapter.adoc"); + std::fs::write(&main, "= Test\n\ninclude::chapter.adoc[]\n")?; + std::fs::write(&child, "Text.\n\nSee xref:old#pass:[bad][Label].\n")?; + let mut builder = Registry::builder(); + builder.register_reference_normalizer("reject", || { + |target: &str, _: &SourceLocation| Err(format!("rejected {target}")) + })?; + let options = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let Err(acdc_parser::Error::Extension(source, message)) = + builder.build().parse_file(&main, &options) + else { + return Err("expected a located extension error".into()); + }; + assert_eq!(message, "rejected old#bad"); + assert_eq!(source.file.as_deref(), Some(child.as_path())); + assert_eq!( + (source.location.start.line, source.location.start.column), + (3, 5) + ); + Ok(()) +} + +#[test] +fn registration_is_atomic_and_scoped_to_each_parse() -> TestResult { + let mut builder = Registry::builder(); + builder.register_reference_normalizer("ordered", || { + let mut ordinal = 0; + move |_: &str, _: &SourceLocation| { + ordinal += 1; + Ok(Some(format!("part.adoc#entry-{ordinal}"))) + } + })?; + let registry = builder.build(); + assert!(!registry.is_empty()); + let mut selected = Registry::builder(); + selected.extend(®istry)?; + assert!( + matches!(selected.extend(®istry),Err(RegistrationError::DuplicateReferenceNormalizer(name)) if name=="ordered") + ); + let options = Options::builder().with_force_local_file_xrefs().build()?; + let selected = selected.build(); + // A section's title also appears in the TOC and reference catalog. + for _ in 0..2 { + let parsed = selected + .parse("== See <>\n\nxref:two[]", &options)? + .finish()?; + assert_eq!(missing_targets(parsed.warnings()), ["entry-1", "entry-2"]); + let Some(BlockKind::Section(section)) = + parsed.document().blocks().next().map(BlockRef::kind) + else { + return Err("expected a section".into()); + }; + assert_eq!( + section.id().ok_or("missing section ID")?.as_str(), + "_see_entry_1" + ); + let toc = parsed + .document() + .toc_entries() + .next() + .ok_or("missing TOC entry")?; + assert_eq!(toc.title(), section.title()); + assert!( + section + .title() + .ok_or("missing section title")? + .inlines() + .any(|n| matches!(n.kind(),InlineKind::CrossReference(x) if x.target()=="entry-1")) + ); + } + Ok(()) +} From cd60df37d88e432dead2ea51d026942eb0c17c1e Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 23:03:18 +0100 Subject: [PATCH 44/55] feat(extensions): expand registered inline macros per conversion Retain authored invocations in macro-enabled spans and resolve them after tree edits with the selected backend and source-position attributes. Give each conversion its own processors and counters, and reuse each result across copied labels. Refs SC-549 --- acdc-parser/CHANGELOG.md | 5 + acdc-parser/benches/parser_bench.rs | 26 +- .../schemas/asg/support-inventory.json | 13 + acdc-parser/src/asg/diagnostics.rs | 1 + acdc-parser/src/asg/projection.rs | 6 +- acdc-parser/src/asg/projection/spans.rs | 3 +- acdc-parser/src/ast/blocks.rs | 9 +- acdc-parser/src/ast/inlines.rs | 150 +++-------- acdc-parser/src/extensions/display.rs | 3 +- .../src/extensions/display/prepared.rs | 55 +++- acdc-parser/src/extensions/late_inline.rs | 236 ++++++++++++++++++ acdc-parser/src/extensions/mod.rs | 5 + acdc-parser/src/extensions/registry.rs | 111 +++++++- acdc-parser/src/grammar/document/finish.rs | 1 + acdc-parser/src/grammar/document/manpage.rs | 1 + acdc-parser/src/grammar/document/table.rs | 3 +- acdc-parser/src/grammar/footnotes.rs | 1 + acdc-parser/src/grammar/inline_processing.rs | 38 ++- acdc-parser/src/grammar/inlines.rs | 1 + acdc-parser/src/grammar/inlines/extensions.rs | 198 +++++++++++++++ acdc-parser/src/grammar/inlines/peg.rs | 20 ++ .../grammar/inlines/typography/neighbors.rs | 3 + acdc-parser/src/grammar/location_mapping.rs | 30 +++ acdc-parser/src/grammar/location_walk.rs | 3 +- acdc-parser/src/grammar/marked_text.rs | 1 + .../src/grammar/passthrough_processing.rs | 6 +- acdc-parser/src/grammar/reference_walk.rs | 3 +- acdc-parser/src/grammar/state.rs | 12 + acdc-parser/src/model/inlines/mod.rs | 10 + acdc-parser/src/model/mod.rs | 1 + acdc-parser/src/model/section.rs | 1 + acdc-parser/src/proptests/invariants.rs | 3 +- converters/core/CHANGELOG.md | 4 + converters/core/src/display.rs | 2 +- converters/core/src/pipeline.rs | 46 +++- converters/html/tests/late_inline_macros.rs | 236 ++++++++++++++++++ 36 files changed, 1108 insertions(+), 139 deletions(-) create mode 100644 acdc-parser/src/extensions/late_inline.rs create mode 100644 acdc-parser/src/grammar/inlines/extensions.rs create mode 100644 converters/html/tests/late_inline_macros.rs diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 3534bddfc..c18f58f19 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Extensions can register full and short inline macros or a pair of custom + delimiters. Registered calls in macro-enabled text retain their source span + and arguments for conversion. A short macro receives its bracket content as + its target. The ordinary parser continues to produce eager inline content. + - Registered extensions can rewrite cross-reference targets before resolution in both xref syntaxes, with access to the original source location. - Block macros can forward selected named arguments to generated blocks while preserving attribute quoting and escaping. diff --git a/acdc-parser/benches/parser_bench.rs b/acdc-parser/benches/parser_bench.rs index cfd746f4a..5ac0252e6 100644 --- a/acdc-parser/benches/parser_bench.rs +++ b/acdc-parser/benches/parser_bench.rs @@ -2,7 +2,11 @@ use std::{fmt::Write as _, fs, hint::black_box, time::Duration}; use acdc_parser::{ Options, Parser, - extensions::{BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroInvocation, Registry}, + extensions::{ + BlockMacro, BlockMacroOutput, BlockMacroProcessor, InlineConversionContext, + InlineInvocation, InlineMacroOutput, InlineMacroProcessor, InlineMatcher, MacroInvocation, + Registry, + }, parse, parse_file, }; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; @@ -218,6 +222,16 @@ impl BlockMacroProcessor for CheapMacro { } } +impl InlineMacroProcessor for CheapMacro { + fn process( + &mut self, + _: &InlineInvocation<'_>, + _: &mut InlineConversionContext<'_>, + ) -> Result { + Ok(InlineMacroOutput::LineBreak) + } +} + #[allow(clippy::expect_used)] fn extension_benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("extensions"); @@ -237,6 +251,16 @@ fn extension_benchmark(c: &mut Criterion) { group.bench_function("unused_registrations_100", |b| { b.iter(|| black_box(registered.parse(black_box(ordinary), &options))); }); + let mut inlines = Registry::builder(); + for index in 0..100 { + inlines + .register_inline_macro(format!("cheap{index}"), InlineMatcher::Full, || CheapMacro) + .expect("valid inline registration"); + } + let inlines = inlines.build(); + group.bench_function("unused_inline_registrations_100", |b| { + b.iter(|| black_box(inlines.parse(black_box(ordinary), &options))); + }); let macros = "cheap0::target[]\n\n".repeat(1000); assert!(registered.parse(¯os, &options).is_ok()); group.bench_function("cheap_callbacks_1000", |b| { diff --git a/acdc-parser/schemas/asg/support-inventory.json b/acdc-parser/schemas/asg/support-inventory.json index 72cb2ffb2..987674a1b 100644 --- a/acdc-parser/schemas/asg/support-inventory.json +++ b/acdc-parser/schemas/asg/support-inventory.json @@ -2094,6 +2094,9 @@ "MonospaceText": [ "0" ], + "Extension": [ + "0" + ], "PlainText": [ "0" ], @@ -2202,6 +2205,12 @@ "policy": "no-direct-field-mapping-is-established-for", "upstream": "#/$defs/inline" }, + "variant:Extension": { + "policy": "unsupported" + }, + "Extension.0": { + "policy": "unsupported" + }, "variant:PlainText": { "policy": "candidate", "upstream": "#/$defs/inline" @@ -4448,6 +4457,7 @@ "shape": { "kind": "struct", "fields": [ + "has_inline_macros", "generated_displays", "header", "untitled_header_location", @@ -4493,6 +4503,9 @@ "policy": "use-authored-endpoint-coordinates-omit-an-unavailable", "upstream": "#/$defs/location" }, + "has_inline_macros": { + "policy": "source-state" + }, "generated_displays": { "policy": "source-state" } diff --git a/acdc-parser/src/asg/diagnostics.rs b/acdc-parser/src/asg/diagnostics.rs index b938f4291..63839533e 100644 --- a/acdc-parser/src/asg/diagnostics.rs +++ b/acdc-parser/src/asg/diagnostics.rs @@ -32,6 +32,7 @@ impl Error { pub(super) fn inline_construct(value: &InlineNode<'_>) -> &'static str { match value { + InlineNode::Extension(_) => "pending inline macro", InlineNode::PlainText(_) => "plain text", InlineNode::RawText(_) => "raw text", InlineNode::VerbatimText(_) => "verbatim text", diff --git a/acdc-parser/src/asg/projection.rs b/acdc-parser/src/asg/projection.rs index 0dd341578..734fbd32b 100644 --- a/acdc-parser/src/asg/projection.rs +++ b/acdc-parser/src/asg/projection.rs @@ -122,6 +122,9 @@ fn inline_value( settings: InlineContext, ) -> Result { let mut result = match value { + InlineNode::Extension(_) => { + return Err(unsupported(path, "inline macro requires conversion")); + } InlineNode::PlainText(text) => literal(settings.text_name(), text.content), InlineNode::VerbatimText(_) => { return Err(unsupported( @@ -626,7 +629,8 @@ impl<'a, 'doc> Export<'a, 'doc> { content.as_inlines().iter().any(|inline| match inline { InlineNode::PlainText(text) => !text.content.trim().is_empty(), InlineNode::RawText(text) => !text.content.trim().is_empty(), - InlineNode::CharacterReference(_) + InlineNode::Extension(_) + | InlineNode::CharacterReference(_) | InlineNode::Symbol(_) | InlineNode::VerbatimText(_) | InlineNode::BoldText(_) diff --git a/acdc-parser/src/asg/projection/spans.rs b/acdc-parser/src/asg/projection/spans.rs index eeab264c4..c7ff3a048 100644 --- a/acdc-parser/src/asg/projection/spans.rs +++ b/acdc-parser/src/asg/projection/spans.rs @@ -82,7 +82,8 @@ pub(super) fn project( settings, ) .map(|result| quotation(result, ["‘", "’"])), - InlineNode::PlainText(_) + InlineNode::Extension(_) + | InlineNode::PlainText(_) | InlineNode::VerbatimText(_) | InlineNode::Symbol(_) | InlineNode::CharacterReference(_) diff --git a/acdc-parser/src/ast/blocks.rs b/acdc-parser/src/ast/blocks.rs index 0af37945a..da7a974a7 100644 --- a/acdc-parser/src/ast/blocks.rs +++ b/acdc-parser/src/ast/blocks.rs @@ -222,7 +222,13 @@ impl<'doc> BlockRef<'doc> { } impl<'doc> DocumentRef<'doc> { - /// Whether conversion must lower symbolic display requests first. + /// Whether the parser retained an authored conversion-time inline macro. + #[must_use] + pub fn has_inline_macros(self) -> bool { + self.node.has_inline_macros + } + + /// Whether the document contains deferred display requests. #[must_use] pub fn has_deferred_displays(self) -> bool { self.node.generated_displays.is_active() @@ -528,6 +534,7 @@ impl<'doc> From> for Document<'doc> { location: header.location.clone(), }), untitled_header_location: document.untitled_header_location.clone(), + has_inline_macros: document.has_inline_macros, generated_displays: document.generated_displays.clone(), attributes: document.attributes.clone(), blocks: document.blocks.clone(), diff --git a/acdc-parser/src/ast/inlines.rs b/acdc-parser/src/ast/inlines.rs index 7e77a5033..cbc14d770 100644 --- a/acdc-parser/src/ast/inlines.rs +++ b/acdc-parser/src/ast/inlines.rs @@ -141,7 +141,13 @@ node_ref!(IndexTermRef<'doc>, crate::IndexTerm<'doc>, "An index term."); /// ``` #[derive(Clone, Copy, Debug)] pub struct InlineRef<'doc> { - kind: InlineKind<'doc>, + source: InlineSource<'doc>, +} + +#[derive(Clone, Copy, Debug)] +enum InlineSource<'doc> { + Node(&'doc InlineNode<'doc>), + Macro(&'doc InlineMacro<'doc>), } /// The semantic kind of an inline, including macros. @@ -185,55 +191,38 @@ impl<'doc> InlineRef<'doc> { /// Match the semantic kind while retaining a concrete typed handle. #[must_use] pub fn kind(self) -> InlineKind<'doc> { - self.kind + match self.source { + InlineSource::Node(node) => InlineKind::from(node), + InlineSource::Macro(node) => InlineKind::from(node), + } } /// The source span of this inline node. #[must_use] pub fn location(self) -> LocationRef<'doc> { - match self.kind { - InlineKind::Plain(node) => node.location(), - InlineKind::Symbol(node) => node.location(), - InlineKind::CharacterReference(node) => node.location(), - InlineKind::Raw(node) => node.location(), - InlineKind::Verbatim(node) => node.location(), - InlineKind::Bold(node) => node.location(), - InlineKind::Italic(node) => node.location(), - InlineKind::Monospace(node) => node.location(), - InlineKind::Highlight(node) => node.location(), - InlineKind::Subscript(node) => node.location(), - InlineKind::Superscript(node) => node.location(), - InlineKind::DoubleQuotedSpan(node) => node.location(), - InlineKind::SingleQuotedSpan(node) => node.location(), - InlineKind::StandaloneCurvedApostrophe(node) => node.location(), - InlineKind::LineBreak(node) => node.location(), - InlineKind::Anchor(node) => node.location(), - InlineKind::Callout(node) => node.location(), - InlineKind::Footnote(node) => node.location(), - InlineKind::Icon(node) => node.location(), - InlineKind::Image(node) => node.location(), - InlineKind::KeyboardShortcut(node) => node.location(), - InlineKind::Button(node) => node.location(), - InlineKind::MenuPath(node) => node.location(), - InlineKind::UrlMacro(node) => node.location(), - InlineKind::Link(node) => node.location(), - InlineKind::Mailto(node) => node.location(), - InlineKind::Autolink(node) => node.location(), - InlineKind::CrossReference(node) => node.location(), - InlineKind::Passthrough(node) => node.location(), - InlineKind::Stem(node) => node.location(), - InlineKind::IndexTerm(node) => node.location(), + match self.source { + InlineSource::Node(node) => LocationRef::from(node.location()), + InlineSource::Macro(node) => LocationRef::from(node.location()), } } } impl<'doc> From<&'doc InlineNode<'doc>> for InlineRef<'doc> { fn from(inline: &'doc InlineNode<'doc>) -> Self { - let kind = match inline { + Self { + source: InlineSource::Node(inline), + } + } +} + +impl<'doc> From<&'doc InlineNode<'doc>> for InlineKind<'doc> { + fn from(inline: &'doc InlineNode<'doc>) -> Self { + match inline { InlineNode::Symbol(node) => InlineKind::Symbol(SymbolRef::new(node)), InlineNode::CharacterReference(node) => { InlineKind::CharacterReference(CharacterReferenceRef::new(node)) } + InlineNode::Extension(call) => InlineKind::Plain(PlainRef::new(&call.literal)), InlineNode::PlainText(node) => InlineKind::Plain(PlainRef::new(node)), InlineNode::RawText(node) => InlineKind::Raw(RawRef::new(node)), InlineNode::VerbatimText(node) => InlineKind::Verbatim(VerbatimRef::new(node)), @@ -255,15 +244,22 @@ impl<'doc> From<&'doc InlineNode<'doc>> for InlineRef<'doc> { InlineNode::LineBreak(node) => InlineKind::LineBreak(LineBreakRef::new(node)), InlineNode::InlineAnchor(node) => InlineKind::Anchor(AnchorRef::new(node)), InlineNode::CalloutMarker(node) => InlineKind::Callout(CalloutMarkerRef::new(node)), - InlineNode::Macro(node) => return Self::from(node), - }; - Self { kind } + InlineNode::Macro(node) => Self::from(node), + } } } impl<'doc> From<&'doc InlineMacro<'doc>> for InlineRef<'doc> { fn from(inline: &'doc InlineMacro<'doc>) -> Self { - let kind = match inline { + Self { + source: InlineSource::Macro(inline), + } + } +} + +impl<'doc> From<&'doc InlineMacro<'doc>> for InlineKind<'doc> { + fn from(inline: &'doc InlineMacro<'doc>) -> Self { + match inline { InlineMacro::Footnote(node) => InlineKind::Footnote(FootnoteRef::new(node)), InlineMacro::Icon(node) => InlineKind::Icon(IconRef::new(node)), InlineMacro::Image(node) => InlineKind::Image(InlineImageRef::new(node)), @@ -284,8 +280,7 @@ impl<'doc> From<&'doc InlineMacro<'doc>> for InlineRef<'doc> { } InlineMacro::Stem(node) => InlineKind::Stem(StemRef::new(node)), InlineMacro::IndexTerm(node) => InlineKind::IndexTerm(IndexTermRef::new(node)), - }; - Self { kind } + } } } @@ -356,76 +351,9 @@ impl From> for crate::CalloutMarker { impl<'doc> From> for InlineNode<'doc> { fn from(read: InlineRef<'doc>) -> Self { - match read.kind() { - InlineKind::Plain(node) => InlineNode::PlainText(crate::Plain::from(node)), - InlineKind::Symbol(node) => InlineNode::Symbol(crate::Symbol::from(node)), - InlineKind::CharacterReference(node) => { - InlineNode::CharacterReference(crate::CharacterReference::from(node)) - } - InlineKind::Raw(node) => InlineNode::RawText(crate::Raw::from(node)), - InlineKind::Verbatim(node) => InlineNode::VerbatimText(crate::Verbatim::from(node)), - InlineKind::Bold(node) => InlineNode::BoldText(crate::Bold::from(node)), - InlineKind::Italic(node) => InlineNode::ItalicText(crate::Italic::from(node)), - InlineKind::Monospace(node) => InlineNode::MonospaceText(crate::Monospace::from(node)), - InlineKind::Highlight(node) => InlineNode::HighlightText(crate::Highlight::from(node)), - InlineKind::Subscript(node) => InlineNode::SubscriptText(crate::Subscript::from(node)), - InlineKind::Superscript(node) => { - InlineNode::SuperscriptText(crate::Superscript::from(node)) - } - InlineKind::DoubleQuotedSpan(node) => { - InlineNode::DoubleQuotedSpan(crate::DoubleQuotedSpan::from(node)) - } - InlineKind::SingleQuotedSpan(node) => { - InlineNode::SingleQuotedSpan(crate::SingleQuotedSpan::from(node)) - } - InlineKind::StandaloneCurvedApostrophe(node) => InlineNode::StandaloneCurvedApostrophe( - crate::StandaloneCurvedApostrophe::from(node), - ), - InlineKind::LineBreak(node) => InlineNode::LineBreak(crate::LineBreak::from(node)), - InlineKind::Anchor(node) => InlineNode::InlineAnchor(crate::Anchor::from(node)), - InlineKind::Callout(node) => { - InlineNode::CalloutMarker(crate::CalloutMarker::from(node)) - } - InlineKind::Footnote(node) => { - InlineNode::Macro(InlineMacro::Footnote(crate::Footnote::from(node))) - } - InlineKind::Icon(node) => { - InlineNode::Macro(InlineMacro::Icon(Box::new(crate::Icon::from(node)))) - } - InlineKind::Image(node) => { - InlineNode::Macro(InlineMacro::Image(Box::new(crate::InlineImage::from(node)))) - } - InlineKind::KeyboardShortcut(node) => InlineNode::Macro(InlineMacro::KeyboardShortcut( - crate::KeyboardShortcut::from(node), - )), - InlineKind::Button(node) => { - InlineNode::Macro(InlineMacro::Button(crate::Button::from(node))) - } - InlineKind::MenuPath(node) => { - InlineNode::Macro(InlineMacro::MenuPath(crate::MenuPath::from(node))) - } - InlineKind::UrlMacro(node) => { - InlineNode::Macro(InlineMacro::UrlMacro(Box::new(crate::UrlMacro::from(node)))) - } - InlineKind::Link(node) => { - InlineNode::Macro(InlineMacro::Link(Box::new(crate::Link::from(node)))) - } - InlineKind::Mailto(node) => { - InlineNode::Macro(InlineMacro::Mailto(Box::new(crate::Mailto::from(node)))) - } - InlineKind::Autolink(node) => { - InlineNode::Macro(InlineMacro::Autolink(crate::Autolink::from(node))) - } - InlineKind::CrossReference(node) => InlineNode::Macro(InlineMacro::CrossReference( - Box::new(crate::CrossReference::from(node)), - )), - InlineKind::Passthrough(node) => { - InlineNode::Macro(InlineMacro::Passthrough(crate::Passthrough::from(node))) - } - InlineKind::Stem(node) => InlineNode::Macro(InlineMacro::Stem(crate::Stem::from(node))), - InlineKind::IndexTerm(node) => InlineNode::Macro(InlineMacro::IndexTerm(Box::new( - crate::IndexTerm::from(node), - ))), + match read.source { + InlineSource::Node(node) => node.clone(), + InlineSource::Macro(node) => Self::Macro(node.clone()), } } } diff --git a/acdc-parser/src/extensions/display.rs b/acdc-parser/src/extensions/display.rs index ad9676149..9e15f54c5 100644 --- a/acdc-parser/src/extensions/display.rs +++ b/acdc-parser/src/extensions/display.rs @@ -433,7 +433,8 @@ fn display_copy<'a>(nodes: &[InlineNode<'a>]) -> Vec> { } InlineNode::RawText(raw) } - InlineNode::PlainText(_) + InlineNode::Extension(_) + | InlineNode::PlainText(_) | InlineNode::Symbol(_) | InlineNode::CharacterReference(_) | InlineNode::VerbatimText(_) diff --git a/acdc-parser/src/extensions/display/prepared.rs b/acdc-parser/src/extensions/display/prepared.rs index ff5de232d..1256ee224 100644 --- a/acdc-parser/src/extensions/display/prepared.rs +++ b/acdc-parser/src/extensions/display/prepared.rs @@ -1,4 +1,4 @@ -use std::fmt; +use std::{collections::HashMap, fmt, sync::Arc}; use bumpalo::Bump; @@ -62,10 +62,38 @@ impl<'doc> PreparedDocument<'doc> { /// # Errors /// Rejects unfinalized requests or content that cannot be repaired. pub fn new( + source: DocumentRef<'doc>, + resolve: impl FnMut(GeneratedDisplayRef<'_>) -> DisplayLabel, + ) -> Result { + Self::prepare(source, resolve, None, |_, _| {}) + } + + /// Expand authored inline macros and symbolic references for one backend. + /// Instances, counters, warnings, and expanded label copies belong to this call. + /// + /// # Errors + /// Returns a located error if a processor fails or a display cannot be resolved. + pub fn with_inline_macros( + source: DocumentRef<'doc>, + resolve: impl FnMut(GeneratedDisplayRef<'_>) -> DisplayLabel, + registry: &crate::extensions::Registry, + backend: &str, + attributes: &crate::DocumentAttributes<'_>, + warn: impl FnMut(crate::SourceLocation, String), + ) -> Result { + let session = source.has_inline_macros().then(|| { + crate::extensions::late_inline::ConversionSession::new(registry, backend, attributes) + }); + Self::prepare(source, resolve, session, warn) + } + + fn prepare( source: DocumentRef<'doc>, mut resolve: impl FnMut(GeneratedDisplayRef<'_>) -> DisplayLabel, + mut session: Option>, + mut warn: impl FnMut(crate::SourceLocation, String), ) -> Result { - if !source.has_deferred_displays() { + if !source.has_deferred_displays() && session.is_none() { return Ok(Self { source, prepared: None, @@ -78,6 +106,7 @@ impl<'doc> PreparedDocument<'doc> { }, |owner| { let mut document = Document::from(owner.source); + let mut expanded: HashMap<_, InlineNode<'_>> = HashMap::new(); try_walk_document_inline_nodes_mut(&mut document, &mut |node| { if let InlineNode::Macro(InlineMacro::CrossReference(xref)) = node && let Some(display) = xref.generated_display.take() @@ -96,8 +125,30 @@ impl<'doc> PreparedDocument<'doc> { xref.text.push(plain("", &display.origin.location)); } } + if let InlineNode::Extension(call) = node + && let Some(session) = &mut session + { + // Catalogs and display labels clone an authored occurrence. Its + // processor and diagnostics run once even when several labels use it. + let key = Arc::as_ptr(&call.args); + let replacement = match expanded.entry(key) { + std::collections::hash_map::Entry::Occupied(saved) => { + saved.get().clone() + } + std::collections::hash_map::Entry::Vacant(slot) => { + let replacement = + session.expand(&owner.arena, source, call, &mut warn)?; + slot.insert(replacement.clone()); + replacement + } + }; + *node = replacement; + } Ok::<_, Error>(()) })?; + if session.is_some() { + document.has_inline_macros = false; + } document.generated_displays = DisplayState::default(); repair(&mut document)?; Ok::<_, Error>(document) diff --git a/acdc-parser/src/extensions/late_inline.rs b/acdc-parser/src/extensions/late_inline.rs new file mode 100644 index 000000000..e9ec6fd4e --- /dev/null +++ b/acdc-parser/src/extensions/late_inline.rs @@ -0,0 +1,236 @@ +//! Authored inline macros evaluated against one conversion's finalized document. + +use std::{collections::HashMap, sync::Arc}; + +use crate::{DocumentAttributes, SourceLocation, ast::DocumentRef}; + +/// Recognize an authored macro in text where macro substitution is enabled. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum InlineMatcher { + /// `name:target[body]`. + Full, + /// `name:[body]`. The bracket content supplies both target and body. + Short, + /// Literal delimiters around a body, for example `@(` and `)`. + Delimited { open: String, close: String }, +} + +/// Arguments and originating source span of one inline macro. +pub struct InlineInvocation<'a> { + /// Full-syntax target or short-syntax bracket content. Delimited calls have an empty target. + pub target: &'a str, + /// Body after the enabled attribute substitutions for this conversion. + pub body: &'a str, + /// Retained source spelling before conversion attribute substitution. + pub source_body: &'a str, + pub location: &'a SourceLocation, +} + +/// Values and services available to one conversion. +pub struct InlineConversionContext<'a> { + /// Name of the backend currently writing output. + pub backend: &'a str, + /// Finalized document after all tree processors have run. + pub document: DocumentRef<'a>, + /// Attributes configured by the backend performing this conversion. + attributes: &'a DocumentAttributes<'a>, + /// Document attributes at the authored invocation. + source_attributes: &'a DocumentAttributes<'a>, + pub(super) counters: &'a mut HashMap, + pub(super) warnings: &'a mut dyn FnMut(String), +} + +impl<'a> InlineConversionContext<'a> { + /// Look up a conversion override, then the value in effect at the call's + /// source position, then the backend default. Explicit unsets hide defaults. + #[must_use] + pub fn attribute(&self, name: &str) -> Option<&'a crate::DocumentAttributeValue<'a>> { + if let Some(assignment) = self.attributes.assignment(name) { + return assignment.value(); + } + if let Some(assignment) = self.source_attributes.assignment(name) { + return assignment.value(); + } + self.attributes + .get(name) + .or_else(|| self.source_attributes.get(name)) + } + + /// Increment a conversion-local named counter, starting at one. + pub fn increment(&mut self, name: &str) -> usize { + if let Some(value) = self.counters.get_mut(name) { + *value += 1; + *value + } else { + self.counters.insert(name.to_owned(), 1); + 1 + } + } + + /// Emit a non-fatal diagnostic at this invocation. + pub fn warn(&mut self, message: impl Into) { + (self.warnings)(message.into()); + } +} + +/// Prepared inline output. Text is literal and uses ordinary backend escaping. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum InlineMacroOutput { + Text(String), + Strong(String), + Emphasis(String), + LineBreak, +} + +/// A processor instance belongs to one conversion and is created on first use. +pub trait InlineMacroProcessor { + /// # Errors + /// Returning an error stops preparation before output is written. + fn process( + &mut self, + call: &InlineInvocation<'_>, + ctx: &mut InlineConversionContext<'_>, + ) -> Result; +} + +impl InlineMacroProcessor for F +where + F: FnMut( + &InlineInvocation<'_>, + &mut InlineConversionContext<'_>, + ) -> Result, +{ + fn process( + &mut self, + call: &InlineInvocation<'_>, + context: &mut InlineConversionContext<'_>, + ) -> Result { + self(call, context) + } +} + +#[derive(Clone, Debug)] +pub(crate) struct Registration { + pub(super) handler: super::registry::ProcessorFactory, + pub(crate) matcher: InlineMatcher, + pub(crate) prefix: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Arguments<'a> { + pub(crate) substitute_attributes: bool, + pub(crate) file: Option, + pub(crate) name: String, + pub(crate) target: &'a str, + pub(crate) body: &'a str, + pub(crate) attributes: Arc>, +} + +/// Retained spelling of an authored inline invocation before conversion. +#[derive(Clone, Debug, PartialEq)] +pub struct RetainedInline<'a> { + pub(crate) literal: crate::Plain<'a>, + pub(crate) args: Arc>, +} + +impl Registration { + pub(crate) fn name(&self) -> &str { + &self.handler.name + } +} + +pub(super) struct ConversionSession<'a> { + registry: &'a super::Registry, + backend: &'a str, + attributes: &'a DocumentAttributes<'a>, + processors: HashMap>, + counters: HashMap, +} + +impl<'a> ConversionSession<'a> { + pub(super) fn new( + registry: &'a super::Registry, + backend: &'a str, + attributes: &'a DocumentAttributes<'a>, + ) -> Self { + Self { + registry, + backend, + attributes, + processors: HashMap::new(), + counters: HashMap::new(), + } + } + + pub(super) fn expand<'doc>( + &mut self, + arena: &'doc bumpalo::Bump, + document: DocumentRef<'_>, + call: &RetainedInline<'doc>, + warn: &mut impl FnMut(crate::SourceLocation, String), + ) -> Result, crate::Error> { + use crate::{Bold, FormattingForm, InlineNode, Italic, LineBreak}; + let location = &call.literal.location; + let args = &call.args; + let origin = SourceLocation::at_location(args.file.clone(), location.clone()); + let Some((index, entry)) = self.registry.inline_registration(&args.name) else { + return Ok(InlineNode::PlainText(call.literal.clone())); + }; + let processor = self + .processors + .entry(index) + .or_insert_with(|| (entry.handler.factory)()); + let mut warnings = |message| warn(origin.clone(), message); + let mut context = InlineConversionContext { + backend: self.backend, + document, + attributes: self.attributes, + source_attributes: &args.attributes, + counters: &mut self.counters, + warnings: &mut warnings, + }; + let substitute = |text| { + if args.substitute_attributes { + crate::model::substitution::substitute_attributes( + text, + args.attributes.reference_mode(), + |name| context.attribute(name), + ) + } else { + std::borrow::Cow::Borrowed(text) + } + }; + let target = substitute(args.target); + let body = substitute(args.body); + let output = processor + .process( + &InlineInvocation { + target: &target, + body: &body, + source_body: args.body, + location: &origin, + }, + &mut context, + ) + .map_err(|message| { + crate::Error::Extension(Box::new(origin), format!("{}: {message}", args.name)) + })?; + let text = |s: String| super::inline::plain(arena.alloc_str(&s), location); + Ok(match output { + InlineMacroOutput::Text(s) => text(s), + InlineMacroOutput::Strong(s) => InlineNode::BoldText(Bold::new( + vec![text(s)], + FormattingForm::Constrained, + location.clone(), + )), + InlineMacroOutput::Emphasis(s) => InlineNode::ItalicText(Italic::new( + vec![text(s)], + FormattingForm::Constrained, + location.clone(), + )), + InlineMacroOutput::LineBreak => InlineNode::LineBreak(LineBreak::new(location.clone())), + }) + } +} diff --git a/acdc-parser/src/extensions/mod.rs b/acdc-parser/src/extensions/mod.rs index 2146e654b..f733f4307 100644 --- a/acdc-parser/src/extensions/mod.rs +++ b/acdc-parser/src/extensions/mod.rs @@ -201,6 +201,7 @@ mod display; mod editor; pub(crate) mod finalization; mod inline; +pub(crate) mod late_inline; mod query; mod recognition; mod registry; @@ -228,6 +229,10 @@ pub use display::{ pub(crate) use display::{DisplayState, GeneratedDisplay}; pub use editor::DocumentEditor; pub use inline::InlineSpec; +pub use late_inline::{ + InlineConversionContext, InlineInvocation, InlineMacroOutput, InlineMacroProcessor, + InlineMatcher, RetainedInline, +}; pub use query::{BlockContext, BlockView, DocumentQuery}; pub(crate) use registry::ReferenceNormalizer; pub use registry::{RegistrationError, Registry, RegistryBuilder}; diff --git a/acdc-parser/src/extensions/registry.rs b/acdc-parser/src/extensions/registry.rs index 6b7b35088..158ce9e6f 100644 --- a/acdc-parser/src/extensions/registry.rs +++ b/acdc-parser/src/extensions/registry.rs @@ -4,7 +4,8 @@ use crate::{Error, Options, ParseResult}; use super::{ BlockMacro, BlockStyle, DocumentEditor, ExtensionParseResult, IncludeProcessor, - IncludeProcessors, RawBlockContext, Session, SourcePreprocessor, TreeProcessorRegistration, + IncludeProcessors, InlineMacroProcessor, InlineMatcher, RawBlockContext, Session, + SourcePreprocessor, TreeProcessorRegistration, late_inline::Registration, }; pub(super) struct ProcessorFactory { @@ -50,6 +51,10 @@ pub enum RegistrationError { DuplicatePreprocessor(String), #[error("reference normalizer is already registered: {0}")] DuplicateReferenceNormalizer(String), + #[error("inline macro is already registered: {0}")] + DuplicateInlineMacro(String), + #[error("inline macro delimiters must be nonempty")] + EmptyInlineDelimiter, #[error("include processor is already registered: {0}")] DuplicateIncludeProcessor(String), #[error("deferred processor already registered for block macro: {0}")] @@ -66,6 +71,7 @@ pub struct RegistryBuilder { preprocessors: Vec>, includes: Vec>, normalizers: Vec>, + inlines: Vec, } impl RegistryBuilder { @@ -106,6 +112,10 @@ impl RegistryBuilder { RegistrationError::DuplicateReferenceNormalizer, )?; } + for registration in ®istry.0.inlines { + self.check_inline_name(®istration.handler.name)?; + } + self.inlines.extend_from_slice(®istry.0.inlines); self.normalizers.extend_from_slice(®istry.0.normalizers); self.preprocessors .extend_from_slice(®istry.0.preprocessors); @@ -125,6 +135,64 @@ impl RegistryBuilder { Ok(self) } + fn check_inline_name(&self, name: &str) -> Result<(), RegistrationError> { + validate_identifier(name)?; + if self.inlines.iter().any(|r| r.handler.name == name) { + return Err(RegistrationError::DuplicateInlineMacro(name.to_owned())); + } + Ok(()) + } + + /// Register a conversion-time inline macro and its instance factory. + /// The parser retains matching calls in macro-enabled spans. Conversion + /// creates the processor after tree edits, on its first surviving call. + /// For overlapping custom delimiters, the first matching registration wins. + /// + /// ``` + /// use acdc_parser::extensions::{ + /// InlineConversionContext, InlineInvocation, InlineMacroOutput, InlineMatcher, Registry, + /// }; + /// + /// let mut builder = Registry::builder(); + /// builder.register_inline_macro("step", InlineMatcher::Short, || { + /// |call: &InlineInvocation<'_>, ctx: &mut InlineConversionContext<'_>| { + /// let number = ctx.increment("steps"); + /// Ok(InlineMacroOutput::Strong(format!("{number}. {}", call.body))) + /// } + /// })?; + /// # Ok::<(), Box>(()) + /// ``` + /// + /// # Errors + /// Rejects duplicate or invalid names and empty custom delimiters. + pub fn register_inline_macro( + &mut self, + name: impl Into, + matcher: InlineMatcher, + factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Result<&mut Self, RegistrationError> { + let name = name.into(); + self.check_inline_name(&name)?; + let prefix = match &matcher { + InlineMatcher::Full | InlineMatcher::Short => format!("{name}:"), + InlineMatcher::Delimited { open, close } => { + if open.is_empty() || close.is_empty() { + return Err(RegistrationError::EmptyInlineDelimiter); + } + open.clone() + } + }; + self.inlines.push(Registration { + matcher, + prefix, + handler: ProcessorFactory { + name, + factory: Arc::new(move || Box::new(factory())), + }, + }); + Ok(self) + } + /// Register a style for the selected raw delimited block contexts. /// Each document gets a fresh processor. Style names are independent of macro names. /// @@ -307,7 +375,17 @@ impl RegistryBuilder { #[must_use] pub fn build(self) -> Registry { + let mut inline_names = HashMap::new(); + let mut custom_inlines = Vec::new(); + for (index, entry) in self.inlines.iter().enumerate() { + if matches!(entry.matcher, InlineMatcher::Delimited { .. }) { + custom_inlines.push(index); + } + inline_names.insert(entry.name().to_owned(), index); + } Registry(Arc::new(RegistryData { + inline_names, + custom_inlines, styles: self.styles, macros: self.macros, names: self.names, @@ -315,6 +393,7 @@ impl RegistryBuilder { preprocessors: self.preprocessors, includes: self.includes, normalizers: self.normalizers, + inlines: self.inlines, })) } } @@ -354,6 +433,8 @@ fn validate_identifier(name: &str) -> Result<(), RegistrationError> { #[derive(Debug, Default)] struct RegistryData { + inline_names: HashMap, + custom_inlines: Vec, styles: Vec, macros: Vec, names: HashMap, @@ -361,6 +442,7 @@ struct RegistryData { preprocessors: Vec>, includes: Vec>, normalizers: Vec>, + inlines: Vec, } /// A cheap-to-clone, immutable collection of extension factories. @@ -375,7 +457,32 @@ impl Registry { #[must_use] pub fn is_empty(&self) -> bool { - !self.has_input_processors() && self.0.trees.is_empty() && self.0.normalizers.is_empty() + !self.has_input_processors() + && self.0.trees.is_empty() + && self.0.normalizers.is_empty() + && self.0.inlines.is_empty() + } + + pub(crate) fn inline_macros(&self) -> &[Registration] { + &self.0.inlines + } + + pub(crate) fn named_inline(&self, name: &str) -> Option { + self.inline_registration(name).and_then(|(index, entry)| { + (!matches!(entry.matcher, InlineMatcher::Delimited { .. })).then_some(index) + }) + } + + pub(crate) fn inline_registration(&self, name: &str) -> Option<(usize, &Registration)> { + let index = *self.0.inline_names.get(name)?; + Some((index, self.0.inlines.get(index)?)) + } + + pub(crate) fn custom_inlines(&self) -> impl Iterator { + self.0 + .custom_inlines + .iter() + .filter_map(|&i| self.0.inlines.get(i).map(|r| (i, r))) } fn has_input_processors(&self) -> bool { diff --git a/acdc-parser/src/grammar/document/finish.rs b/acdc-parser/src/grammar/document/finish.rs index 86df06314..f94dcf1c9 100644 --- a/acdc-parser/src/grammar/document/finish.rs +++ b/acdc-parser/src/grammar/document/finish.rs @@ -46,6 +46,7 @@ pub(super) fn finish<'a>( natural_targets: HashMap::new(), }; let mut document = Document { + has_inline_macros: state.retained_inline.as_ref().is_some_and(|v| v.get()), generated_displays: crate::extensions::DisplayState::default(), header, untitled_header_location, diff --git a/acdc-parser/src/grammar/document/manpage.rs b/acdc-parser/src/grammar/document/manpage.rs index 0ba0cfa84..e8d67a9be 100644 --- a/acdc-parser/src/grammar/document/manpage.rs +++ b/acdc-parser/src/grammar/document/manpage.rs @@ -136,6 +136,7 @@ fn extract_plain_text(nodes: &[InlineNode]) -> String { let mut result = String::new(); for node in nodes { match node { + InlineNode::Extension(call) => result.push_str(call.literal.content), InlineNode::PlainText(text) => result.push_str(text.content), InlineNode::Symbol(symbol) => result.push_str(symbol.kind.text()), InlineNode::CharacterReference(reference) => { diff --git a/acdc-parser/src/grammar/document/table.rs b/acdc-parser/src/grammar/document/table.rs index e0adaac03..c9351734a 100644 --- a/acdc-parser/src/grammar/document/table.rs +++ b/acdc-parser/src/grammar/document/table.rs @@ -658,7 +658,8 @@ fn simple_cell_nodes(nodes: &[InlineNode<'_>]) -> bool { InlineNode::BoldText(text) => text.id.is_none() && simple_cell_nodes(&text.content), InlineNode::ItalicText(text) => text.id.is_none() && simple_cell_nodes(&text.content), InlineNode::MonospaceText(text) => text.id.is_none() && simple_cell_nodes(&text.content), - InlineNode::Symbol(_) + InlineNode::Extension(_) + | InlineNode::Symbol(_) | InlineNode::CharacterReference(_) | InlineNode::RawText(_) | InlineNode::VerbatimText(_) diff --git a/acdc-parser/src/grammar/footnotes.rs b/acdc-parser/src/grammar/footnotes.rs index 66e6f9dce..9ffc8a73b 100644 --- a/acdc-parser/src/grammar/footnotes.rs +++ b/acdc-parser/src/grammar/footnotes.rs @@ -406,6 +406,7 @@ impl Document<'_> { } pub(crate) fn commit_repair(&mut self, mut candidate: Self) { + candidate.has_inline_macros = self.has_inline_macros; candidate.generated_displays = std::mem::take(&mut self.generated_displays); *self = candidate; } diff --git a/acdc-parser/src/grammar/inline_processing.rs b/acdc-parser/src/grammar/inline_processing.rs index a80b1d133..079311a40 100644 --- a/acdc-parser/src/grammar/inline_processing.rs +++ b/acdc-parser/src/grammar/inline_processing.rs @@ -406,6 +406,11 @@ fn parse_processed_inlines<'a>( byte.is_ascii_alphanumeric() || matches!(byte, b' ' | b',' | b';' | b'.' | b'!' | b'?') }) && !text.contains("...") + && !state + .options + .extensions + .as_ref() + .is_some_and(|r| r.custom_inlines().any(|(_, m)| text.contains(&m.prefix))) { return Ok(vec![InlineNode::PlainText(Plain { content: text, @@ -496,15 +501,7 @@ fn parse_inline_syntax<'a>( inline_peg_state.late_attribute_sources = late_attribute_sources(processed, state, location); } - let inlines = if verbatim { - inline_parser::verbatim_inlines(text, &mut inline_peg_state) - } else if !autolinks { - inline_parser::inlines_no_autolinks(text, &mut inline_peg_state) - } else if inline_peg_state.quotes_only { - inline_parser::quotes_only_inlines(text, &mut inline_peg_state) - } else { - inline_parser::inlines(text, &mut inline_peg_state) - }; + let inlines = parse_inline_nodes(&mut inline_peg_state, text, verbatim, autolinks); let warnings = inline_peg_state.take_inline_warnings(); let mut inlines = inlines @@ -544,6 +541,29 @@ fn parse_inline_syntax<'a>( Ok(inlines) } +fn parse_inline_nodes<'a>( + inline_peg_state: &mut ParserState<'a>, + text: &'a str, + verbatim: bool, + autolinks: bool, +) -> Result>, peg::error::ParseError> { + if inline_peg_state.retained_inline.is_some() { + inline_peg_state.inline_candidates = + super::inlines::extensions::candidates(inline_peg_state); + } + if inline_peg_state.inline_candidates.is_some() { + inline_parser::extension_inlines(text, inline_peg_state, verbatim) + } else if verbatim { + inline_parser::verbatim_inlines(text, inline_peg_state) + } else if !autolinks { + inline_parser::inlines_no_autolinks(text, inline_peg_state) + } else if inline_peg_state.quotes_only { + inline_parser::quotes_only_inlines(text, inline_peg_state) + } else { + inline_parser::inlines(text, inline_peg_state) + } +} + fn late_attribute_sources<'a>( processed: &ProcessedContent<'a>, state: &ParserState<'a>, diff --git a/acdc-parser/src/grammar/inlines.rs b/acdc-parser/src/grammar/inlines.rs index 0ad2c7ddd..486f5246a 100644 --- a/acdc-parser/src/grammar/inlines.rs +++ b/acdc-parser/src/grammar/inlines.rs @@ -1,6 +1,7 @@ //! Inline grammar and its supporting modules. mod attributes; +pub(super) mod extensions; mod index_terms; mod links; mod peg; diff --git a/acdc-parser/src/grammar/inlines/extensions.rs b/acdc-parser/src/grammar/inlines/extensions.rs new file mode 100644 index 000000000..3aa94b125 --- /dev/null +++ b/acdc-parser/src/grammar/inlines/extensions.rs @@ -0,0 +1,198 @@ +//! Candidate offsets keep registration lookup out of the character scanner. +//! Only the inline grammar can commit a candidate at an eligible node boundary. + +use std::{cell::Cell, sync::Arc}; + +use crate::{ + InlineNode, Plain, Substitution, + extensions::{InlineMatcher, RetainedInline, late_inline::Arguments}, + grammar::{ParserState, brackets::escaped_bracket_end}, +}; + +#[derive(Debug)] +struct Candidate { + start: usize, + prefix: usize, + registration: usize, +} + +#[derive(Debug)] +pub(in crate::grammar) struct Candidates<'a> { + offsets: Vec, + plain_end: Cell, + attributes: Arc>, +} + +pub(in crate::grammar) fn candidates<'a>(state: &ParserState<'a>) -> Option>> { + let mut found = Vec::new(); + if !state + .inline_ctx + .substitutions + .enabled(&Substitution::Macros) + || state.quotes_only + { + return None; + } + let Some(registry) = &state.options.extensions else { + return None; + }; + let input = state.input; + let mut record = |prefix: usize, registration| { + let start = prefix - usize::from(input[..prefix].ends_with('\\')); + found.push(Candidate { + start, + prefix, + registration, + }); + }; + for (colon, _) in input.match_indices(':') { + let name_start = input[..colon] + .trim_end_matches(|c: char| c.is_ascii_alphanumeric() || matches!(c, '_' | '-')) + .len(); + if let Some(registration) = registry.named_inline(&input[name_start..colon]) { + record(name_start, registration); + } + } + for (registration, entry) in registry.custom_inlines() { + for (prefix, _) in input.match_indices(&entry.prefix) { + record(prefix, registration); + } + } + found.sort_by_key(|c| (c.start, c.registration)); + (!found.is_empty()).then(|| { + Box::new(Candidates { + offsets: found, + plain_end: Cell::new(0), + attributes: Arc::new((*state.document_attributes).clone()), + }) + }) +} + +/// Split one complete invocation at an eligible grammar position. +pub(in crate::grammar) fn arguments<'a>( + entry: &crate::extensions::late_inline::Registration, + source: &'a str, +) -> Option<(&'a str, &'a str, usize)> { + let tail = source.strip_prefix(&entry.prefix)?; + let (target, body, end) = match &entry.matcher { + InlineMatcher::Delimited { close, .. } => { + let end = tail.find(close)?; + ("", &tail[..end], end + close.len()) + } + InlineMatcher::Full | InlineMatcher::Short => { + if tail.starts_with(':') { + return None; + } + let open = tail.find(|c: char| c == '[' || c.is_whitespace())?; + if tail.as_bytes().get(open) != Some(&b'[') + || (open == 0) != (entry.matcher == InlineMatcher::Short) + { + return None; + } + let end = escaped_bracket_end(tail, open + 1)?; + { + let body = &tail[open + 1..end]; + (if open == 0 { body } else { &tail[..open] }, body, end + 1) + } + } + }; + Some((target, body, end + entry.prefix.len())) +} + +pub(super) fn recognize<'a>( + state: &ParserState<'a>, + start: usize, +) -> peg::RuleResult> { + let Some(registry) = &state.options.extensions else { + return peg::RuleResult::Failed; + }; + let Some(candidates) = &state.inline_candidates else { + return peg::RuleResult::Failed; + }; + let index = candidates.offsets.partition_point(|c| c.start < start); + for candidate in candidates + .offsets + .iter() + .skip(index) + .take_while(|c| c.start == start) + { + let Some(entry) = registry.inline_macros().get(candidate.registration) else { + continue; + }; + if !super::recognition::macro_token_allowed(state, candidate.prefix, entry.prefix.len()) { + continue; + } + let Some((target, body, len)) = arguments(entry, &state.input[candidate.prefix..]) else { + continue; + }; + let end = candidate.prefix + len; + let literal = Plain::new( + &state.input[candidate.prefix..end], + state.create_block_location(start, end, state.inline_ctx.offset), + ) + .with_escaped(true); + let node = if candidate.prefix == start { + if let Some(retained) = &state.retained_inline { + retained.set(true); + } + InlineNode::Extension(Box::new(RetainedInline { + literal, + args: Arc::new(Arguments { + file: state.current_file.as_deref().cloned(), + name: entry.name().to_owned(), + target, + body, + substitute_attributes: state + .inline_ctx + .substitutions + .enabled(&Substitution::Attributes), + attributes: Arc::clone(&candidates.attributes), + }), + })) + } else { + InlineNode::PlainText(literal) + }; + return peg::RuleResult::Matched(end, node); + } + // Reuse the remainder of an already scanned plain run between calls. + let limit = candidates.plain_end.get(); + if start < limit { + let next = candidates.offsets.partition_point(|c| c.start <= start); + let end = candidates + .offsets + .get(next) + .map_or(limit, |c| limit.min(c.start)); + return peg::RuleResult::Matched( + end, + InlineNode::PlainText(Plain::new( + &state.input[start..end], + state.create_block_location(start, end, state.inline_ctx.offset), + )), + ); + } + peg::RuleResult::Failed +} + +/// An ordinary text run can cross a registered prefix. Leave the suffix to PEG; +/// formatted spans and built-in macros keep ownership of their entire match. +pub(super) fn clip<'a>( + state: &ParserState<'a>, + start: usize, + end: usize, + node: InlineNode<'a>, +) -> peg::RuleResult> { + if let Some(candidates) = &state.inline_candidates + && matches!(&node, InlineNode::PlainText(plain) if !plain.escaped && state.input.get(start..end).is_some_and(|source| std::ptr::eq(plain.content,source))) + { + let index = candidates.offsets.partition_point(|c| c.start <= start); + if let Some(call) = candidates.offsets.get(index).filter(|c| c.start < end) { + candidates.plain_end.set(end); + let location = state.create_block_location(start, call.start, state.inline_ctx.offset); + return peg::RuleResult::Matched( + call.start, + InlineNode::PlainText(Plain::new(&state.input[start..call.start], location)), + ); + } + } + peg::RuleResult::Matched(end, node) +} diff --git a/acdc-parser/src/grammar/inlines/peg.rs b/acdc-parser/src/grammar/inlines/peg.rs index 08d781c90..36b6657a4 100644 --- a/acdc-parser/src/grammar/inlines/peg.rs +++ b/acdc-parser/src/grammar/inlines/peg.rs @@ -78,6 +78,26 @@ peg::parser! { node } + pub(in crate::grammar) rule extension_inlines(verbatim: bool) -> Vec> + = check_attribute_profiles() chunks:(profiled_attribute() / nodes:registered_inline(verbatim)+ { nodes })+ {? expand_escaped_index_terms(chunks.into_iter().flatten().collect(), state) } + / nodes:registered_inline(verbatim)+ {? expand_escaped_index_terms(nodes, state) } + + rule registered_inline(verbatim: bool) -> InlineNode<'input> + = node:extension_inline() { + record_url_boundary(state, &node, span_end, &Substitution::Quotes); + node + } + / start:position!() node:(({? verbatim.then_some(()).ok_or("prose") }) n:verbatim_inline() { n } / normal_inline()) clipped:clip_extension(start, node) { + record_url_boundary(state, &clipped, span_end, &Substitution::Quotes); + clipped + } + + rule extension_inline() -> InlineNode<'input> + = #{|_, pos| crate::grammar::inlines::extensions::recognize(state, pos)} + + rule clip_extension(start: usize, node: InlineNode<'input>) -> InlineNode<'input> + = #{|_, end| crate::grammar::inlines::extensions::clip(state, start, end, node)} + rule check_passthrough_attributes() = {? (state.options.compatibility_mode == crate::CompatibilityMode::Asciidoctor && !state.attribute_passthroughs.is_empty()).then_some(()).ok_or("literal passthrough prefix") } rule attributed_passthrough_index(start: usize) -> usize diff --git a/acdc-parser/src/grammar/inlines/typography/neighbors.rs b/acdc-parser/src/grammar/inlines/typography/neighbors.rs index 2120f8cba..9e72b386d 100644 --- a/acdc-parser/src/grammar/inlines/typography/neighbors.rs +++ b/acdc-parser/src/grammar/inlines/typography/neighbors.rs @@ -74,6 +74,9 @@ impl Edge { fn edge(node: &InlineNode<'_>, first: bool, state: &ParserState<'_>) -> Edge { match node { + InlineNode::Extension(call) => { + text_edge(call.literal.content, &call.literal.location, first, state) + } InlineNode::PlainText(text) => text_edge(text.content, &text.location, first, state), InlineNode::RawText(raw) => text_edge(raw.content, &raw.location, first, state), InlineNode::Symbol(symbol) => { diff --git a/acdc-parser/src/grammar/location_mapping.rs b/acdc-parser/src/grammar/location_mapping.rs index 7f13448c6..86ffb7263 100644 --- a/acdc-parser/src/grammar/location_mapping.rs +++ b/acdc-parser/src/grammar/location_mapping.rs @@ -61,6 +61,30 @@ impl<'a> LocationMappingContext<'_, 'a> { }) } + fn map_extension(&self, call: &mut crate::extensions::RetainedInline<'a>) -> Result<(), Error> { + let location = self.map_location(&call.literal.location)?; + let args = std::sync::Arc::make_mut(&mut call.args); + args.file = self + .state + .create_error_source_location(location.clone()) + .file; + if let Some(entry) = self + .state + .options + .extensions + .as_ref() + .and_then(|r| r.inline_registration(&args.name).map(|(_, entry)| entry)) + && let Some(source) = self.state.source_tail(location.absolute_start) + && let Some((target, body, len)) = super::inlines::extensions::arguments(entry, source) + { + args.target = target; + args.body = body; + call.literal.content = &source[..len]; + } + call.literal.location = location; + Ok(()) + } + fn map_symbol_location(&self, loc: &Location) -> Result { let mapped = self.map_location(loc)?; let start = self @@ -159,6 +183,9 @@ pub(super) fn map_inner_content_locations<'a>( ) -> Result>, Error> { let mapped = map_nodes(content, |node| { match node { + InlineNode::Extension(call) => { + ctx.map_extension(call)?; + } InlineNode::PlainText(plain) => { let expanded = map_plain_text_inline_locations(plain, ctx)?; if expanded.is_none() { @@ -292,6 +319,9 @@ fn map_locations<'a>( let mapped = map_nodes(content, |inline| { match inline { + InlineNode::Extension(call) => { + ctx.map_extension(call)?; + } InlineNode::PlainText(plain) => { return map_plain_text_inline_locations(plain, &ctx); } diff --git a/acdc-parser/src/grammar/location_walk.rs b/acdc-parser/src/grammar/location_walk.rs index 332e468ec..a9ef1ffb2 100644 --- a/acdc-parser/src/grammar/location_walk.rs +++ b/acdc-parser/src/grammar/location_walk.rs @@ -547,7 +547,8 @@ where (self.visit_location)(&mut id.location)?; } } - InlineNode::PlainText(_) + InlineNode::Extension(_) + | InlineNode::PlainText(_) | InlineNode::VerbatimText(_) | InlineNode::StandaloneCurvedApostrophe(_) | InlineNode::Symbol(_) diff --git a/acdc-parser/src/grammar/marked_text.rs b/acdc-parser/src/grammar/marked_text.rs index cea6036e5..6e924ba71 100644 --- a/acdc-parser/src/grammar/marked_text.rs +++ b/acdc-parser/src/grammar/marked_text.rs @@ -119,6 +119,7 @@ pub(super) fn map_marked_text_locations<'a>( InlineNode::DoubleQuotedSpan(node) => node.map_locations(ctx), InlineNode::SingleQuotedSpan(node) => node.map_locations(ctx), InlineNode::RawText(_) + | InlineNode::Extension(_) | InlineNode::PlainText(_) | InlineNode::VerbatimText(_) | InlineNode::LineBreak(_) diff --git a/acdc-parser/src/grammar/passthrough_processing.rs b/acdc-parser/src/grammar/passthrough_processing.rs index 3456d4e53..f03c9e2c3 100644 --- a/acdc-parser/src/grammar/passthrough_processing.rs +++ b/acdc-parser/src/grammar/passthrough_processing.rs @@ -1007,7 +1007,8 @@ fn process_inline_children<'a>( | InlineMacro::Stem(_) => {} } } - InlineNode::PlainText(_) + InlineNode::Extension(_) + | InlineNode::PlainText(_) | InlineNode::RawText(_) | InlineNode::VerbatimText(_) | InlineNode::StandaloneCurvedApostrophe(_) @@ -1536,7 +1537,8 @@ fn for_each_inline_children<'a>( | InlineMacro::Stem(_) => {} } } - InlineNode::PlainText(_) + InlineNode::Extension(_) + | InlineNode::PlainText(_) | InlineNode::RawText(_) | InlineNode::VerbatimText(_) | InlineNode::StandaloneCurvedApostrophe(_) diff --git a/acdc-parser/src/grammar/reference_walk.rs b/acdc-parser/src/grammar/reference_walk.rs index 6fde282f4..86dee6d4e 100644 --- a/acdc-parser/src/grammar/reference_walk.rs +++ b/acdc-parser/src/grammar/reference_walk.rs @@ -291,7 +291,8 @@ pub(crate) fn inlines<'a, V: ReferenceVisitor<'a>>( visitor.untitled(id.id, &node.location)?; } } - InlineNode::PlainText(_) + InlineNode::Extension(_) + | InlineNode::PlainText(_) | InlineNode::VerbatimText(_) | InlineNode::StandaloneCurvedApostrophe(_) | InlineNode::Symbol(_) diff --git a/acdc-parser/src/grammar/state.rs b/acdc-parser/src/grammar/state.rs index 165258d05..b8d9d60d2 100644 --- a/acdc-parser/src/grammar/state.rs +++ b/acdc-parser/src/grammar/state.rs @@ -90,6 +90,8 @@ pub(crate) struct ParserState<'a> { /// Original references for index labels and code boundaries checked before attributes. pub(super) late_attribute_sources: Vec<(Range, &'a str)>, /// Boundary left by the last completed inline node in this parse. + pub(super) inline_candidates: Option>>, + pub(super) retained_inline: Option>>, pub(super) last_url_boundary: Option, pub(crate) line_map: Rc, /// Parse options, shared via `Rc` so the per-inline-parse @@ -861,12 +863,18 @@ impl<'a> ParserState<'a> { body_reftext_source: None, untitled_header_entries: None, document_attributes: Rc::new(options.document_attributes.clone()), + retained_inline: options + .extensions + .as_ref() + .filter(|r| !r.inline_macros().is_empty()) + .map(|_| Rc::default()), options, nested_parent_attributes: None, hardbreaks: false, empty_attribute_offsets: Vec::new(), attribute_value_ranges: Vec::new(), late_attribute_sources: Vec::new(), + inline_candidates: None, last_url_boundary: None, line_map, input, @@ -916,6 +924,7 @@ impl<'a> ParserState<'a> { ..Options::default() }); Self { + retained_inline: None, options: Rc::new(EMPTY_OPTIONS.clone()), attribute_sources: Rc::default(), reference_text_sources: Rc::default(), @@ -929,6 +938,7 @@ impl<'a> ParserState<'a> { empty_attribute_offsets: Vec::new(), attribute_value_ranges: Vec::new(), late_attribute_sources: Vec::new(), + inline_candidates: None, last_url_boundary: None, line_map: Rc::new(LineMap::new(input)), input, @@ -974,6 +984,7 @@ impl<'a> ParserState<'a> { inline_ctx: InlineContext, ) -> Self { Self { + retained_inline: parent.retained_inline.clone(), options: parent.options.clone(), attribute_sources: Rc::clone(&parent.attribute_sources), reference_text_sources: Rc::clone(&parent.reference_text_sources), @@ -987,6 +998,7 @@ impl<'a> ParserState<'a> { empty_attribute_offsets: Vec::new(), attribute_value_ranges: Vec::new(), late_attribute_sources: Vec::new(), + inline_candidates: None, last_url_boundary: None, line_map: if std::ptr::eq(input, parent.input) { Rc::clone(&parent.line_map) diff --git a/acdc-parser/src/model/inlines/mod.rs b/acdc-parser/src/model/inlines/mod.rs index 82cc10c40..4a8e78f75 100644 --- a/acdc-parser/src/model/inlines/mod.rs +++ b/acdc-parser/src/model/inlines/mod.rs @@ -30,6 +30,8 @@ use crate::{Anchor, InlineImage, Location}; pub enum InlineNode<'a> { /// Ordinary text that inherits substitutions from its enclosing block. PlainText(Plain<'a>), + /// Authored macro spelling retained for conversion. + Extension(Box>), /// Resolved typography that requires no further language interpretation. Symbol(Symbol), CharacterReference(CharacterReference<'a>), @@ -59,6 +61,7 @@ impl InlineNode<'_> { pub fn location(&self) -> &Location { match self { InlineNode::PlainText(t) => &t.location, + Self::Extension(call) => &call.literal.location, InlineNode::Symbol(t) => &t.location, InlineNode::CharacterReference(t) => &t.location, InlineNode::RawText(t) => &t.location, @@ -86,6 +89,7 @@ impl InlineNode<'_> { pub(crate) fn location_mut(&mut self) -> &mut Location { match self { InlineNode::PlainText(t) => &mut t.location, + Self::Extension(call) => &mut call.literal.location, InlineNode::Symbol(t) => &mut t.location, InlineNode::CharacterReference(t) => &mut t.location, InlineNode::RawText(t) => &mut t.location, @@ -259,6 +263,12 @@ impl Serialize for InlineNode<'_> { let mut map = serializer.serialize_map(None)?; match self { + InlineNode::Extension(call) => { + map.serialize_entry("name", "text")?; + map.serialize_entry("type", "string")?; + map.serialize_entry("value", &call.literal.content)?; + map.serialize_entry("location", &call.literal.location)?; + } InlineNode::PlainText(plain) => { map.serialize_entry("name", "text")?; map.serialize_entry("type", "string")?; diff --git a/acdc-parser/src/model/mod.rs b/acdc-parser/src/model/mod.rs index 08657f824..ead64bf14 100644 --- a/acdc-parser/src/model/mod.rs +++ b/acdc-parser/src/model/mod.rs @@ -79,6 +79,7 @@ pub use token_assignment::TokenAssignment; #[derive(Default, Debug, PartialEq)] #[non_exhaustive] pub struct Document<'a> { + pub(crate) has_inline_macros: bool, pub(crate) generated_displays: crate::extensions::DisplayState<'a>, pub(crate) header: Option>, /// Span of the leading attribute entries and comments of a document diff --git a/acdc-parser/src/model/section.rs b/acdc-parser/src/model/section.rs index 2d840a891..a217b0c01 100644 --- a/acdc-parser/src/model/section.rs +++ b/acdc-parser/src/model/section.rs @@ -1071,6 +1071,7 @@ impl<'a> Section<'a> { fn append_id_from_inlines(inlines: &[InlineNode<'a>], append: &mut impl FnMut(&str)) { for node in inlines { match node { + InlineNode::Extension(call) => append(call.literal.content), InlineNode::PlainText(text) => { append(text.content); } diff --git a/acdc-parser/src/proptests/invariants.rs b/acdc-parser/src/proptests/invariants.rs index b6323c798..3fe99069d 100644 --- a/acdc-parser/src/proptests/invariants.rs +++ b/acdc-parser/src/proptests/invariants.rs @@ -411,7 +411,8 @@ fn walk_inline_locations(inline: &InlineNode, visitor: &mut impl FnMut(&Location } } // Leaf inlines: no children to recurse into - InlineNode::PlainText(_) + InlineNode::Extension(_) + | InlineNode::PlainText(_) | InlineNode::RawText(_) | InlineNode::VerbatimText(_) | InlineNode::StandaloneCurvedApostrophe(_) diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index 7bef30619..1388bc180 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- A pipeline can render registered inline macros against its selected backend + and attributes after tree edits. Each conversion starts fresh processors and + counters and reports warnings at the authored invocation. + - Native block renderers can read the attributes in effect at the block, including accepted body assignments and local table-cell settings. Implementations of `RenderHost::document_attributes` now return a reference diff --git a/converters/core/src/display.rs b/converters/core/src/display.rs index db09f79a8..b5cb78e89 100644 --- a/converters/core/src/display.rs +++ b/converters/core/src/display.rs @@ -19,7 +19,7 @@ pub fn prepare(document: DocumentRef<'_>) -> Result, Error> PreparedDocument::new(document, resolve) } -fn resolve(request: GeneratedDisplayRef<'_>) -> DisplayLabel { +pub(crate) fn resolve(request: GeneratedDisplayRef<'_>) -> DisplayLabel { if request.intent() == DisplayIntent::Title { return DisplayLabel::Title; } diff --git a/converters/core/src/pipeline.rs b/converters/core/src/pipeline.rs index c1b632251..01c45f7a9 100644 --- a/converters/core/src/pipeline.rs +++ b/converters/core/src/pipeline.rs @@ -28,6 +28,12 @@ //! stay on the parse result; conversion warnings stay in [`Diagnostics`] or //! [`ConversionResult`]. The application decides how to present them. //! +//! Selected inline macros run after tree edits, at document preparation for the +//! selected backend. A factory runs on its first surviving invocation. Copied +//! title and catalog labels share that invocation's output. Attribute substitution +//! uses conversion overrides and the source-position attributes. Processor failures +//! precede backend output. Returning typed text leaves escaping to the backend. +//! //! Each conversion resolves a fresh display overlay and uses fresh backend counters //! and traversal state. Shared parsed storage is never mutated. Custom backends //! must honor this same per-conversion state contract in [`Converter::write_to`]. @@ -117,6 +123,31 @@ impl<'options, C: Converter<'options>> Pipeline { } } + fn prepare<'doc>( + &self, + document: DocumentRef<'doc>, + diagnostics: &mut Diagnostics<'_>, + ) -> Result, Error> { + if let Some(registry) = self.extensions.parser_registry() + && document.has_inline_macros() + { + acdc_parser::extensions::PreparedDocument::with_inline_macros( + document, + display::resolve, + registry, + self.converter.name(), + self.converter.parser_options().document_attributes(), + |location, message| { + diagnostics.emit( + crate::Warning::new(diagnostics.source().clone(), message).at(location), + ); + }, + ) + } else { + display::prepare(document) + } + } + /// Resolve display content and write one conversion with structured diagnostics. /// /// # Errors @@ -129,7 +160,7 @@ impl<'options, C: Converter<'options>> Pipeline { output_path: Option<&Path>, diagnostics: &mut Diagnostics<'_>, ) -> Result<(), C::Error> { - let prepared = display::prepare(document)?; + let prepared = self.prepare(document, diagnostics)?; self.converter.write_to_with_extensions( prepared.document(), writer, @@ -151,8 +182,17 @@ impl<'options, C: Converter<'options>> Pipeline { source_file: Option<&Path>, ) -> Result { if self.extensions.renderers.is_empty() { - let prepared = display::prepare(document)?; - self.converter.convert(prepared.document(), source_file) + let mut warnings = Vec::new(); + let prepared = self.prepare( + document, + &mut Diagnostics::new(&self.converter.warning_source(), &mut warnings), + )?; + let mut result = self.converter.convert(prepared.document(), source_file)?; + if !warnings.is_empty() { + warnings.append(&mut result.warnings); + result.warnings = warnings; + } + Ok(result) } else { >::convert(self, document, source_file) } diff --git a/converters/html/tests/late_inline_macros.rs b/converters/html/tests/late_inline_macros.rs new file mode 100644 index 000000000..a586a1539 --- /dev/null +++ b/converters/html/tests/late_inline_macros.rs @@ -0,0 +1,236 @@ +//! Exercise the public inline registration and conversion boundary. +use acdc_converters_core::{Converter as _, Diagnostics, Options, pipeline::Pipeline}; +use acdc_converters_html::{Converter, HtmlVariant}; +use acdc_parser::{ + Options as ParserOptions, + extensions::{ + InlineConversionContext, InlineInvocation, InlineMacroOutput, InlineMacroProcessor, + InlineMatcher, Registry, + }, +}; + +struct Count(usize); +impl InlineMacroProcessor for Count { + fn process( + &mut self, + call: &InlineInvocation<'_>, + ctx: &mut InlineConversionContext<'_>, + ) -> Result { + if call.body == "fail" { + return Err("processor failed".into()); + } + self.0 += 1; + let count = ctx.increment("all"); + let configured = ctx + .attribute("setting") + .and_then(|v| v.as_str()) + .unwrap_or("-"); + let authored = ctx + .attribute("audience") + .and_then(|v| v.as_str()) + .unwrap_or("-"); + ctx.warn(format!( + "{} {}", + call.location.location.start.line, call.location.location.start.column + )); + Ok(InlineMacroOutput::Strong(format!( + "{} {} {} {}/{} {} {} <{}>", + ctx.backend, + configured, + authored, + self.0, + count, + call.target, + call.body, + ctx.document.blocks().count() + ))) + } +} + +fn registry() -> Result> { + let mut builder = Registry::builder(); + for (name, matcher) in [ + ("label", InlineMatcher::Full), + ("tag", InlineMatcher::Short), + ( + "delim", + InlineMatcher::Delimited { + open: "@(".into(), + close: ")".into(), + }, + ), + ] { + builder.register_inline_macro(name, matcher, || Count(0))?; + } + Ok(builder.build()) +} + +#[test] +fn repeated_and_parallel_conversions_expand_eligible_inline_macros() +-> Result<(), Box> { + let registry = registry()?; + let source = ":audience: old\n\nπ label:rust[A & B] and tag:[short].\n\n:audience: new\n\n@(other) and pass:[tag:[skip]] and \\tag:[escaped].\n\n[subs=-macros]\ntag:[skip]\n\n----\ntag:[literal]\n----"; + let parsed = registry + .parse(source, &ParserOptions::default())? + .finish()?; + assert!(parsed.document().has_inline_macros()); + let document = parsed.document(); + let render = |variant, setting: &'static str| -> Result { + let converter = Converter::new_with_variant( + Options::builder().embedded(true).build(), + ParserOptions::builder().with_attribute("setting", setting), + variant, + ) + .map_err(|e| e.to_string())?; + let pipeline = Pipeline::new(converter).with_extensions(registry.clone()); + let mut output = Vec::new(); + let mut warnings = Vec::new(); + pipeline + .write_to( + document, + &mut output, + None, + None, + &mut Diagnostics::new(&pipeline.converter().warning_source(), &mut warnings), + ) + .map_err(|e| e.to_string())?; + assert_eq!(warnings.len(), 3, "{warnings:?}"); + assert_eq!(warnings.first().map(|w| w.message.as_ref()), Some("3 3")); + String::from_utf8(output).map_err(|e| e.to_string()) + }; + let (first, other) = std::thread::scope(|scope| { + let one = scope.spawn(|| render(HtmlVariant::Standard, "first")); + let two = scope.spawn(|| render(HtmlVariant::Semantic, "other")); + (one.join(), two.join()) + }); + let first = first.map_err(|_| "first conversion panicked")??; + let other = other.map_err(|_| "second conversion panicked")??; + assert_eq!(first, render(HtmlVariant::Standard, "first")?); + assert!( + first.contains("html first old 1/1 rust A & B <"), + "{first}" + ); + assert!(first.contains("html first old 1/2 short short")); + assert!(first.contains("html first new 1/3 other")); + assert!(other.contains("html5s other old 1/1")); + assert!(first.contains("tag:[escaped]")); + assert!(first.contains("tag:[literal]")); + Ok(()) +} + +#[test] +fn failed_processor_reports_its_location_before_writing() -> Result<(), Box> +{ + let pipeline = Pipeline::new(Converter::new_with_variant( + Options::default(), + ParserOptions::builder(), + HtmlVariant::Standard, + )?) + .with_extensions(registry()?); + let parsed = pipeline.parse("ordinary text")?; + assert!(!parsed.document().has_inline_macros()); + let parsed = pipeline.parse("before\n\ntag:[fail]")?; + let mut output = Vec::new(); + let error = pipeline + .write_to( + parsed.document(), + &mut output, + None, + None, + &mut Diagnostics::new(&pipeline.converter().warning_source(), &mut Vec::new()), + ) + .err() + .ok_or("macro should fail")?; + assert!(error.to_string().contains("processor failed"), "{error}"); + assert_eq!(output.as_slice(), b""); + Ok(()) +} + +struct RemoveSection; +impl acdc_parser::extensions::TreeProcessor for RemoveSection { + fn process( + &mut self, + editor: &mut acdc_parser::extensions::DocumentEditor<'_>, + ) -> Result<(), acdc_parser::Error> { + let target = editor + .query() + .select(acdc_parser::extensions::BlockContext::Section) + .find(|section| section.output_id() == Some("omit")) + .map(|section| section.target().clone()); + if let Some(target) = target { + editor.remove_section(&target)?; + } + Ok(()) + } +} + +#[test] +fn late_title_uses_source_context_and_runs_once_after_tree_edits() +-> Result<(), Box> { + let mut builder = Registry::builder(); + builder.extend(®istry()?)?; + builder.register_tree_processor(acdc_parser::extensions::TreeProcessorRegistration::new( + "remove", + || RemoveSection, + ))?; + let registry = builder.build(); + let source = "= Doc\n:audience: early\n:setting: parsed\n:toc:\n\n[#omit]\n== Removed\n\ntag:[fail]\n\n[#keep]\n== label:section[{audience}/{setting}]\n\n:audience: later\n\nSee <>."; + let parsed = registry + .parse(source, &ParserOptions::default())? + .finish()?; + let converter = Converter::new_with_variant( + Options::builder().embedded(true).build(), + ParserOptions::builder().with_attribute("setting", "converted"), + HtmlVariant::Standard, + )?; + let pipeline = Pipeline::new(converter).with_extensions(registry); + let mut output = Vec::new(); + let mut warnings = Vec::new(); + pipeline.write_to( + parsed.document(), + &mut output, + None, + None, + &mut Diagnostics::new(&pipeline.converter().warning_source(), &mut warnings), + )?; + let html = String::from_utf8(output)?; + assert_eq!(warnings.len(), 1, "{warnings:?} {html}"); + assert!(html.contains("early 1/1 section early/converted"), "{html}"); + assert!(!html.contains("Removed")); + Ok(()) +} + +#[test] +fn included_macro_warnings_identify_the_file_and_column() -> Result<(), Box> +{ + let directory = tempfile::tempdir()?; + let entry = directory.path().join("entry.adoc"); + let chapter = directory.path().join("chapter.adoc"); + std::fs::write(&entry, "= Entry\n\ninclude::chapter.adoc[]")?; + std::fs::write(&chapter, "π tag:[two]")?; + let pipeline = Pipeline::new(Converter::new_with_variant( + Options::builder().embedded(true).build(), + ParserOptions::builder().with_safe_mode(acdc_parser::SafeMode::Unsafe), + HtmlVariant::Standard, + )?) + .with_extensions(registry()?); + let parsed = pipeline.parse_file(&entry)?; + let mut warnings = Vec::new(); + pipeline.write_to( + parsed.document(), + Vec::new(), + Some(&entry), + None, + &mut Diagnostics::new(&pipeline.converter().warning_source(), &mut warnings), + )?; + let origin = warnings + .first() + .and_then(acdc_converters_core::Warning::source_location) + .ok_or("expected a located inline warning")?; + assert_eq!(origin.file.as_deref(), Some(chapter.as_path())); + assert_eq!( + (origin.location.start.line, origin.location.start.column), + (1, 3) + ); + Ok(()) +} From da2e53eb7db2564ecc0230ff18aa5ba149ae25d8 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 08:39:43 +0100 Subject: [PATCH 45/55] feat(converters): delegate accepted blocks through the HTML renderer chain --- converters/core/CHANGELOG.md | 2 + converters/core/src/pipeline/registrations.rs | 10 +- converters/core/src/render.rs | 151 ++++++++++++++---- converters/core/tests/pipeline.rs | 13 +- converters/html/CHANGELOG.md | 2 + converters/html/src/delimited.rs | 1 + converters/html/src/extensions.rs | 27 +++- converters/html/src/html_visitor.rs | 18 ++- converters/html/src/lib.rs | 3 + converters/html/tests/render_extensions.rs | 73 +++++++-- 10 files changed, 237 insertions(+), 63 deletions(-) diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index 1388bc180..c9d55455f 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Block renderers can decline with a diagnostic before gaining access to output. An accepting renderer can delegate once and wrap the result. Package selection and registration order determine the chain. + - A pipeline can render registered inline macros against its selected backend and attributes after tree edits. Each conversion starts fresh processors and counters and reports warnings at the authored invocation. diff --git a/converters/core/src/pipeline/registrations.rs b/converters/core/src/pipeline/registrations.rs index 8ffe6f8ec..41a067186 100644 --- a/converters/core/src/pipeline/registrations.rs +++ b/converters/core/src/pipeline/registrations.rs @@ -39,6 +39,14 @@ impl Extensions { self.parser.is_none() && self.renderers.is_empty() } + /// Trusted script hashes requested by selected HTML block renderers. + pub fn html_script_hashes(&self) -> impl Iterator + '_ { + self.renderers + .iter() + .filter(|r| r.backend == "html") + .flat_map(|r| r.html_script_hashes().iter().copied()) + } + /// Construct document-local renderers for a backend family, in registration order. /// Other backends invoke no factories. Empty selections allocate no session. #[must_use] @@ -49,6 +57,6 @@ impl Extensions { .filter(|registration| registration.backend == backend) .map(|registration| (registration.factory)()) .collect(); - (!processors.is_empty()).then_some(RenderSession { processors }) + (!processors.is_empty()).then_some(RenderSession::new(processors)) } } diff --git a/converters/core/src/render.rs b/converters/core/src/render.rs index ae8805a05..36573b3eb 100644 --- a/converters/core/src/render.rs +++ b/converters/core/src/render.rs @@ -13,6 +13,7 @@ pub type RenderError = Box; #[derive(Clone)] pub struct BlockRenderer { pub(crate) backend: &'static str, + html_script_hashes: &'static [&'static str], pub(crate) factory: Arc Box + Send + Sync>, } @@ -34,39 +35,53 @@ impl BlockRenderer { ) -> Self { Self { backend, + html_script_hashes: &[], factory: Arc::new(move || Box::new(factory())), } } + /// Declare trusted inline scripts for the HTML host's Content Security Policy. + #[must_use] + pub fn with_html_script_hashes(mut self, hashes: &'static [&'static str]) -> Self { + self.html_script_hashes = hashes; + self + } } -/// A mutable processor belonging to one conversion, including its nested blocks. +/// A mutable renderer for one conversion. HTML dispatches paragraph, listing, +/// and literal blocks. Children of other blocks follow ordinary traversal. pub trait BlockRenderProcessor { - /// Render a block or decline it so the next renderer or backend can handle it. - /// A declined block must not write output; structured fallback warnings are allowed. + /// Select this block before gaining access to output. A decline can warn. /// /// # Errors - /// Stops conversion on processor, host, or output failure. Earlier writes and - /// external effects cannot be rolled back. - fn render( + /// Stops conversion on a selection failure. + fn accepts( &mut self, block: BlockRef<'_>, - host: &mut dyn RenderHost, + context: &mut dyn RenderContext, ) -> Result; - /// Inline script hashes required by this selected renderer, for the host's CSP. - fn script_hashes(&self) -> &'static [&'static str] { - &[] - } + /// Replace the selected block, or decorate the remaining chain with [`Next::render`]. + /// + /// # Errors + /// An error stops the chain. Earlier writes and external effects are observable. + fn render(&mut self, block: BlockRef<'_>, next: Next<'_, '_>) -> Result<(), RenderError>; } -/// Backend services for a native renderer. Titles and metadata retain host semantics. -pub trait RenderHost { - /// Current backend variant, such as `html5` or `html5s`. +/// Services available during selection. Output becomes available only on acceptance. +pub trait RenderContext { + /// Selected backend variant. fn variant(&self) -> &str; - /// Attributes in effect at this block, including body and table-cell assignments. + /// Attributes at the current block, including nested scopes. fn document_attributes(&self) -> &TraversalContext<'_>; - /// Validated application options, including safe mode. + /// Validated converter options and safe mode. fn options(&self) -> &Options; + /// Borrow this conversion’s diagnostic sink. + fn diagnostics(&mut self) -> Diagnostics<'_>; +} + +/// HTML-specific output services. The HTML host owns element wrappers, CSS +/// classes, title rendering, and escaping document metadata. +pub trait HtmlRenderHost: RenderContext { /// Open a backend element with the block's ID, roles, and default classes. /// Native renderers supply trusted target markup; the host escapes document metadata. /// @@ -96,9 +111,78 @@ pub trait RenderHost { } } -/// Selected processors instantiated once for a conversion. Dispatch follows registration order. +/// A one-shot continuation for an accepted block. Write a prefix through +/// [`Self::host`], delegate, then write a suffix through the returned host. +/// Dropping the continuation replaces the block. A delegated error propagates +/// without trying another handler or replaying any writes. +pub struct Next<'a, 'doc> { + host: &'a mut dyn DispatchHost, + remaining: &'a mut [Box], + block: BlockRef<'doc>, +} + +impl<'a> Next<'a, '_> { + /// Write output before delegating, or implement a complete replacement. + pub fn host(&mut self) -> &mut dyn HtmlRenderHost { + self.host.output_host() + } + + /// Run the rest of the chain, falling back to the built-in visitor. + /// + /// # Errors + /// Returns the delegated processor or backend failure. + pub fn render(self) -> Result<&'a mut dyn HtmlRenderHost, RenderError> { + dispatch(self.remaining, self.block, self.host)?; + Ok(self.host.output_host()) + } +} + +trait DispatchHost { + fn output_host(&mut self) -> &mut dyn HtmlRenderHost; + fn base(&mut self) -> Result<(), RenderError>; +} + +struct Host<'a, H, F> { + host: &'a mut H, + base: F, +} + +impl Result<(), RenderError>> DispatchHost + for Host<'_, H, F> +{ + fn output_host(&mut self) -> &mut dyn HtmlRenderHost { + self.host + } + fn base(&mut self) -> Result<(), RenderError> { + (self.base)(self.host) + } +} + +fn dispatch( + mut processors: &mut [Box], + block: BlockRef<'_>, + host: &mut dyn DispatchHost, +) -> Result<(), RenderError> { + while let Some((processor, remaining)) = processors.split_first_mut() { + if processor.accepts(block, host.output_host())? { + return processor.render( + block, + Next { + host, + remaining, + block, + }, + ); + } + processors = remaining; + } + host.base() +} + +/// Fresh handlers in package-selection and registration order. The first +/// accepting handler can replace the block or delegate to later handlers. pub struct RenderSession { - pub(crate) processors: Vec>, + processors: Vec>, } impl fmt::Debug for RenderSession { @@ -111,27 +195,26 @@ impl fmt::Debug for RenderSession { } impl RenderSession { - /// Dispatch until a processor handles the block, otherwise use ordinary rendering. + pub(crate) fn new(processors: Vec>) -> Self { + Self { processors } + } + + /// Dispatch an eligible HTML block. The generic fallback uses the original visitor. /// /// # Errors - /// Stops at the first processor failure without retrying it. - pub fn render( + /// Stops at the first selection, processor, or backend failure. + pub fn render( &mut self, block: BlockRef<'_>, - host: &mut dyn RenderHost, - ) -> Result { - for processor in &mut self.processors { - if processor.render(block, host)? { - return Ok(true); - } - } - Ok(false) + host: &mut H, + base: impl FnMut(&mut H) -> Result<(), RenderError>, + ) -> Result<(), RenderError> { + dispatch(&mut self.processors, block, &mut Host { host, base }) } +} - /// CSP hashes belonging to selected processors for this backend. - pub fn script_hashes(&self) -> impl Iterator + '_ { - self.processors - .iter() - .flat_map(|processor| processor.script_hashes().iter().copied()) +impl BlockRenderer { + pub(crate) fn html_script_hashes(&self) -> &'static [&'static str] { + self.html_script_hashes } } diff --git a/converters/core/tests/pipeline.rs b/converters/core/tests/pipeline.rs index f5dccd62c..c99bbd4aa 100644 --- a/converters/core/tests/pipeline.rs +++ b/converters/core/tests/pipeline.rs @@ -393,18 +393,25 @@ fn pipeline_selection_order_controls_processor_order() -> TestResult { #[test] fn pipeline_renderer_factories_wait_for_matching_backend_sessions() -> TestResult { use acdc_converters_core::render::{ - BlockRenderProcessor, BlockRenderer, RenderError, RenderHost, + BlockRenderProcessor, BlockRenderer, Next, RenderContext, RenderError, }; struct Decline; impl BlockRenderProcessor for Decline { - fn render( + fn accepts( &mut self, _: acdc_parser::ast::BlockRef<'_>, - _: &mut dyn RenderHost, + _: &mut dyn RenderContext, ) -> Result { Ok(false) } + fn render( + &mut self, + _: acdc_parser::ast::BlockRef<'_>, + _: Next<'_, '_>, + ) -> Result<(), RenderError> { + Err("declined renderer called".into()) + } } let created = Arc::new(AtomicUsize::new(0)); diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index a08d82b14..b2e731a93 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Native renderers can decorate paragraphs, listings, and literal blocks while retaining the selected HTML variant’s built-in rendering. + - Native HTML renderers now observe body attribute changes in source order and restore the enclosing settings after each AsciiDoc table cell. diff --git a/converters/html/src/delimited.rs b/converters/html/src/delimited.rs index 8ee6c0152..9469fdef0 100644 --- a/converters/html/src/delimited.rs +++ b/converters/html/src/delimited.rs @@ -1151,6 +1151,7 @@ mod tests { index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(std::cell::RefCell::new(Vec::new())), generate_index: false, + extension_script_hashes: Vec::new(), render_session: None, variant: crate::HtmlVariant::Standard, } diff --git a/converters/html/src/extensions.rs b/converters/html/src/extensions.rs index 8c81907fb..56805d569 100644 --- a/converters/html/src/extensions.rs +++ b/converters/html/src/extensions.rs @@ -4,9 +4,12 @@ use std::io::Write; use acdc_converters_core::{ Diagnostics, Options, TraversalContext, - render::{RenderError, RenderHost}, + render::{HtmlRenderHost, RenderContext, RenderError}, +}; +use acdc_parser::{ + CaptionKind, + ast::{BlockKind, BlockRef}, }; -use acdc_parser::{CaptionKind, ast::BlockRef}; use crate::{ Error, HtmlVariant, HtmlVisitor, @@ -22,16 +25,24 @@ impl<'doc, W: Write> HtmlVisitor<'doc, '_, W> { let Some(session) = self.converter.render_session.clone() else { return Ok(false); }; + if !matches!( + block.kind(), + BlockKind::Paragraph(_) | BlockKind::Listing(_) | BlockKind::Literal(_) + ) { + return Ok(false); + } let mut session = session.try_borrow_mut().map_err(|_| { Error::Extension(std::io::Error::other("recursive block renderer dispatch").into()) })?; - Ok(session.render( + session.render( block, &mut Host { visitor: self, traversal, }, - )?) + |host| Ok(host.visitor.render_builtin_block(host.traversal, block)?), + )?; + Ok(true) } } @@ -40,7 +51,7 @@ struct Host<'host, 'doc, 'diagnostics, W: Write> { traversal: &'host mut TraversalContext<'doc>, } -impl RenderHost for Host<'_, '_, '_, W> { +impl RenderContext for Host<'_, '_, '_, W> { fn variant(&self) -> &str { self.visitor.converter.variant.backend_profile().backend() } @@ -51,6 +62,12 @@ impl RenderHost for Host<'_, '_, '_, W> { &self.visitor.converter.options } + fn diagnostics(&mut self) -> Diagnostics<'_> { + self.visitor.diagnostics.reborrow() + } +} + +impl HtmlRenderHost for Host<'_, '_, '_, W> { fn open_block( &mut self, block: BlockRef<'_>, diff --git a/converters/html/src/html_visitor.rs b/converters/html/src/html_visitor.rs index 61063332d..5216d5657 100644 --- a/converters/html/src/html_visitor.rs +++ b/converters/html/src/html_visitor.rs @@ -539,13 +539,7 @@ impl<'a, 'd, W: Write> HtmlVisitor<'a, 'd, W> { webfonts: !(stylesheet_disabled || !attrs.contains("webfonts") && attrs.is_explicit("webfonts")), icons_font: font_icons, - extension_script_hashes: self - .converter - .render_session - .as_ref() - .map_or_else(Vec::new, |session| { - session.borrow().script_hashes().collect() - }), + extension_script_hashes: self.converter.extension_script_hashes.clone(), } } @@ -744,6 +738,16 @@ impl<'a, W: Write> BlockVisitor<'a> for HtmlVisitor<'a, '_, W> { if self.render_extension(context, block)? { return Ok(()); } + self.render_builtin_block(context, block) + } +} + +impl<'a, W: Write> HtmlVisitor<'a, '_, W> { + pub(super) fn render_builtin_block( + &mut self, + context: &mut TraversalContext<'a>, + block: BlockRef<'a>, + ) -> Result<(), Error> { match block.kind() { BlockKind::Section(section) => self.visit_section_ref(context, section), BlockKind::Paragraph(paragraph) => self.visit_paragraph_ref(context, paragraph), diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index 5400ae486..21749c8b6 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -178,6 +178,7 @@ pub struct Converter<'a> { index_entries: Rc>>, /// Whether the header opts into a catalog and the section hierarchy has a seed. generate_index: bool, + extension_script_hashes: Vec<&'static str>, render_session: Option>>, /// HTML output variant (Standard or Semantic). variant: HtmlVariant, @@ -331,6 +332,7 @@ impl<'a> Converter<'a> { index_term_counter: Rc::new(Cell::new(0)), index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(RefCell::new(Vec::new())), + extension_script_hashes: extensions.html_script_hashes().collect(), render_session: extensions .render_session("html") .map(|session| Rc::new(RefCell::new(session))), @@ -648,6 +650,7 @@ impl<'a> Converter<'a> { index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(RefCell::new(Vec::new())), generate_index: false, + extension_script_hashes: Vec::new(), render_session: None, variant, }) diff --git a/converters/html/tests/render_extensions.rs b/converters/html/tests/render_extensions.rs index 3db443480..c35c3caa5 100644 --- a/converters/html/tests/render_extensions.rs +++ b/converters/html/tests/render_extensions.rs @@ -12,7 +12,7 @@ use std::{ use acdc_converters_core::{ Converter as _, Diagnostics, Options, pipeline::{ExtensionCatalog, Extensions, Pipeline}, - render::{BlockRenderProcessor, BlockRenderer, RenderError, RenderHost}, + render::{BlockRenderProcessor, BlockRenderer, Next, RenderContext, RenderError}, }; use acdc_converters_html::Converter; use acdc_parser::{ @@ -27,17 +27,18 @@ struct Counter { } impl BlockRenderProcessor for Counter { - fn render( + fn accepts( &mut self, block: BlockRef<'_>, - host: &mut dyn RenderHost, + _: &mut dyn RenderContext, ) -> Result { - if !matches!(block.kind(), BlockKind::Paragraph(_)) { - return Ok(false); - } + Ok(matches!(block.kind(), BlockKind::Paragraph(_))) + } + fn render(&mut self, _: BlockRef<'_>, mut next: Next<'_, '_>) -> Result<(), RenderError> { + let host = next.host(); self.calls.set(self.calls.get() + 1); host.write(format!("

native:{}

\n", self.calls.get()).as_bytes())?; - Ok(true) + Ok(()) } } @@ -139,7 +140,10 @@ fn native_renderers_are_explicit_and_fresh_across_nested_and_parallel_conversion struct Fail(Arc); impl BlockRenderProcessor for Fail { - fn render(&mut self, _: BlockRef<'_>, _: &mut dyn RenderHost) -> Result { + fn accepts(&mut self, _: BlockRef<'_>, _: &mut dyn RenderContext) -> Result { + Ok(true) + } + fn render(&mut self, _: BlockRef<'_>, _: Next<'_, '_>) -> Result<(), RenderError> { self.0.fetch_add(1, Ordering::SeqCst); Err(std::io::Error::other("native failure").into()) } @@ -180,10 +184,10 @@ struct Decision { } impl BlockRenderProcessor for Decision { - fn render( + fn accepts( &mut self, block: BlockRef<'_>, - host: &mut dyn RenderHost, + _: &mut dyn RenderContext, ) -> Result { if !matches!(block.kind(), BlockKind::Paragraph(_)) { return Ok(false); @@ -192,11 +196,11 @@ impl BlockRenderProcessor for Decision { .lock() .map_err(|_| "trace lock poisoned")? .push(self.label); - if self.handled { - host.write(self.label.as_bytes())?; - } Ok(self.handled) } + fn render(&mut self, _: BlockRef<'_>, mut next: Next<'_, '_>) -> Result<(), RenderError> { + next.host().write(self.label.as_bytes()) + } } #[test] @@ -226,3 +230,46 @@ fn native_renderer_dispatch_follows_selection_order_and_stops_when_handled() -> assert_eq!(*trace.lock().map_err(|_| "trace lock poisoned")?, ["third"]); Ok(()) } + +#[test] +fn decorators_wrap_the_next_handler_and_declines_only_emit_diagnostics() -> TestResult { + struct Decorator(&'static str); + impl BlockRenderProcessor for Decorator { + fn accepts( + &mut self, + _: BlockRef<'_>, + context: &mut dyn RenderContext, + ) -> Result { + if self.0 == "decline" { + context.diagnostics().warn("declined"); + return Ok(false); + } + Ok(true) + } + fn render(&mut self, _: BlockRef<'_>, mut next: Next<'_, '_>) -> Result<(), RenderError> { + next.host().write(format!("<{}>", self.0).as_bytes())?; + next.render()?.write(format!("", self.0).as_bytes()) + } + } + let mut extensions = Extensions::default(); + for tag in ["outer", "decline", "inner"] { + extensions = extensions.with_renderer(BlockRenderer::new("html", move || Decorator(tag))); + } + let pipeline = pipeline(Some(extensions))?; + let parsed = pipeline.parse("ordinary")?; + let mut warnings = Vec::new(); + let mut output = Vec::new(); + pipeline.write_to( + parsed.document(), + &mut output, + None, + None, + &mut Diagnostics::new(&pipeline.converter().warning_source(), &mut warnings), + )?; + let html = String::from_utf8(output)?; + assert!(html.starts_with(""), "{html}"); + assert!(html.ends_with(""), "{html}"); + assert_eq!(html.matches("

ordinary

").count(), 1); + assert_eq!(warnings.len(), 1); + Ok(()) +} From b11788ac585d6a5dab0bee5f385dd5ff60000936 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 08:39:51 +0100 Subject: [PATCH 46/55] feat(html): run ordered docinfo hooks at document insertion points --- converters/core/CHANGELOG.md | 2 + converters/core/src/docinfo.rs | 67 ++++++++ converters/core/src/lib.rs | 7 + converters/core/src/pipeline.rs | 28 ++-- converters/core/src/pipeline/extensions.rs | 3 + converters/core/src/pipeline/registrations.rs | 34 +++- converters/html/CHANGELOG.md | 2 + converters/html/src/html_visitor.rs | 34 +++- converters/html/src/lib.rs | 10 ++ converters/html/tests/docinfo_extensions.rs | 151 ++++++++++++++++++ 10 files changed, 319 insertions(+), 19 deletions(-) create mode 100644 converters/core/src/docinfo.rs create mode 100644 converters/html/tests/docinfo_extensions.rs diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index c9d55455f..b05416aa7 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Selected docinfo hooks can insert trusted fragments during conversion in registration order, with access to the current document attributes and diagnostics. + - Block renderers can decline with a diagnostic before gaining access to output. An accepting renderer can delegate once and wrap the result. Package selection and registration order determine the chain. - A pipeline can render registered inline macros against its selected backend diff --git a/converters/core/src/docinfo.rs b/converters/core/src/docinfo.rs new file mode 100644 index 000000000..d956d64e6 --- /dev/null +++ b/converters/core/src/docinfo.rs @@ -0,0 +1,67 @@ +//! Trusted fragments inserted into the selected backend's document frame. +use std::{fmt, sync::Arc}; + +use acdc_parser::ast::DocumentRef; + +use crate::{Diagnostics, TraversalContext, render::RenderError}; + +/// Full HTML supports these positions, in order. Embedded HTML has no document frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum DocinfoPosition { + /// Immediately before the closing head tag. + Head, + /// Immediately after the opening body tag. + Header, + /// After the document footer and before closing the body. + Footer, +} + +/// Document and attributes at this insertion point. Footer hooks observe body assignments. +#[derive(Clone, Copy)] +pub struct DocinfoContext<'a> { + /// Actual backend variant. + pub backend: &'a str, + /// Insertion point reached during host traversal. + pub position: DocinfoPosition, + /// Prepared document being rendered. + pub document: DocumentRef<'a>, + /// Attribute values at the insertion point. + pub attributes: &'a TraversalContext<'a>, +} + +/// One conversion's callback. Return trusted backend markup or omit the fragment. +/// The host appends a newline to a present fragment and never interprets or escapes it. +/// Authors must escape document-derived values for their insertion context. +pub type DocinfoProcessor = + dyn FnMut(DocinfoContext<'_>, &mut Diagnostics<'_>) -> Result, RenderError>; + +/// A docinfo factory for an explicitly selected backend family. +#[derive(Clone)] +pub struct DocinfoHook { + pub(crate) backend: &'static str, + pub(crate) factory: Arc Box + Send + Sync>, +} + +impl fmt::Debug for DocinfoHook { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DocinfoHook") + .field("backend", &self.backend) + .finish_non_exhaustive() + } +} + +impl DocinfoHook { + /// Create one mutable callback per full document, shared by its insertion points. + /// Registration and embedded conversions never execute the factory. + pub fn new(backend: &'static str, factory: impl Fn() -> F + Send + Sync + 'static) -> Self + where + F: FnMut(DocinfoContext<'_>, &mut Diagnostics<'_>) -> Result, RenderError> + + 'static, + { + Self { + backend, + factory: Arc::new(move || Box::new(factory())), + } + } +} diff --git a/converters/core/src/lib.rs b/converters/core/src/lib.rs index 81c122eb7..96e1b3780 100644 --- a/converters/core/src/lib.rs +++ b/converters/core/src/lib.rs @@ -47,6 +47,7 @@ mod backend; /// Source code syntax highlighting and callouts support. pub mod code; pub mod display; +pub mod docinfo; mod doctype; mod document_attributes; pub mod icon; @@ -627,6 +628,12 @@ pub trait Converter<'a>: Sized { diagnostics: &mut Diagnostics<'_>, ) -> Result<(), Self::Error>; + /// Whether this backend handles any selected hooks during its own traversal. + /// The pipeline preserves backend-specific destination routing for other selections. + fn uses_render_extensions(&self, _extensions: &pipeline::Extensions) -> bool { + false + } + /// Write with explicitly selected native rendering extensions. /// Backends without rendering hooks retain their ordinary output. /// diff --git a/converters/core/src/pipeline.rs b/converters/core/src/pipeline.rs index 01c45f7a9..c071835e1 100644 --- a/converters/core/src/pipeline.rs +++ b/converters/core/src/pipeline.rs @@ -67,6 +67,7 @@ impl Pipeline { extensions: Extensions { parser: None, renderers: Vec::new(), + docinfo: Vec::new(), }, } } @@ -181,21 +182,20 @@ impl<'options, C: Converter<'options>> Pipeline { document: DocumentRef<'_>, source_file: Option<&Path>, ) -> Result { - if self.extensions.renderers.is_empty() { - let mut warnings = Vec::new(); - let prepared = self.prepare( - document, - &mut Diagnostics::new(&self.converter.warning_source(), &mut warnings), - )?; - let mut result = self.converter.convert(prepared.document(), source_file)?; - if !warnings.is_empty() { - warnings.append(&mut result.warnings); - result.warnings = warnings; - } - Ok(result) - } else { - >::convert(self, document, source_file) + if self.converter.uses_render_extensions(&self.extensions) { + return >::convert(self, document, source_file); + } + let mut warnings = Vec::new(); + let prepared = self.prepare( + document, + &mut Diagnostics::new(&self.converter.warning_source(), &mut warnings), + )?; + let mut result = self.converter.convert(prepared.document(), source_file)?; + if !warnings.is_empty() { + warnings.append(&mut result.warnings); + result.warnings = warnings; } + Ok(result) } } diff --git a/converters/core/src/pipeline/extensions.rs b/converters/core/src/pipeline/extensions.rs index 85cdf5a90..40e7b0cd0 100644 --- a/converters/core/src/pipeline/extensions.rs +++ b/converters/core/src/pipeline/extensions.rs @@ -78,6 +78,7 @@ impl ExtensionCatalog { let mut builder = Registry::builder(); let mut active = false; let mut renderers = Vec::new(); + let mut docinfo = Vec::new(); for name in names { let (name, registrations) = self .available @@ -95,11 +96,13 @@ impl ExtensionCatalog { })?; active = true; } + docinfo.extend(registrations.docinfo.iter().cloned()); renderers.extend(registrations.renderers.iter().cloned()); } let extensions = Extensions { parser: active.then(|| builder.build()), renderers, + docinfo, }; Ok((!extensions.is_empty()).then_some(extensions)) } diff --git a/converters/core/src/pipeline/registrations.rs b/converters/core/src/pipeline/registrations.rs index 41a067186..05a82f959 100644 --- a/converters/core/src/pipeline/registrations.rs +++ b/converters/core/src/pipeline/registrations.rs @@ -1,12 +1,16 @@ use acdc_parser::extensions::Registry; -use crate::render::{BlockRenderer, RenderSession}; +use crate::{ + docinfo::{DocinfoHook, DocinfoProcessor}, + render::{BlockRenderer, RenderSession}, +}; /// Immutable parser and renderer registrations, available or explicitly selected. /// Cloning shares factories; every parse and conversion gets fresh mutable processors. #[derive(Clone, Debug, Default)] pub struct Extensions { pub(super) parser: Option, + pub(super) docinfo: Vec, pub(super) renderers: Vec, } @@ -15,6 +19,7 @@ impl From for Extensions { Self { parser: (!registry.is_empty()).then_some(registry), renderers: Vec::new(), + docinfo: Vec::new(), } } } @@ -27,6 +32,31 @@ impl Extensions { self } + /// Append a docinfo hook. At each insertion point hooks run in selection + /// and registration order, following any file-based docinfo. + #[must_use] + pub fn with_docinfo(mut self, hook: DocinfoHook) -> Self { + self.docinfo.push(hook); + self + } + + /// Whether a backend family has selected renderers or supported docinfo hooks. + #[must_use] + pub fn has_render_hooks(&self, backend: &str, full_document: bool) -> bool { + self.renderers.iter().any(|r| r.backend == backend) + || (full_document && self.docinfo.iter().any(|r| r.backend == backend)) + } + + /// Instantiate docinfo processors for a backend's available insertion points. + #[must_use] + pub fn docinfo_processors(&self, backend: &str) -> Vec> { + self.docinfo + .iter() + .filter(|r| r.backend == backend) + .map(|r| (r.factory)()) + .collect() + } + /// Parser registrations, for callers that need a working edit session. #[must_use] pub fn parser_registry(&self) -> Option<&Registry> { @@ -36,7 +66,7 @@ impl Extensions { /// Whether this collection has no parser or rendering capabilities. #[must_use] pub fn is_empty(&self) -> bool { - self.parser.is_none() && self.renderers.is_empty() + self.parser.is_none() && self.renderers.is_empty() && self.docinfo.is_empty() } /// Trusted script hashes requested by selected HTML block renderers. diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index b2e731a93..19786dfbe 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Full HTML documents accept native docinfo fragments at the end of the head, start of the body, and after the footer. Embedded HTML skips these hooks. + - Native renderers can decorate paragraphs, listings, and literal blocks while retaining the selected HTML variant’s built-in rendering. - Native HTML renderers now observe body attribute changes in source order diff --git a/converters/html/src/html_visitor.rs b/converters/html/src/html_visitor.rs index 5216d5657..7977735b5 100644 --- a/converters/html/src/html_visitor.rs +++ b/converters/html/src/html_visitor.rs @@ -3,7 +3,9 @@ use std::{convert::Infallible, io::Write, path::Path, rc::Rc}; use acdc_converters_core::{ - Diagnostics, TraversalContext, document_attribute_text, + Diagnostics, TraversalContext, + docinfo::{DocinfoContext, DocinfoPosition, DocinfoProcessor}, + document_attribute_text, substitutions::{TextBoundaries, effective_subs}, visitor::BlockVisitor, }; @@ -276,6 +278,7 @@ pub(crate) struct HtmlVisitor<'a, 'd, W: Write> { pub(crate) captured_raw_fragments: Option>, /// Resolved docinfo content for injection at head, header, and footer positions. docinfo: DocInfo, + pub(super) docinfo_processors: Vec>, pub(crate) text_boundaries: TextBoundaries, } @@ -310,6 +313,7 @@ impl<'a, 'd, W: Write> HtmlVisitor<'a, 'd, W> { captured_raw_fragments: None, inline_link: None, docinfo, + docinfo_processors: Vec::new(), text_boundaries: TextBoundaries::BOTH, } } @@ -543,8 +547,29 @@ impl<'a, 'd, W: Write> HtmlVisitor<'a, 'd, W> { } } + fn write_docinfo( + &mut self, + position: DocinfoPosition, + doc: DocumentRef<'a>, + traversal: &TraversalContext<'a>, + ) -> Result<(), Error> { + for hook in &mut self.docinfo_processors { + let context = DocinfoContext { + backend: self.converter.variant.backend_profile().backend(), + position, + document: doc, + attributes: traversal, + }; + if let Some(fragment) = hook(context, &mut self.diagnostics)? { + writeln!(self.writer, "{fragment}")?; + } + } + Ok(()) + } + fn render_head( &mut self, + traversal: &TraversalContext<'a>, document: DocumentRef<'a>, stem: bool, font_icons: bool, @@ -606,6 +631,7 @@ impl<'a, 'd, W: Write> HtmlVisitor<'a, 'd, W> { if let Some(content) = &self.docinfo.head { writeln!(self.writer, "{content}")?; } + self.write_docinfo(DocinfoPosition::Head, document, traversal)?; writeln!(self.writer, "")?; Ok(()) } @@ -804,7 +830,7 @@ impl<'a, W: Write> HtmlVisitor<'a, '_, W> { impl<'a, W: Write> acdc_converters_core::visitor::DocumentVisitor<'a> for HtmlVisitor<'a, '_, W> { fn visit_document_start( &mut self, - _traversal: &mut TraversalContext<'a>, + traversal: &mut TraversalContext<'a>, doc: DocumentRef<'a>, ) -> Result<(), Self::Error> { let attributes = doc.attributes(); @@ -831,7 +857,7 @@ impl<'a, W: Write> acdc_converters_core::visitor::DocumentVisitor<'a> for HtmlVi } let resources = HeadResources::collect(doc); - self.render_head(doc, resources.stem, resources.font_icons)?; + self.render_head(traversal, doc, resources.stem, resources.font_icons)?; let converter_attributes = DocumentAttributesRef::from(self.converter.document_attributes()); @@ -886,6 +912,7 @@ impl<'a, W: Write> acdc_converters_core::visitor::DocumentVisitor<'a> for HtmlVi if let Some(content) = &self.docinfo.header { writeln!(self.writer, "{content}")?; } + self.write_docinfo(DocinfoPosition::Header, doc, traversal)?; Ok(()) } @@ -930,6 +957,7 @@ impl<'a, W: Write> acdc_converters_core::visitor::DocumentVisitor<'a> for HtmlVi if let Some(content) = &self.docinfo.footer { writeln!(self.writer, "{content}")?; } + self.write_docinfo(DocinfoPosition::Footer, doc, traversal)?; } Ok(()) } diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index 21749c8b6..6585b7bab 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -345,6 +345,9 @@ impl<'a> Converter<'a> { options.clone(), diagnostics.reborrow(), ); + if !options.embedded { + visitor.docinfo_processors = extensions.docinfo_processors("html"); + } acdc_converters_core::visitor::DocumentVisitor::visit_document( &mut visitor, &mut traversal, @@ -556,6 +559,13 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { ) } + fn uses_render_extensions( + &self, + extensions: &acdc_converters_core::pipeline::Extensions, + ) -> bool { + extensions.has_render_hooks("html", !self.options.embedded()) + } + fn write_to_with_extensions( &self, doc: DocumentRef<'_>, diff --git a/converters/html/tests/docinfo_extensions.rs b/converters/html/tests/docinfo_extensions.rs new file mode 100644 index 000000000..9dfd3214b --- /dev/null +++ b/converters/html/tests/docinfo_extensions.rs @@ -0,0 +1,151 @@ +//! Frame insertion uses the library pipeline shared with CLI output routing. +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +use acdc_converters_core::{ + Converter as _, Diagnostics, Options, Warning, + docinfo::{DocinfoContext, DocinfoHook, DocinfoPosition}, + pipeline::{ExtensionCatalog, Extensions, Pipeline}, +}; +use acdc_converters_html::{Converter, HtmlVariant}; +use acdc_parser::{Options as ParserOptions, ast::DocumentRef}; + +type TestResult = Result<(), Box>; +fn pipeline( + embedded: bool, + variant: HtmlVariant, + selection: Extensions, +) -> Result>, acdc_converters_html::Error> { + Ok(Pipeline::new(Converter::new_with_variant( + Options::builder().embedded(embedded).build(), + ParserOptions::builder(), + variant, + )?) + .with_extensions(selection)) +} +fn render( + p: &Pipeline>, + doc: DocumentRef<'_>, +) -> Result<(String, Vec), Box> { + let mut output = Vec::new(); + let mut warnings = Vec::new(); + p.write_to( + doc, + &mut output, + None, + None, + &mut Diagnostics::new(&p.converter().warning_source(), &mut warnings), + )?; + Ok((String::from_utf8(output)?, warnings)) +} +#[test] +fn ordered_docinfo_tracks_traversal_and_is_fresh_for_each_full_document() -> TestResult { + let count = Arc::new(AtomicUsize::new(0)); + let mut catalog = ExtensionCatalog::default(); + for tag in ["one", "two"] { + let count = Arc::clone(&count); + catalog.register( + tag, + Extensions::default().with_docinfo(DocinfoHook::new("html", move || { + count.fetch_add(1, Ordering::SeqCst); + let mut calls = 0; + move |ctx: DocinfoContext<'_>, diagnostics: &mut Diagnostics<'_>| { + calls += 1; + if ctx.position == DocinfoPosition::Footer { + diagnostics.warn(tag); + } + let value = ctx + .attributes + .get("phase") + .and_then(|a| a.text()) + .unwrap_or("missing"); + Ok(Some(format!(""))) + } + })), + )?; + } + let selection = catalog.select(["one", "two", "one"])?.ok_or("selection")?; + let source = "= Frame\n:phase: early\n:!stylesheet:\n\nText.\n\n:phase: late\n\nEnd."; + for variant in [HtmlVariant::Standard, HtmlVariant::Semantic] { + let p = pipeline(false, variant, selection.clone())?; + let parsed = p.parse(source)?; + let first = render(&p, parsed.document())?; + assert_eq!(first, render(&p, parsed.document())?); + for (text, closing) in [ + ("\n", ""), + ("\n", "Text."), + ("\n", ""), + ] { + let (_, tail) = first + .0 + .split_once(text) + .ok_or_else(|| format!("missing {text}"))?; + assert!(tail.contains(closing)); + } + assert_eq!(first.1.len(), 2); + let other = pipeline(true, variant, selection.clone())?; + let (embedded, warnings) = render(&other, parsed.document())?; + assert!(!embedded.contains("")).count(), 1); + assert_eq!(warnings.len(), 2); + Ok(()) + }) + }); + for worker in workers { + worker.join().map_err(|_| "docinfo worker panicked")??; + } + Ok::<(), String>(()) + })?; + Ok(()) +} + +#[test] +fn docinfo_failure_stops_subsequent_hooks_and_keeps_prior_output() -> TestResult { + let extensions = Extensions::default() + .with_docinfo(DocinfoHook::new("html", || { + |ctx: DocinfoContext<'_>, _: &mut Diagnostics<'_>| { + if ctx.position == DocinfoPosition::Footer { + return Err("footer failure".into()); + } + Ok(None) + } + })) + .with_docinfo(DocinfoHook::new("html", || { + |ctx: DocinfoContext<'_>, _: &mut Diagnostics<'_>| { + Ok(Some(format!("", ctx.position))) + } + })); + let p = pipeline(false, HtmlVariant::Standard, extensions)?; + let parsed = p.parse("Text")?; + let mut output = Vec::new(); + let error = p + .write_to( + parsed.document(), + &mut output, + None, + None, + &mut Diagnostics::new(&p.converter().warning_source(), &mut Vec::new()), + ) + .err() + .ok_or("expected failure")?; + assert!(error.to_string().contains("footer failure")); + let partial = String::from_utf8(output)?; + assert!(partial.contains("")); + assert!(!partial.contains("")); + Ok(()) +} From 121daa9ee33fb0c7127bea71f6fd3a8ada52cb89 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 08:39:51 +0100 Subject: [PATCH 47/55] feat(converters): postprocess completed text before delivery --- Cargo.lock | 1 + acdc-cli/CHANGELOG.md | 2 + acdc-cli/src/subcommands/convert.rs | 141 +++++++++++- converters/core/CHANGELOG.md | 2 + converters/core/Cargo.toml | 1 + converters/core/src/lib.rs | 106 +++++---- converters/core/src/pipeline.rs | 125 ++++++++++- converters/core/src/pipeline/extensions.rs | 3 + converters/core/src/pipeline/registrations.rs | 22 +- converters/core/src/postprocess.rs | 93 ++++++++ converters/core/tests/postprocessing.rs | 207 ++++++++++++++++++ converters/html/CHANGELOG.md | 2 + converters/html/src/lib.rs | 4 + converters/manpage/CHANGELOG.md | 2 + converters/manpage/src/lib.rs | 4 + converters/markdown/CHANGELOG.md | 2 + converters/markdown/src/lib.rs | 4 + converters/terminal/CHANGELOG.md | 2 + converters/terminal/src/lib.rs | 4 + 19 files changed, 677 insertions(+), 50 deletions(-) create mode 100644 converters/core/src/postprocess.rs create mode 100644 converters/core/tests/postprocessing.rs diff --git a/Cargo.lock b/Cargo.lock index e37dc7008..f9e46c0a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -41,6 +41,7 @@ dependencies = [ "relative-path 2.0.3", "rustc-hash", "serde_json", + "stats_alloc", "tempfile", "thiserror", "tracing", diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index bdeac16a8..ca85c0d82 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Selected native text postprocessors run per input, including when multiple terminal documents share a pager. + - Conversion accepts repeatable `--extension NAME` selections and rejects unavailable packages before reading input. All input and output routes share the backend-aware library pipeline. diff --git a/acdc-cli/src/subcommands/convert.rs b/acdc-cli/src/subcommands/convert.rs index b75020fff..68faff820 100644 --- a/acdc-cli/src/subcommands/convert.rs +++ b/acdc-cli/src/subcommands/convert.rs @@ -1085,7 +1085,10 @@ mod tests { #[test] fn fail_on_warnings_counts_pager_diagnostics_after_all_inputs_finish() -> Result<(), Box> { - use std::process::{Command, Stdio}; + use std::{ + fmt::Write as _, + process::{Command, Stdio}, + }; let directory = tempfile::tempdir()?; let warning = directory.path().join("warning.adoc"); @@ -1103,7 +1106,21 @@ mod tests { let converter = Pipeline::new(acdc_converters_terminal::Converter::new( options.clone(), ParserOptions::builder(), - )?); + )?) + .with_extensions(Extensions::default().with_postprocessor( + acdc_converters_core::postprocess::TextPostprocessor::new( + "terminal", + |text, ctx, _| { + let stem = ctx + .source_file + .and_then(Path::file_stem) + .and_then(|name| name.to_str()) + .ok_or("missing pager source")?; + writeln!(text, "completed {stem}")?; + Ok(()) + }, + ), + )); let pager = Command::new("/bin/sh") .args([ "-c", @@ -1122,7 +1139,117 @@ mod tests { let rendered = std::fs::read_to_string(captured)?; assert!(rendered.contains("Retained body.")); assert!(rendered.contains("Clean pager body.")); - assert!(rendered.ends_with("pager finished\n")); + assert!(rendered.contains("completed warning")); + assert!(rendered.ends_with("completed clean\npager finished\n")); + Ok(()) + } + + #[cfg(feature = "pdf")] + #[test] + fn pdf_rejects_a_selected_text_postprocessor_before_writing() -> Result<(), Box> { + use acdc_converters_core::postprocess::{PostprocessError, TextPostprocessor}; + + let directory = tempfile::tempdir()?; + let path = directory.path().join("existing.pdf"); + std::fs::write(&path, b"previous output")?; + let options = Options::builder() + .output_destination(OutputDestination::File(path.clone())) + .build(); + let extension = Extensions::default() + .with_postprocessor(TextPostprocessor::new("pdf", |_, _, _| { + Err("unexpected PDF callback".into()) + })); + let pipeline = configure_pipeline( + acdc_converters_pdf::Converter::new(options, ParserOptions::builder())?, + Some(&extension), + ); + let parsed = pipeline.parse("Body")?; + let Err(acdc_converters_pdf::Error::Io(error)) = pipeline.convert(parsed.document(), None) + else { + return Err("expected an unsupported PDF postprocessor".into()); + }; + assert!(matches!( + error + .get_ref() + .and_then(|source| source.downcast_ref::()), + Some(PostprocessError::Unsupported("pdf")) + )); + assert_eq!(std::fs::read(path)?, b"previous output"); + Ok(()) + } + + #[cfg(feature = "html")] + #[test] + fn postprocessing_sees_one_complete_document_per_reader_and_batch_file() -> MietteResult<()> { + use acdc_converters_core::postprocess::TextPostprocessor; + use miette::IntoDiagnostic as _; + + let dir = tempfile::tempdir().into_diagnostic()?; + let files = ["left.adoc", "right.adoc"].map(|name| dir.path().join(name)); + for file in &files { + std::fs::write(file, "Document body.").into_diagnostic()?; + } + let extension = Extensions::default().with_postprocessor(TextPostprocessor::new( + "html", + |text, ctx, _| { + assert!(text.contains("Document body.") && text.trim_end().ends_with("")); + let input = ctx + .source_file + .and_then(Path::file_stem) + .and_then(|name| name.to_str()) + .unwrap_or("stdin"); + let output = ctx + .output_path + .and_then(Path::file_stem) + .and_then(|name| name.to_str()) + .unwrap_or("stdout"); + *text = format!("{input} to {output}"); + Ok(()) + }, + )); + let batch = run_multi_file( + &Options::default(), + &ParserOptions::builder(), + &files, + Some(&extension), + acdc_converters_html::Converter::new, + )?; + assert_eq!(batch.output_paths.len(), 2); + for name in ["left", "right"] { + let text = std::fs::read_to_string(dir.path().join(name).with_extension("html")) + .into_diagnostic()?; + assert_eq!(text, format!("{name} to {name}")); + } + let dst = dir.path().join("reader.html"); + let reader = configure_pipeline( + acdc_converters_html::Converter::new( + Options::builder() + .output_destination(OutputDestination::File(dst.clone())) + .build(), + ParserOptions::builder(), + ) + .into_diagnostic()?, + Some(&extension), + ); + convert_reader(&reader, "Document body.".as_bytes())?; + assert_eq!( + std::fs::read_to_string(dst).into_diagnostic()?, + "stdin to reader" + ); + let stdout = configure_pipeline( + acdc_converters_html::Converter::new( + Options::builder() + .output_destination(OutputDestination::Stdout) + .build(), + ParserOptions::builder(), + ) + .into_diagnostic()?, + Some(&extension), + ); + assert_eq!( + convert_reader(&stdout, "Document body.".as_bytes())?.warning_count, + 0 + ); Ok(()) } @@ -1403,7 +1530,13 @@ fn run_terminal_through_pager( for file in files { let mut parsed = parse_terminal_file(base_options, converter, file)?; let parser_warnings = parsed.take_warnings(); - converter.write_to(parsed.document(), &mut writer, None, None, &mut diagnostics)?; + converter.write_to( + parsed.document(), + &mut writer, + Some(file), + None, + &mut diagnostics, + )?; // `parsed` drops here — output is already buffered into `writer`. deferred.push((parser_warnings, file.clone())); } diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index b05416aa7..96c4e286f 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Selected UTF-8 postprocessors can edit complete output in order before it reaches its destination. Conversions stream as usual when no matching processor is selected. + - Selected docinfo hooks can insert trusted fragments during conversion in registration order, with access to the current document attributes and diagnostics. - Block renderers can decline with a diagnostic before gaining access to output. An accepting renderer can delegate once and wrap the result. Package selection and registration order determine the chain. diff --git a/converters/core/Cargo.toml b/converters/core/Cargo.toml index 71f19f9e0..552da3073 100644 --- a/converters/core/Cargo.toml +++ b/converters/core/Cargo.toml @@ -21,6 +21,7 @@ thiserror.workspace = true tracing.workspace = true [dev-dependencies] +stats_alloc = "0.1" serde_json.workspace = true tempfile.workspace = true diff --git a/converters/core/src/lib.rs b/converters/core/src/lib.rs index 96e1b3780..fa6dba02c 100644 --- a/converters/core/src/lib.rs +++ b/converters/core/src/lib.rs @@ -57,6 +57,7 @@ pub mod link; pub mod list; pub mod media; pub mod pipeline; +pub mod postprocess; pub mod render; pub mod section; pub mod substitutions; @@ -661,6 +662,12 @@ pub trait Converter<'a>: Sized { #[must_use] fn name(&self) -> &'static str; + /// Whether completed output can be delivered to a selected UTF-8 text processor. + /// The default keeps opaque and binary converters on their own output paths. + fn supports_text_output(&self) -> bool { + false + } + /// Tag used on warnings emitted by this converter. /// /// The default uses [`Self::name`] verbatim, which suits backends with a @@ -709,47 +716,15 @@ pub trait Converter<'a>: Sized { source_file: Option<&Path>, output_path: &Path, ) -> Result { - let start = self.options().timings().then(Instant::now); - - if let Some(f) = source_file.filter(|_| self.options().timings()) { - println!("Input file: {}", f.display()); - } - - tracing::debug!( - source = ?source_file, - destination = ?output_path, - "converting document to {}", - self.name() - ); - - if let Some(parent) = output_path.parent() { - std::fs::create_dir_all(parent)?; - } - let file = std::fs::File::create(output_path)?; - let source = self.warning_source(); - let mut warnings = Vec::new(); - let mut diagnostics = Diagnostics::new(&source, &mut warnings); - self.write_to( - doc, - std::io::BufWriter::new(file), - source_file, - Some(output_path), - &mut diagnostics, - )?; - - if let Some(start) = start { - let elapsed = start.elapsed(); - tracing::debug!( - time = elapsed.format_human_with_precision(3), - source = ?source_file, - destination = ?output_path, - "time to convert document" - ); - println!(" Time to convert document: {}", elapsed.format_human()); - } - - println!("Generated {} file: {}", self.name(), output_path.display()); - Ok(ConversionResult::file(output_path.to_path_buf(), warnings)) + report_file_conversion(self, source_file, output_path, |diagnostics| { + self.write_to( + doc, + create_output(output_path)?, + source_file, + Some(output_path), + diagnostics, + ) + }) } /// Main entry point: route based on [`OutputDestination`]. @@ -782,6 +757,55 @@ pub trait Converter<'a>: Sized { } } +fn create_output(path: &Path) -> std::io::Result> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + Ok(std::io::BufWriter::new(std::fs::File::create(path)?)) +} + +fn report_file_conversion<'a, C: Converter<'a>>( + converter: &C, + source_file: Option<&Path>, + output_path: &Path, + write: impl FnOnce(&mut Diagnostics<'_>) -> Result<(), C::Error>, +) -> Result { + let start = converter.options().timings().then(Instant::now); + + if let Some(f) = source_file.filter(|_| converter.options().timings()) { + println!("Input file: {}", f.display()); + } + + tracing::debug!( + source = ?source_file, + destination = ?output_path, + "converting document to {}", + converter.name() + ); + + let source = converter.warning_source(); + let mut warnings = Vec::new(); + write(&mut Diagnostics::new(&source, &mut warnings))?; + + if let Some(start) = start { + let elapsed = start.elapsed(); + tracing::debug!( + time = elapsed.format_human_with_precision(3), + source = ?source_file, + destination = ?output_path, + "time to convert document" + ); + println!(" Time to convert document: {}", elapsed.format_human()); + } + + println!( + "Generated {} file: {}", + converter.name(), + output_path.display() + ); + Ok(ConversionResult::file(output_path.to_path_buf(), warnings)) +} + /// Walk the error source chain to find a parser error. /// /// This utility function searches through the error chain looking for diff --git a/converters/core/src/pipeline.rs b/converters/core/src/pipeline.rs index c071835e1..4806a7557 100644 --- a/converters/core/src/pipeline.rs +++ b/converters/core/src/pipeline.rs @@ -45,7 +45,10 @@ use std::{ use acdc_parser::{Error, ParseResult, ast::DocumentRef}; -use crate::{ConversionResult, Converter, Diagnostics, display}; +use crate::{ + ConversionResult, Converter, Diagnostics, display, + postprocess::{PostprocessContext, PostprocessError}, +}; mod extensions; mod registrations; @@ -68,6 +71,7 @@ impl Pipeline { parser: None, renderers: Vec::new(), docinfo: Vec::new(), + postprocessors: Vec::new(), }, } } @@ -149,6 +153,62 @@ impl<'options, C: Converter<'options>> Pipeline { } } + fn has_postprocessors(&self) -> bool { + self.extensions + .postprocessors(self.converter.name()) + .next() + .is_some() + } + + fn completed_text( + &self, + document: DocumentRef<'_>, + source_file: Option<&Path>, + output_path: Option<&Path>, + diagnostics: &mut Diagnostics<'_>, + ) -> Result { + use std::io::{Error as IoError, ErrorKind}; + + let backend = self.converter.name(); + if !self.converter.supports_text_output() { + return Err(IoError::new( + ErrorKind::Unsupported, + PostprocessError::Unsupported(backend), + ) + .into()); + } + let prepared = self.prepare(document, diagnostics)?; + let context = PostprocessContext { + backend, + document: prepared.document(), + source_file, + output_path, + }; + let mut bytes = Vec::new(); + self.converter.write_to_with_extensions( + context.document, + &mut bytes, + source_file, + output_path, + &self.extensions, + diagnostics, + )?; + let mut text = String::from_utf8(bytes).map_err(|e| { + IoError::new( + ErrorKind::InvalidData, + PostprocessError::InvalidText { + backend, + source: e.utf8_error(), + }, + ) + })?; + for processor in self.extensions.postprocessors(backend) { + (processor.process)(&mut text, context, diagnostics) + .map_err(|source| IoError::other(PostprocessError::Callback { backend, source }))?; + } + Ok(text) + } + /// Resolve display content and write one conversion with structured diagnostics. /// /// # Errors @@ -156,11 +216,16 @@ impl<'options, C: Converter<'options>> Pipeline { pub fn write_to( &self, document: DocumentRef<'_>, - writer: impl Write, + mut writer: impl Write, source_file: Option<&Path>, output_path: Option<&Path>, diagnostics: &mut Diagnostics<'_>, ) -> Result<(), C::Error> { + if self.has_postprocessors() { + let text = self.completed_text(document, source_file, output_path, diagnostics)?; + writer.write_all(text.as_bytes())?; + return Ok(writer.flush()?); + } let prepared = self.prepare(document, diagnostics)?; self.converter.write_to_with_extensions( prepared.document(), @@ -182,15 +247,25 @@ impl<'options, C: Converter<'options>> Pipeline { document: DocumentRef<'_>, source_file: Option<&Path>, ) -> Result { - if self.converter.uses_render_extensions(&self.extensions) { + if self.has_postprocessors() || self.converter.uses_render_extensions(&self.extensions) { return >::convert(self, document, source_file); } + self.convert_prepared(document, |prepared| { + self.converter.convert(prepared, source_file) + }) + } + + fn convert_prepared( + &self, + document: DocumentRef<'_>, + convert: impl FnOnce(DocumentRef<'_>) -> Result, + ) -> Result { let mut warnings = Vec::new(); let prepared = self.prepare( document, &mut Diagnostics::new(&self.converter.warning_source(), &mut warnings), )?; - let mut result = self.converter.convert(prepared.document(), source_file)?; + let mut result = convert(prepared.document())?; if !warnings.is_empty() { warnings.append(&mut result.warnings); result.warnings = warnings; @@ -223,6 +298,48 @@ impl<'options, C: Converter<'options>> Converter<'options> for Pipeline { fn name(&self) -> &'static str { self.converter.name() } + fn supports_text_output(&self) -> bool { + self.converter.supports_text_output() + } + + fn convert_to_file( + &self, + doc: DocumentRef<'_>, + source_file: Option<&Path>, + output_path: &Path, + ) -> Result { + let postprocess = self.has_postprocessors(); + if !postprocess && !self.converter.uses_render_extensions(&self.extensions) { + return self.convert_prepared(doc, |prepared| { + self.converter + .convert_to_file(prepared, source_file, output_path) + }); + } + crate::report_file_conversion(self, source_file, output_path, |diagnostics| { + if postprocess { + // Renderers may place companion files beside the final output. + if self.converter.supports_text_output() + && let Some(parent) = output_path.parent() + { + std::fs::create_dir_all(parent)?; + } + let text = self.completed_text(doc, source_file, Some(output_path), diagnostics)?; + let mut writer = crate::create_output(output_path)?; + writer.write_all(text.as_bytes())?; + writer.flush()?; + Ok(()) + } else { + self.write_to( + doc, + crate::create_output(output_path)?, + source_file, + Some(output_path), + diagnostics, + ) + } + }) + } + fn warning_source(&self) -> crate::WarningSource { self.converter.warning_source() } diff --git a/converters/core/src/pipeline/extensions.rs b/converters/core/src/pipeline/extensions.rs index 40e7b0cd0..e72a17fdf 100644 --- a/converters/core/src/pipeline/extensions.rs +++ b/converters/core/src/pipeline/extensions.rs @@ -78,6 +78,7 @@ impl ExtensionCatalog { let mut builder = Registry::builder(); let mut active = false; let mut renderers = Vec::new(); + let mut postprocessors = Vec::new(); let mut docinfo = Vec::new(); for name in names { let (name, registrations) = self @@ -96,6 +97,7 @@ impl ExtensionCatalog { })?; active = true; } + postprocessors.extend(registrations.postprocessors.iter().cloned()); docinfo.extend(registrations.docinfo.iter().cloned()); renderers.extend(registrations.renderers.iter().cloned()); } @@ -103,6 +105,7 @@ impl ExtensionCatalog { parser: active.then(|| builder.build()), renderers, docinfo, + postprocessors, }; Ok((!extensions.is_empty()).then_some(extensions)) } diff --git a/converters/core/src/pipeline/registrations.rs b/converters/core/src/pipeline/registrations.rs index 05a82f959..3bd9a0661 100644 --- a/converters/core/src/pipeline/registrations.rs +++ b/converters/core/src/pipeline/registrations.rs @@ -2,6 +2,7 @@ use acdc_parser::extensions::Registry; use crate::{ docinfo::{DocinfoHook, DocinfoProcessor}, + postprocess::TextPostprocessor, render::{BlockRenderer, RenderSession}, }; @@ -10,6 +11,7 @@ use crate::{ #[derive(Clone, Debug, Default)] pub struct Extensions { pub(super) parser: Option, + pub(super) postprocessors: Vec, pub(super) docinfo: Vec, pub(super) renderers: Vec, } @@ -20,6 +22,7 @@ impl From for Extensions { parser: (!registry.is_empty()).then_some(registry), renderers: Vec::new(), docinfo: Vec::new(), + postprocessors: Vec::new(), } } } @@ -32,6 +35,20 @@ impl Extensions { self } + /// Append a completed-text callback. Matching callbacks edit the same string + /// in package selection and registration order. + #[must_use] + pub fn with_postprocessor(mut self, processor: TextPostprocessor) -> Self { + self.postprocessors.push(processor); + self + } + + pub(super) fn postprocessors(&self, backend: &str) -> impl Iterator { + self.postprocessors + .iter() + .filter(move |p| p.backend == backend) + } + /// Append a docinfo hook. At each insertion point hooks run in selection /// and registration order, following any file-based docinfo. #[must_use] @@ -66,7 +83,10 @@ impl Extensions { /// Whether this collection has no parser or rendering capabilities. #[must_use] pub fn is_empty(&self) -> bool { - self.parser.is_none() && self.renderers.is_empty() && self.docinfo.is_empty() + self.parser.is_none() + && self.renderers.is_empty() + && self.docinfo.is_empty() + && self.postprocessors.is_empty() } /// Trusted script hashes requested by selected HTML block renderers. diff --git a/converters/core/src/postprocess.rs b/converters/core/src/postprocess.rs new file mode 100644 index 000000000..bee2ee8ac --- /dev/null +++ b/converters/core/src/postprocess.rs @@ -0,0 +1,93 @@ +//! Ordered transformations of one completed UTF-8 document. +//! +//! Selected hooks edit the rendered text in place after all docinfo insertions. +//! Register against the converter name: `html`, `html5s`, `markdown`, `manpage`, +//! or `terminal`. Both Markdown variants use `markdown`. Other converters can opt +//! in through [`crate::Converter::supports_text_output`]. +//! If rendering or a callback fails, the pipeline discards the text before writing +//! the destination. Earlier diagnostics, companion files and other external effects +//! persist. Once writing starts, ordinary destination I/O errors may leave partial output. + +use std::{fmt, path::Path, sync::Arc}; + +use acdc_parser::ast::DocumentRef; + +use crate::{Diagnostics, render::RenderError}; + +/// The converter and paths used for this document. Streams can have no path. +#[derive(Clone, Copy)] +pub struct PostprocessContext<'a> { + /// Configured converter name. + pub backend: &'static str, + /// Document used to generate the text. + pub document: DocumentRef<'a>, + /// Input file when available. + pub source_file: Option<&'a Path>, + /// Final file destination when available. + pub output_path: Option<&'a Path>, +} + +/// Error carried by the converter's I/O error when postprocessing fails. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum PostprocessError { + /// The backend has not opted into completed UTF-8 output. + #[error("backend '{0}' does not support text postprocessing")] + Unsupported(&'static str), + /// A backend that opted into UTF-8 produced invalid bytes. + #[error("invalid UTF-8 from backend '{backend}': {source}")] + InvalidText { + /// Configured converter name. + backend: &'static str, + /// Invalid byte position. + source: std::str::Utf8Error, + }, + /// A selected callback failed before output was delivered. + #[error("postprocessor for '{backend}' failed: {source}")] + Callback { + /// Configured converter name. + backend: &'static str, + /// Original callback failure. + source: RenderError, + }, +} + +type Callback = dyn Fn(&mut String, PostprocessContext<'_>, &mut Diagnostics<'_>) -> Result<(), RenderError> + + Send + + Sync; + +/// A callback for one named backend. The pipeline calls it once per document. +/// Local variables are per call; explicitly captured shared state belongs to the author. +#[derive(Clone)] +pub struct TextPostprocessor { + pub(crate) backend: &'static str, + pub(crate) process: Arc, +} + +impl fmt::Debug for TextPostprocessor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TextPostprocessor") + .field("backend", &self.backend) + .finish_non_exhaustive() + } +} + +impl TextPostprocessor { + /// Register a complete-text transformation without executing it. + pub fn new( + backend: &'static str, + process: impl Fn( + &mut String, + PostprocessContext<'_>, + &mut Diagnostics<'_>, + ) -> Result<(), RenderError> + + Send + + Sync + + 'static, + ) -> Self { + Self { + backend, + process: Arc::new(process), + } + } +} diff --git a/converters/core/tests/postprocessing.rs b/converters/core/tests/postprocessing.rs new file mode 100644 index 000000000..c211b7442 --- /dev/null +++ b/converters/core/tests/postprocessing.rs @@ -0,0 +1,207 @@ +//! Check delivery boundaries and measure the output buffer independently of parser allocations. +use acdc_converters_core::{ + Converter, Diagnostics, Options, OutputDestination, + pipeline::{ExtensionCatalog, Extensions, Pipeline}, + postprocess::{PostprocessError, TextPostprocessor}, +}; +use acdc_parser::{Options as ParserOptions, OptionsBuilder, ast::DocumentRef}; +use stats_alloc::{INSTRUMENTED_SYSTEM, Region, StatsAlloc}; +use std::{ + alloc::System, + io::{self, Write}, + path::{Path, PathBuf}, +}; + +#[global_allocator] +static ALLOCATOR: &StatsAlloc = &INSTRUMENTED_SYSTEM; + +type TestResult = Result<(), Box>; +#[derive(Debug, thiserror::Error)] +enum Error { + #[error(transparent)] + Parser(#[from] acdc_parser::Error), + #[error(transparent)] + Io(#[from] io::Error), +} +struct Chunked { + options: Options, + parser: ParserOptions<'static>, + utf8: bool, + chunk: &'static [u8], +} +impl Converter<'static> for Chunked { + type Error = Error; + fn new(options: Options, parser: OptionsBuilder<'static>) -> Result { + Ok(Self { + options, + parser: parser.build()?, + utf8: true, + chunk: &[b'x'; 1024], + }) + } + fn options(&self) -> &Options { + &self.options + } + fn parser_options(&self) -> &ParserOptions<'static> { + &self.parser + } + fn name(&self) -> &'static str { + "chunked" + } + fn supports_text_output(&self) -> bool { + self.utf8 + } + fn derive_output_path(&self, _: &Path, _: DocumentRef<'_>) -> Result, Error> { + Ok(None) + } + fn write_to( + &self, + _: DocumentRef<'_>, + mut writer: W, + _: Option<&Path>, + _: Option<&Path>, + _: &mut Diagnostics<'_>, + ) -> Result<(), Error> { + for _ in 0..64 { + writer.write_all(self.chunk)?; + } + Ok(()) + } +} +#[derive(Default)] +struct Sink { + writes: usize, + bytes: usize, +} +impl Write for Sink { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.writes += 1; + self.bytes += bytes.len(); + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn only_selected_postprocessors_allocate_a_complete_output_buffer() -> TestResult { + let mut catalog = ExtensionCatalog::default(); + for name in ["first", "second"] { + catalog.register( + name, + Extensions::default().with_postprocessor(TextPostprocessor::new( + "chunked", + move |text, ctx, diag| { + assert_eq!(ctx.backend, "chunked"); + assert!(ctx.source_file.is_none() && ctx.output_path.is_none()); + if name == "first" { + assert_eq!(text.len(), 65_536); + text.truncate(1); + } else { + assert_eq!(text, "x"); + diag.warn("completed"); + } + Ok(()) + }, + )), + )?; + } + let wrong = Extensions::default() + .with_postprocessor(TextPostprocessor::new("other", |_, _, _| { + Err("unexpected callback".into()) + })); + for (extensions, active) in [ + (Extensions::default(), false), + (wrong, false), + ( + catalog + .select(["first", "second", "first"])? + .ok_or("missing selection")?, + true, + ), + ] { + let backend = Chunked::new(Options::default(), ParserOptions::builder())?; + let pipeline = Pipeline::new(backend).with_extensions(extensions); + let parsed = pipeline.parse("hello")?; + for _ in 0..2 { + let mut sink = Sink::default(); + let mut warnings = Vec::new(); + let source = pipeline.warning_source(); + let region = Region::new(ALLOCATOR); + pipeline.write_to( + parsed.document(), + &mut sink, + None, + None, + &mut Diagnostics::new(&source, &mut warnings), + )?; + let allocated = region.change().bytes_allocated; + if active { + assert_eq!((sink.writes, sink.bytes, warnings.len()), (1, 1, 1)); + assert!(allocated >= 65_536, "{allocated}"); + } else { + assert_eq!((sink.writes, sink.bytes, warnings.len()), (64, 65_536, 0)); + assert!(allocated < 4096, "{allocated}"); + } + eprintln!("active={active}, allocated={allocated}"); + } + } + output_errors_keep_existing_files_and_skip_later_processors() +} + +fn output_errors_keep_existing_files_and_skip_later_processors() -> TestResult { + let dir = tempfile::tempdir()?; + let path = dir.path().join("out"); + let input = dir.path().join("source.adoc"); + for (supported, valid) in [(false, true), (true, false), (true, true)] { + let mut backend = Chunked::new( + Options::builder() + .output_destination(OutputDestination::File(path.clone())) + .build(), + ParserOptions::builder(), + )?; + backend.utf8 = supported; + if !valid { + backend.chunk = b"\xff"; + } + let processors = Extensions::default() + .with_postprocessor(TextPostprocessor::new("chunked", |_, ctx, _| { + assert!(ctx.source_file.is_some_and(|p| p.ends_with("source.adoc"))); + assert!(ctx.output_path.is_some_and(|p| p.ends_with("out"))); + Err("failed".into()) + })) + .with_postprocessor(TextPostprocessor::new("chunked", |_, _, _| { + Err("unexpected later callback".into()) + })); + let pipeline = Pipeline::new(backend).with_extensions(processors); + let parsed = pipeline.parse("test")?; + for exists in [false, true] { + if exists { + std::fs::write(&path, "original")?; + } + let Err(Error::Io(e)) = pipeline.convert(parsed.document(), Some(&input)) else { + return Err("missing output error".into()); + }; + let error = e + .get_ref() + .and_then(|e| e.downcast_ref::()) + .ok_or("missing postprocessor error")?; + match (supported, valid, error) { + (false, _, PostprocessError::Unsupported("chunked")) + | (true, false, PostprocessError::InvalidText { .. }) => (), + (true, true, PostprocessError::Callback { source, .. }) => { + assert_eq!(source.to_string(), "failed"); + } + _ => return Err(format!("unexpected error {error}").into()), + } + if exists { + assert_eq!(std::fs::read_to_string(&path)?, "original"); + std::fs::remove_file(&path)?; + } else { + assert!(!path.exists()); + } + } + } + Ok(()) +} diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index 19786dfbe..72e6b97da 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Selected text postprocessors can transform a complete HTML document or embedded fragment after rendering. + - Full HTML documents accept native docinfo fragments at the end of the head, start of the body, and after the footer. Embedded HTML skips these hooks. - Native renderers can decorate paragraphs, listings, and literal blocks while retaining the selected HTML variant’s built-in rendering. diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index 6585b7bab..79e244c2e 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -608,6 +608,10 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { Ok(()) } + fn supports_text_output(&self) -> bool { + true + } + fn name(&self) -> &'static str { match self.variant { HtmlVariant::Semantic => "html5s", diff --git a/converters/manpage/CHANGELOG.md b/converters/manpage/CHANGELOG.md index 8c1445241..f9659e45b 100644 --- a/converters/manpage/CHANGELOG.md +++ b/converters/manpage/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Selected text postprocessors can transform a completed manpage before delivery. + - Extension-generated caption and captured-title links now use explicit labels, preserving title formatting and source attributes while following final captions and renamed targets. Repeated conversion preserves the shared parsed document. diff --git a/converters/manpage/src/lib.rs b/converters/manpage/src/lib.rs index 4ae83e7d3..8ed452ed9 100644 --- a/converters/manpage/src/lib.rs +++ b/converters/manpage/src/lib.rs @@ -225,6 +225,10 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { self.write_document(doc, writer, source_file, diagnostics) } + fn supports_text_output(&self) -> bool { + true + } + fn name(&self) -> &'static str { "manpage" } diff --git a/converters/markdown/CHANGELOG.md b/converters/markdown/CHANGELOG.md index 2aa9bdc89..eca804ca0 100644 --- a/converters/markdown/CHANGELOG.md +++ b/converters/markdown/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Selected text postprocessors can transform the completed Markdown for either variant. + - Extension-generated caption and captured-title links now use explicit labels, preserving title formatting and source attributes while following final captions and renamed targets. Repeated conversion preserves the shared parsed document. diff --git a/converters/markdown/src/lib.rs b/converters/markdown/src/lib.rs index e73683053..1becaa26c 100644 --- a/converters/markdown/src/lib.rs +++ b/converters/markdown/src/lib.rs @@ -380,6 +380,10 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { visitor.visit_document(&mut traversal, doc) } + fn supports_text_output(&self) -> bool { + true + } + fn name(&self) -> &'static str { "markdown" } diff --git a/converters/terminal/CHANGELOG.md b/converters/terminal/CHANGELOG.md index ee90e26af..b9cdfa9ba 100644 --- a/converters/terminal/CHANGELOG.md +++ b/converters/terminal/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Selected text postprocessors can transform the completed terminal output for each document, including documents sent to a pager. + - Extension-generated caption and captured-title links now use explicit labels, preserving title formatting and source attributes while following final captions and renamed targets. Repeated conversion preserves the shared parsed document. diff --git a/converters/terminal/src/lib.rs b/converters/terminal/src/lib.rs index 23e8b3630..c122a9157 100644 --- a/converters/terminal/src/lib.rs +++ b/converters/terminal/src/lib.rs @@ -213,6 +213,10 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { visitor.visit_document(&mut traversal, document) } + fn supports_text_output(&self) -> bool { + true + } + fn name(&self) -> &'static str { "terminal" } From b16ab8bf069d401e4af936e1b9bb40d4149520c3 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 08:58:38 +0100 Subject: [PATCH 48/55] feat(converters): register backend names and typed variants before parsing --- converters/core/CHANGELOG.md | 2 + converters/core/src/lib.rs | 1 + converters/core/src/registry.rs | 362 +++++++++++++++++++++++++++++++ converters/html/CHANGELOG.md | 2 + converters/html/src/lib.rs | 21 +- converters/manpage/CHANGELOG.md | 2 + converters/manpage/src/lib.rs | 5 +- converters/markdown/CHANGELOG.md | 2 + converters/markdown/src/lib.rs | 24 +- converters/pdf/CHANGELOG.md | 2 + converters/pdf/src/lib.rs | 5 + converters/terminal/CHANGELOG.md | 2 + converters/terminal/src/lib.rs | 6 +- 13 files changed, 432 insertions(+), 4 deletions(-) create mode 100644 converters/core/src/registry.rs diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index 96c4e286f..da3d86bdb 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Applications can register statically linked converters, resolve names and variants before parsing, and explicitly replace a registration. + - Selected UTF-8 postprocessors can edit complete output in order before it reaches its destination. Conversions stream as usual when no matching processor is selected. - Selected docinfo hooks can insert trusted fragments during conversion in registration order, with access to the current document attributes and diagnostics. diff --git a/converters/core/src/lib.rs b/converters/core/src/lib.rs index fa6dba02c..f1cb75051 100644 --- a/converters/core/src/lib.rs +++ b/converters/core/src/lib.rs @@ -58,6 +58,7 @@ pub mod list; pub mod media; pub mod pipeline; pub mod postprocess; +pub mod registry; pub mod render; pub mod section; pub mod substitutions; diff --git a/converters/core/src/registry.rs b/converters/core/src/registry.rs new file mode 100644 index 000000000..c590f3925 --- /dev/null +++ b/converters/core/src/registry.rs @@ -0,0 +1,362 @@ +//! Select a statically linked converter before constructing its pipeline. +//! +//! A converter owns its public names and typed variants. The application binds each +//! choice to a factory or runner, then resolves the user's selection before reading +//! input. Only the selected runner constructs a converter. Its [`crate::BackendProfile`] +//! supplies parser attributes and its [`crate::ConversionResult`] reports the actual +//! destination after rendering. +//! +//! ``` +//! use acdc_converters_core::registry::{ConverterRegistry, ConverterSpec}; +//! let mut registry = ConverterRegistry::default(); +//! registry.register(ConverterSpec::new("text", ()).with_aliases(&["txt"]), |()| str::to_uppercase)?; +//! let uppercase = registry.resolve("txt", None)?; +//! assert_eq!(uppercase("Hello"), "HELLO"); +//! # Ok::<(), acdc_converters_core::registry::SelectionError>(()) +//! ``` +use std::collections::{BTreeMap, BTreeSet}; + +/// A public variant spelling and its converter-owned typed value. +#[derive(Clone, Copy, Debug)] +pub struct Variant { + /// Canonical variant name. + pub name: &'static str, + /// Alternate spellings accepted as variants. + pub aliases: &'static [&'static str], + /// Legacy backend name selecting just this variant, if any. + pub shortcut: Option<&'static str>, + /// Typed choice passed to the application adapter. + pub value: V, +} + +/// Names by which applications can select a statically linked converter. +#[derive(Clone, Copy, Debug)] +pub struct ConverterSpec { + name: &'static str, + aliases: &'static [&'static str], + default: V, + variants: &'static [Variant], +} + +impl ConverterSpec { + /// Declare a backend with its default choice. A plain backend uses `()`. + pub const fn new(name: &'static str, default: V) -> Self { + Self { + name, + default, + aliases: &[], + variants: &[], + } + } + + /// Accept alternative names with the same variant selection as the canonical name. + #[must_use] + pub const fn with_aliases(mut self, aliases: &'static [&'static str]) -> Self { + self.aliases = aliases; + self + } + + /// Declare all explicit variant choices, including the default. + #[must_use] + pub const fn with_variants(mut self, variants: &'static [Variant]) -> Self { + self.variants = variants; + self + } +} + +/// Registration and selection errors are reported before input processing. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +#[non_exhaustive] +pub enum SelectionError { + /// A backend or alias is already claimed. + #[error("backend name '{0}' is already registered")] + Conflict(&'static str), + /// A registration has an ambiguous variant namespace or an invalid name/default. + #[error("invalid registration for backend '{0}': {1}")] + Invalid(&'static str, &'static str), + /// No backend or alias matches this spelling. + #[error("backend '{0}' is not available")] + Unavailable(String), + /// A plain backend or fixed shortcut does not allow an explicit variant. + #[error("backend '{0}' does not accept a variant")] + NoVariants(String), + /// A variant belongs to another backend or has an unknown spelling. + #[error("variant '{variant}' is not supported by backend '{backend}'")] + UnsupportedVariant { + /// Canonical backend. + backend: &'static str, + /// Requested variant. + variant: String, + }, +} + +struct Family { + default: T, + // An explicit spelling of the default reuses its adapter. + variants: BTreeMap<&'static str, Option>, + variant_aliases: BTreeMap<&'static str, &'static str>, +} + +/// A checked registry of application adapters. Resolution borrows the selected +/// adapter. Writes require exclusive access and leave existing entries intact on error. +pub struct ConverterRegistry { + families: BTreeMap<&'static str, Family>, + // Every public backend spelling resolves to its family and optional fixed variant. + names: BTreeMap<&'static str, (&'static str, Option<&'static str>)>, +} + +impl Default for ConverterRegistry { + fn default() -> Self { + Self { + families: BTreeMap::new(), + names: BTreeMap::new(), + } + } +} + +impl ConverterRegistry { + /// Register a converter, rejecting collisions with every existing name or alias. + /// Bindings should describe how to run a choice without starting a conversion. + /// + /// # Errors + /// Returns a conflict or invalid specification without changing the registry. + pub fn register( + &mut self, + spec: ConverterSpec, + bind: impl Fn(V) -> T, + ) -> Result<(), SelectionError> { + self.install(spec, bind, false) + } + + /// Replace the family with this canonical name, retiring its former aliases. + /// + /// # Errors + /// Rejects unknown families and alias collisions, preserving the prior registration. + pub fn replace( + &mut self, + spec: ConverterSpec, + bind: impl Fn(V) -> T, + ) -> Result<(), SelectionError> { + if !self.families.contains_key(spec.name) { + return Err(SelectionError::Unavailable(spec.name.to_owned())); + } + self.install(spec, bind, true) + } + + fn install( + &mut self, + spec: ConverterSpec, + bind: impl Fn(V) -> T, + replace: bool, + ) -> Result<(), SelectionError> { + let canonical = spec.name; + let names = std::iter::once((canonical, None)) + .chain(spec.aliases.iter().map(|&name| (name, None))) + .chain( + spec.variants + .iter() + .filter_map(|v| Some((v.shortcut?, Some(v.name)))), + ); + let mut additions = BTreeMap::new(); + for (name, fixed) in names { + if name.is_empty() { + return Err(SelectionError::Invalid(canonical, "empty backend name")); + } + if additions.insert(name, (canonical, fixed)).is_some() + || self + .names + .get(name) + .is_some_and(|&(owner, _)| !replace || owner != canonical) + { + return Err(SelectionError::Conflict(name)); + } + } + let mut spellings = BTreeSet::new(); + for variant in spec.variants { + for name in std::iter::once(&variant.name).chain(variant.aliases) { + if name.is_empty() || !spellings.insert(*name) { + return Err(SelectionError::Invalid( + canonical, + "empty or duplicate variant spelling", + )); + } + } + } + if !spec.variants.is_empty() && !spec.variants.iter().any(|v| v.value == spec.default) { + return Err(SelectionError::Invalid( + canonical, + "default variant is missing", + )); + } + let family = Family { + default: bind(spec.default), + variants: spec + .variants + .iter() + .map(|v| (v.name, (v.value != spec.default).then(|| bind(v.value)))) + .collect(), + variant_aliases: spec + .variants + .iter() + .flat_map(|v| v.aliases.iter().map(|&alias| (alias, v.name))) + .collect(), + }; + if replace { + self.names.retain(|_, (owner, _)| *owner != canonical); + } + self.names.extend(additions); + self.families.insert(canonical, family); + Ok(()) + } + + /// Available canonical backend names, aliases, and shortcuts in lexical order. + pub fn names(&self) -> impl Iterator + '_ { + self.names.keys().copied() + } + + /// Backend spellings for command-line help. Plain aliases are accepted but hidden. + pub fn backend_spellings(&self) -> impl Iterator + '_ { + self.names + .iter() + .map(|(&name, &(canonical, fixed))| (name, name == canonical || fixed.is_some())) + } + + /// All variant spellings and whether each has a canonical use in the registry. + pub fn variant_spellings(&self) -> impl Iterator { + let mut names = BTreeMap::new(); + for family in self.families.values() { + for &alias in family.variant_aliases.keys() { + names.entry(alias).or_insert(false); + } + for &name in family.variants.keys() { + names.insert(name, true); + } + } + names.into_iter() + } + + /// Resolve a backend and optional variant. Fixed shortcuts reject another variant. + /// + /// # Errors + /// Reports an unavailable backend or incompatible variant. + pub fn resolve(&self, name: &str, variant: Option<&str>) -> Result<&T, SelectionError> { + let &(canonical, fixed) = self + .names + .get(name) + .ok_or_else(|| SelectionError::Unavailable(name.to_owned()))?; + let family = self + .families + .get(canonical) + .ok_or_else(|| SelectionError::Unavailable(name.to_owned()))?; + if variant.is_some() && (fixed.is_some() || family.variants.is_empty()) { + return Err(SelectionError::NoVariants(name.to_owned())); + } + let Some(requested) = fixed.or(variant) else { + return Ok(&family.default); + }; + let key = family + .variant_aliases + .get(requested) + .copied() + .unwrap_or(requested); + family + .variants + .get(key) + .map(|adapter| adapter.as_ref().unwrap_or(&family.default)) + .ok_or_else(|| SelectionError::UnsupportedVariant { + backend: canonical, + variant: requested.to_owned(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FORMAT: ConverterSpec = ConverterSpec::new("format", false) + .with_aliases(&["f"]) + .with_variants(&[ + Variant { + name: "standard", + aliases: &[], + shortcut: None, + value: false, + }, + Variant { + name: "alternate", + aliases: &["alt"], + shortcut: Some("format2"), + value: true, + }, + ]); + + #[test] + fn registered_names_select_one_adapter_per_choice() -> Result<(), SelectionError> { + let mut catalog = ConverterRegistry::default(); + let calls = std::cell::Cell::new(0); + catalog.register(FORMAT, |choice| { + calls.set(calls.get() + 1); + choice + })?; + assert_eq!(calls.get(), 2); + assert!(std::ptr::eq( + catalog.resolve("f", None)?, + catalog.resolve("format", Some("standard"))? + )); + assert!(std::ptr::eq( + catalog.resolve("format2", None)?, + catalog.resolve("f", Some("alt"))? + )); + assert_eq!( + catalog.resolve("format2", Some("alt")), + Err(SelectionError::NoVariants("format2".into())) + ); + assert!(matches!( + catalog.resolve("format", Some("other")), + Err(SelectionError::UnsupportedVariant { + backend: "format", + .. + }) + )); + Ok(()) + } + + #[test] + fn replacement_retires_aliases_and_rejected_updates_are_atomic() -> Result<(), SelectionError> { + let mut catalog = ConverterRegistry::default(); + catalog.register(FORMAT, |x| x)?; + let other = ConverterSpec::new("other", ()); + catalog.register(other, |()| false)?; + assert_eq!( + catalog.register(other.with_aliases(&["f"]), |()| true), + Err(SelectionError::Conflict("other")) + ); + assert_eq!( + catalog.replace(other.with_aliases(&["format2"]), |()| true), + Err(SelectionError::Conflict("format2")) + ); + assert!(matches!( + catalog.register( + ConverterSpec::new("third", ()).with_aliases(&["third"]), + |()| false + ), + Err(SelectionError::Conflict("third")) + )); + assert_eq!(catalog.resolve("format2", None), Ok(&true)); + catalog.replace( + ConverterSpec::new("format", false).with_aliases(&["new"]), + |x| x, + )?; + assert!(matches!( + catalog.resolve("f", None), + Err(SelectionError::Unavailable(_)) + )); + assert!(matches!( + catalog.resolve("format2", None), + Err(SelectionError::Unavailable(_)) + )); + assert_eq!(catalog.resolve("new", None), Ok(&false)); + Ok(()) + } +} diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index 72e6b97da..6ca485157 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Applications can register this converter using its built-in backend names and variant choices. + - Selected text postprocessors can transform a complete HTML document or embedded fragment after rendering. - Full HTML documents accept native docinfo fragments at the end of the head, start of the body, and after the footer. Embedded HTML skips these hooks. diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index 79e244c2e..7f2f36fc9 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -11,7 +11,9 @@ use std::{ use acdc_converters_core::substitutions::TextBoundaries; use acdc_converters_core::{ BackendProfile, Converter as _, Diagnostics, Options, TraversalContext, WarningSource, - section::contains_index_section, xref::XrefGuard, + registry::{ConverterSpec, Variant}, + section::contains_index_section, + xref::XrefGuard, }; use acdc_parser::{ @@ -29,6 +31,23 @@ use acdc_parser::{ ast::{InlineKind, InlineRef}, }; +/// Static backend selection offered to applications before parsing. +pub const REGISTRATION: ConverterSpec = + ConverterSpec::new("html", HtmlVariant::Standard).with_variants(&[ + Variant { + name: "standard", + aliases: &[], + shortcut: None, + value: HtmlVariant::Standard, + }, + Variant { + name: "semantic", + aliases: &[], + shortcut: Some("html5s"), + value: HtmlVariant::Semantic, + }, + ]); + mod admonition; mod audio; mod callouts; diff --git a/converters/manpage/CHANGELOG.md b/converters/manpage/CHANGELOG.md index f9659e45b..9c036e624 100644 --- a/converters/manpage/CHANGELOG.md +++ b/converters/manpage/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Applications can register this converter using its built-in backend names and variant choices. + - Selected text postprocessors can transform a completed manpage before delivery. - Extension-generated caption and captured-title links now use explicit labels, diff --git a/converters/manpage/src/lib.rs b/converters/manpage/src/lib.rs index 8ed452ed9..c339b5db0 100644 --- a/converters/manpage/src/lib.rs +++ b/converters/manpage/src/lib.rs @@ -41,7 +41,7 @@ use std::{ }; use acdc_converters_core::{ - BackendProfile, Diagnostics, Doctype, Options, TraversalContext, + BackendProfile, Diagnostics, Doctype, Options, TraversalContext, registry::ConverterSpec, section::contains_index_section, visitor::DocumentVisitor, xref::XrefGuard, }; @@ -50,6 +50,9 @@ use acdc_parser::{ ast::{DocumentRef, TocEntryRef}, }; +/// Static backend selection offered to applications before parsing. +pub const REGISTRATION: ConverterSpec<()> = ConverterSpec::new("manpage", ()); + mod admonition; mod delimited; mod document; diff --git a/converters/markdown/CHANGELOG.md b/converters/markdown/CHANGELOG.md index eca804ca0..ca46f883e 100644 --- a/converters/markdown/CHANGELOG.md +++ b/converters/markdown/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Applications can register this converter using its built-in backend names and variant choices. + - Selected text postprocessors can transform the completed Markdown for either variant. - Extension-generated caption and captured-title links now use explicit labels, diff --git a/converters/markdown/src/lib.rs b/converters/markdown/src/lib.rs index 1becaa26c..8490a893e 100644 --- a/converters/markdown/src/lib.rs +++ b/converters/markdown/src/lib.rs @@ -111,13 +111,35 @@ use std::{ use acdc_converters_core::{ BackendProfile, Diagnostics, Options, TraversalContext, WarningSource, - section::contains_index_section, visitor::DocumentVisitor, xref::XrefGuard, + registry::{ConverterSpec, Variant}, + section::contains_index_section, + visitor::DocumentVisitor, + xref::XrefGuard, }; use acdc_parser::{ CaptionKind, Options as ParserOptions, ReferenceTarget, ast::{AttributesRef, CaptionRef, DocumentAttributesRef, DocumentRef}, }; +/// Static backend selection offered to applications before parsing. +pub const REGISTRATION: ConverterSpec = + ConverterSpec::new("markdown", MarkdownVariant::GitHubFlavored) + .with_aliases(&["md"]) + .with_variants(&[ + Variant { + name: "commonmark", + aliases: &["cm"], + shortcut: None, + value: MarkdownVariant::CommonMark, + }, + Variant { + name: "gfm", + aliases: &["github", "github-flavored"], + shortcut: None, + value: MarkdownVariant::GitHubFlavored, + }, + ]); + mod error; mod index; mod markdown_visitor; diff --git a/converters/pdf/CHANGELOG.md b/converters/pdf/CHANGELOG.md index b9276cc0b..685b26c71 100644 --- a/converters/pdf/CHANGELOG.md +++ b/converters/pdf/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Applications can register this converter using its built-in backend names and variant choices. + - Extension-generated caption and captured-title links now use explicit labels, preserving title formatting and source attributes while following final captions and renamed targets. Repeated conversion preserves the shared parsed document. diff --git a/converters/pdf/src/lib.rs b/converters/pdf/src/lib.rs index 4c4fcaf8f..1a0046c83 100644 --- a/converters/pdf/src/lib.rs +++ b/converters/pdf/src/lib.rs @@ -27,6 +27,7 @@ use acdc_converters_core::{ IconMode, custom_image_source as admonition_icon_source, image_source as icon_image_source, }, media::resolve_target, + registry::ConverterSpec, toc::Config as TocConfig, visitor::{BlockVisitor, DocumentVisitor}, xref::XrefGuard, @@ -49,6 +50,10 @@ use acdc_pdf_typst::{ DocumentLocale, DocumentMetadata, EmitOptions, Error as TypstError, Writer, preamble, }; use lopdf::{Document as PdfDocument, Object, dictionary}; + +/// Static backend selection offered to applications before parsing. +pub const REGISTRATION: ConverterSpec<()> = ConverterSpec::new("pdf", ()); + mod anchors; mod converter; mod error; diff --git a/converters/terminal/CHANGELOG.md b/converters/terminal/CHANGELOG.md index b9cdfa9ba..4420b13ac 100644 --- a/converters/terminal/CHANGELOG.md +++ b/converters/terminal/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Applications can register this converter using its built-in backend names and variant choices. + - Selected text postprocessors can transform the completed terminal output for each document, including documents sent to a pager. - Extension-generated caption and captured-title links now use explicit labels, diff --git a/converters/terminal/src/lib.rs b/converters/terminal/src/lib.rs index c122a9157..5b099a6c1 100644 --- a/converters/terminal/src/lib.rs +++ b/converters/terminal/src/lib.rs @@ -8,13 +8,17 @@ use std::{ use acdc_converters_core::{ BackendProfile, Converter as _, Diagnostics, InlineTextTransform, Options, TraversalContext, - section::contains_index_section, visitor::DocumentVisitor, xref::XrefGuard, + registry::ConverterSpec, section::contains_index_section, visitor::DocumentVisitor, + xref::XrefGuard, }; use acdc_parser::{ CaptionKind, DocumentAttributes, Options as ParserOptions, ReferenceTarget, ast::{AttributesRef, CaptionRef, ContentRef, DocumentRef}, }; +/// Static backend selection offered to applications before parsing. +pub const REGISTRATION: ConverterSpec<()> = ConverterSpec::new("terminal", ()); + pub(crate) use appearance::Appearance; const FALLBACK_TERMINAL_WIDTH: usize = 80; From 07111f0c84a64740062038867e81e0268c778593 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 09:05:01 +0100 Subject: [PATCH 49/55] feat(cli): select statically registered converters for every conversion route --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/src/subcommands/convert.rs | 328 +++--------------- .../src/subcommands/convert/pipeline_tests.rs | 152 +++++++- acdc-cli/src/subcommands/convert/selection.rs | 138 ++++++++ converters/README.adoc | 19 + converters/core/src/registry.rs | 29 +- .../html/examples/extension_pipeline.rs | 10 +- converters/pdf/CHANGELOG.md | 2 +- converters/pdf/src/converter.rs | 11 +- 9 files changed, 394 insertions(+), 297 deletions(-) create mode 100644 acdc-cli/src/subcommands/convert/selection.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index ca85c0d82..5e2b968a6 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Statically linked converter registrations now supply the available backend names, aliases, and variants for CLI help and conversion. + - Selected native text postprocessors run per input, including when multiple terminal documents share a pager. - Conversion accepts repeatable `--extension NAME` selections and rejects diff --git a/acdc-cli/src/subcommands/convert.rs b/acdc-cli/src/subcommands/convert.rs index 68faff820..f3acb41df 100644 --- a/acdc-cli/src/subcommands/convert.rs +++ b/acdc-cli/src/subcommands/convert.rs @@ -8,22 +8,12 @@ use std::{ time::{Duration, Instant}, }; -#[cfg(any( - test, - feature = "manpage", - feature = "markdown", - feature = "pdf", - feature = "terminal" -))] +#[cfg(any(test, feature = "terminal"))] use acdc_converters_core::Converter as _; use acdc_converters_core::{ ConversionResult, Doctype, GeneratorMetadata, Options, OutputDestination, pipeline::{ExtensionCatalog, Extensions, Pipeline}, }; -#[cfg(feature = "html")] -use acdc_converters_html::HtmlVariant; -#[cfg(feature = "markdown")] -use acdc_converters_markdown::MarkdownVariant; #[cfg(feature = "pdf")] use acdc_converters_pdf::{PageOrientation, PageSize, PdfOptions, ThemeFormat}; #[cfg(feature = "terminal")] @@ -32,7 +22,9 @@ use acdc_parser::{ AttributeValue, Options as ParserOptions, OptionsBuilder, ParseResult, SafeMode, Warning, }; -use clap::{ArgAction, Args as ClapArgs, ValueEnum}; +#[cfg(feature = "pdf")] +use clap::ValueEnum; +use clap::{ArgAction, Args as ClapArgs}; use rayon::prelude::*; use crate::{ @@ -40,6 +32,9 @@ use crate::{ timing::{TimingEntry, render_summary}, }; +#[path = "convert/selection.rs"] +mod selection; + type RawAttributes<'a> = std::collections::HashMap, AttributeValue<'a>>; #[cfg(test)] @@ -79,9 +74,9 @@ pub(crate) struct Args { /// /// `html` is the default when its feature is compiled in; otherwise /// `--backend` must be supplied explicitly. - #[arg(short = 'b', long, value_enum)] + #[arg(short = 'b', long, value_parser = selection::backend_parser())] #[cfg_attr(feature = "html", arg(default_value = "html"))] - backend: BackendArg, + backend: Box, /// Backend output variant /// @@ -93,9 +88,8 @@ pub(crate) struct Args { /// /// `--backend html5s` is preserved as a shortcut for /// `--backend html --variant semantic` and rejects `--variant`. - #[cfg(any(feature = "html", feature = "markdown"))] - #[arg(long, value_enum, verbatim_doc_comment)] - variant: Option, + #[arg(long, value_parser = selection::variant_parser(), hide = selection::installed().is_ok_and(|registry| registry.variant_spellings().next().is_none()), verbatim_doc_comment)] + variant: Option>, /// Document type to use when converting document #[arg(short = 'd', long, value_parser = clap::value_parser!(Doctype), default_value = "article")] @@ -295,17 +289,24 @@ pub(crate) fn run(args: &Args) -> MietteResult<()> { } fn run_with_extensions(args: &Args, available: &ExtensionCatalog) -> MietteResult<()> { - #[cfg(any(feature = "html", feature = "markdown"))] - let backend = args.backend.resolve(args.variant)?; - #[cfg(not(any(feature = "html", feature = "markdown")))] - let backend = args.backend.resolve(); + run_with_registries(args, available, selection::installed()?) +} + +fn run_with_registries( + args: &Args, + available: &ExtensionCatalog, + converters: &acdc_converters_core::registry::ConverterRegistry, +) -> MietteResult<()> { + let backend = converters + .resolve(&args.backend, args.variant.as_deref()) + .map_err(|e| error::display(&e))?; let extensions = available .select(&args.extensions) .map_err(|error| error::display(&error))?; #[cfg(feature = "pdf")] - validate_pdf_options(args, backend)?; + validate_pdf_options(args, backend.pdf_options)?; let safe_mode = if args.safe { SafeMode::Safe @@ -328,63 +329,7 @@ fn run_with_extensions(args: &Args, available: &ExtensionCatalog) -> MietteResul .build(); let document_attributes = build_parser_options(args, &options); - let summary = match backend { - #[cfg(feature = "html")] - Backend::Html(variant) => run_converter::( - args, - &options, - document_attributes, - extensions.as_ref(), - move |opts, attrs| { - acdc_converters_html::Converter::new_with_variant(opts, attrs, variant) - }, - ), - - #[cfg(feature = "terminal")] - Backend::Terminal => { - // Terminal outputs to stdout with optional pager support - run_terminal_with_pager(args, &options, document_attributes, extensions.as_ref()) - .map_err(|e| error::display(&e)) - } - - #[cfg(feature = "manpage")] - Backend::Manpage => run_converter::( - args, - &options, - document_attributes, - extensions.as_ref(), - acdc_converters_manpage::Converter::new, - ), - - #[cfg(feature = "markdown")] - Backend::Markdown(variant) => run_converter::( - args, - &options, - document_attributes, - extensions.as_ref(), - move |opts, attrs| { - acdc_converters_markdown::Converter::new(opts, attrs) - .map(|converter| converter.with_variant(variant)) - }, - ), - - #[cfg(feature = "pdf")] - Backend::Pdf => { - let pdf_options = pdf_options_from_args(args); - run_converter::( - args, - &options, - document_attributes, - extensions.as_ref(), - move |opts, attrs| { - acdc_converters_pdf::Converter::new(opts, attrs) - .map(|converter| converter.with_pdf_options(pdf_options.clone())) - }, - ) - } - }; - - let summary = summary?; + let summary = (backend.run)(args, &options, document_attributes, extensions.as_ref())?; if args.fail_on_warnings && summary.warning_count > 0 { let count = summary.warning_count; @@ -404,8 +349,8 @@ fn run_with_extensions(args: &Args, available: &ExtensionCatalog) -> MietteResul } #[cfg(feature = "pdf")] -fn validate_pdf_options(args: &Args, backend: Backend) -> MietteResult<()> { - if matches!(backend, Backend::Pdf) { +fn validate_pdf_options(args: &Args, accepts_pdf_options: bool) -> MietteResult<()> { + if accepts_pdf_options { if args.emit_typst.is_some() && !args.stdin && args.files.len() > 1 { return Err(miette::miette!( "--emit-typst can only be used with a single input file" @@ -430,10 +375,12 @@ fn validate_pdf_options(args: &Args, backend: Backend) -> MietteResult<()> { .filter(|path| *path != "-") .is_some_and(|output| paths_match(path, Path::new(output))) || args.out_file.is_none() - && args - .files - .iter() - .any(|file| paths_match(path, &file.with_extension("pdf"))) + && args.files.iter().any(|file| { + paths_match( + path, + &acdc_converters_pdf::Converter::default_output_path(file), + ) + }) { return Err(miette::miette!( "--emit-theme-config must use a different path from PDF output" @@ -1004,8 +951,10 @@ mod tests { "2", "document.adoc", ])?; - let backend = args.backend.resolve(args.variant)?; - assert!(validate_pdf_options(&args, backend).is_err()); + let backend = selection::installed()? + .resolve(&args.backend, args.variant.as_deref()) + .map_err(|e| error::display(&e))?; + assert!(validate_pdf_options(&args, backend.pdf_options).is_err()); Ok(()) } @@ -1022,17 +971,10 @@ mod tests { "first.adoc", "second.adoc", ])?; - let backend = { - #[cfg(any(feature = "html", feature = "markdown"))] - { - args.backend.resolve(args.variant)? - } - #[cfg(not(any(feature = "html", feature = "markdown")))] - { - args.backend.resolve() - } - }; - let Err(error) = validate_pdf_options(&args, backend) else { + let backend = selection::installed()? + .resolve(&args.backend, args.variant.as_deref()) + .map_err(|e| error::display(&e))?; + let Err(error) = validate_pdf_options(&args, backend.pdf_options) else { return Err(miette::miette!( "--emit-typst unexpectedly accepted multiple inputs" )); @@ -1054,8 +996,10 @@ mod tests { "Architecture", "document.adoc", ])?; - let backend = args.backend.resolve(args.variant)?; - let Err(error) = validate_pdf_options(&args, backend) else { + let backend = selection::installed()? + .resolve(&args.backend, args.variant.as_deref()) + .map_err(|e| error::display(&e))?; + let Err(error) = validate_pdf_options(&args, backend.pdf_options) else { return Err(miette::miette!( "PDF-only option unexpectedly accepted by HTML" )); @@ -1605,30 +1549,6 @@ fn run_terminal_with_pager( Ok(summary) } -/// CLI-local enum mirroring the surface form of `--backend`. -/// -/// Each arm is feature-gated so disabling a converter cleanly removes -/// it from the parser, the resolver, and the dispatch match. `Html5s` -/// stays in this enum (rather than being normalized to `Html`) so the -/// resolver can reject the contradictory `--backend html5s --variant -/// ` form before lowering it to the typed [`Backend`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] -enum BackendArg { - #[cfg(feature = "html")] - Html, - #[cfg(feature = "html")] - Html5s, - #[cfg(feature = "manpage")] - Manpage, - #[cfg(feature = "terminal")] - Terminal, - #[cfg(feature = "markdown")] - #[value(alias = "md")] - Markdown, - #[cfg(feature = "pdf")] - Pdf, -} - /// Input schema selected by `--theme-format`. #[cfg(feature = "pdf")] #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] @@ -1693,166 +1613,6 @@ impl PdfPageLayoutArg { } } -impl Display for BackendArg { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - #[cfg(feature = "html")] - Self::Html => f.write_str("html"), - #[cfg(feature = "html")] - Self::Html5s => f.write_str("html5s"), - #[cfg(feature = "manpage")] - Self::Manpage => f.write_str("manpage"), - #[cfg(feature = "terminal")] - Self::Terminal => f.write_str("terminal"), - #[cfg(feature = "markdown")] - Self::Markdown => f.write_str("markdown"), - #[cfg(feature = "pdf")] - Self::Pdf => f.write_str("pdf"), - } - } -} - -/// CLI-local variant choice, parsed from `--variant` before being combined -/// with the backend into the typed [`Backend`]. Each arm is feature-gated -/// so disabling its converter removes its variant names from `--variant` -/// entirely. -#[cfg(any(feature = "html", feature = "markdown"))] -#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] -enum VariantArg { - #[cfg(feature = "html")] - Standard, - #[cfg(feature = "html")] - Semantic, - #[cfg(feature = "markdown")] - #[value(name = "commonmark", alias = "cm")] - CommonMark, - #[cfg(feature = "markdown")] - #[value(alias = "github", alias = "github-flavored")] - Gfm, -} - -#[cfg(any(feature = "html", feature = "markdown"))] -impl Display for VariantArg { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - #[cfg(feature = "html")] - Self::Standard => f.write_str("standard"), - #[cfg(feature = "html")] - Self::Semantic => f.write_str("semantic"), - #[cfg(feature = "markdown")] - Self::CommonMark => f.write_str("commonmark"), - #[cfg(feature = "markdown")] - Self::Gfm => f.write_str("gfm"), - } - } -} - -/// The user's `--backend`/`--variant` pair after validation, lowered into -/// the strongly-typed combination accepted by the converter crates. -/// -/// Each arm carries the converter's own variant payload (or no payload -/// for backends that have none). This is the boundary at which CLI -/// surface concerns (the `html5s` alias, cross-backend mismatches) are -/// resolved — downstream code only ever sees a well-typed choice. New -/// variant-bearing backends simply gain a payload here without -/// rearranging anything else. -#[derive(Debug, Clone, Copy)] -enum Backend { - #[cfg(feature = "html")] - Html(HtmlVariant), - #[cfg(feature = "manpage")] - Manpage, - #[cfg(feature = "terminal")] - Terminal, - #[cfg(feature = "markdown")] - Markdown(MarkdownVariant), - #[cfg(feature = "pdf")] - Pdf, -} - -/// Reject a `--variant` for a backend that doesn't define any. Interpolating -/// the backend name keeps the error consistent across no-variant backends -/// and means a future addition only needs one `resolve` arm, not a bespoke -/// error string. -#[cfg(all( - any(feature = "manpage", feature = "pdf", feature = "terminal"), - any(feature = "html", feature = "markdown") -))] -fn require_no_variant(backend: &'static str, variant: Option) -> MietteResult<()> { - if variant.is_some() { - return Err(miette::miette!( - "backend '{backend}' does not accept a variant" - )); - } - Ok(()) -} - -impl BackendArg { - /// Combine the CLI's separate `--backend` / `--variant` flags into a - /// fully-typed [`Backend`], rejecting any combination the - /// converter layer can't honor: the `html5s` alias paired with any - /// variant, a markdown variant on the html backend (or vice versa), - /// or any variant on a backend that has none. - #[cfg(any(feature = "html", feature = "markdown"))] - fn resolve(self, variant: Option) -> MietteResult { - match (self, variant) { - // The `html5s` alias is the surface spelling of "html + semantic". - // Pairing it with `--variant` would be self-contradicting. - #[cfg(feature = "html")] - (Self::Html5s, Some(_)) => Err(miette::miette!( - "--backend html5s does not accept a variant — it is a backwards-compat \ - alias for `--backend html --variant semantic`. Drop --variant, or use \ - `--backend html` with the variant of your choice." - )), - #[cfg(feature = "html")] - (Self::Html5s, None) | (Self::Html, Some(VariantArg::Semantic)) => { - Ok(Backend::Html(HtmlVariant::Semantic)) - } - #[cfg(feature = "html")] - (Self::Html, None | Some(VariantArg::Standard)) => { - Ok(Backend::Html(HtmlVariant::Standard)) - } - #[cfg(all(feature = "html", feature = "markdown"))] - (Self::Html, Some(v @ (VariantArg::CommonMark | VariantArg::Gfm))) => Err( - miette::miette!("variant '{v}' is not supported by backend 'html'"), - ), - #[cfg(feature = "markdown")] - (Self::Markdown, None) => Ok(Backend::Markdown(MarkdownVariant::default())), - #[cfg(feature = "markdown")] - (Self::Markdown, Some(VariantArg::CommonMark)) => { - Ok(Backend::Markdown(MarkdownVariant::CommonMark)) - } - #[cfg(feature = "markdown")] - (Self::Markdown, Some(VariantArg::Gfm)) => { - Ok(Backend::Markdown(MarkdownVariant::GitHubFlavored)) - } - #[cfg(all(feature = "markdown", feature = "html"))] - (Self::Markdown, Some(v @ (VariantArg::Standard | VariantArg::Semantic))) => Err( - miette::miette!("variant '{v}' is not supported by backend 'markdown'"), - ), - #[cfg(feature = "manpage")] - (Self::Manpage, v) => require_no_variant("manpage", v).map(|()| Backend::Manpage), - #[cfg(feature = "pdf")] - (Self::Pdf, v) => require_no_variant("pdf", v).map(|()| Backend::Pdf), - #[cfg(feature = "terminal")] - (Self::Terminal, v) => require_no_variant("terminal", v).map(|()| Backend::Terminal), - } - } - - /// Resolve the backend when no compiled converter accepts `--variant`. - #[cfg(not(any(feature = "html", feature = "markdown")))] - fn resolve(self) -> Backend { - match self { - #[cfg(feature = "manpage")] - Self::Manpage => Backend::Manpage, - #[cfg(feature = "pdf")] - Self::Pdf => Backend::Pdf, - #[cfg(feature = "terminal")] - Self::Terminal => Backend::Terminal, - } - } -} - fn build_attributes_map(values: &[String]) -> RawAttributes<'static> { let mut map = RawAttributes::with_capacity(values.len()); diff --git a/acdc-cli/src/subcommands/convert/pipeline_tests.rs b/acdc-cli/src/subcommands/convert/pipeline_tests.rs index 97bada8b0..0e1b88401 100644 --- a/acdc-cli/src/subcommands/convert/pipeline_tests.rs +++ b/acdc-cli/src/subcommands/convert/pipeline_tests.rs @@ -13,7 +13,7 @@ use acdc_parser::extensions::{ BlockMacro, BlockMacroOutput, BlockMacroProcessor, MacroExecutionContext, MacroInvocation, Registry, }; -use clap::{Parser, ValueEnum}; +use clap::Parser; use super::*; @@ -71,17 +71,14 @@ fn available(created: &Arc) -> Result TestResult { - let backend = BackendArg::value_variants() - .first() - .and_then(ValueEnum::to_possible_value) - .ok_or("backend")?; + let backend = selection::installed()?.names().next().ok_or("backend")?; let created = Arc::new(AtomicUsize::new(0)); let available = available(&created)?; for input in ["--stdin", "missing-input.adoc"] { let args = args( [ "--backend", - backend.get_name(), + backend, "--extension", "probe", "--extension", @@ -235,3 +232,146 @@ fn pipeline_cli_terminal_reader_files_and_pager_share_processing() -> TestResult assert_eq!(created.load(Ordering::SeqCst), 4); Ok(()) } + +/// A downstream converter chooses its own parser profile, serialization, and suffix. +struct NativeJson { + options: Options, + parser: acdc_parser::Options<'static>, +} + +#[derive(Debug, thiserror::Error)] +enum JsonError { + #[error(transparent)] + Parser(#[from] acdc_parser::Error), + #[error(transparent)] + Io(#[from] std::io::Error), + #[error(transparent)] + Json(#[from] serde_json::Error), +} + +impl acdc_converters_core::Converter<'static> for NativeJson { + type Error = JsonError; + + fn new(options: Options, parser: OptionsBuilder<'static>) -> Result { + let parser = + acdc_converters_core::BackendProfile::new("native-json", "json", "json", ".ast.json") + .apply(parser, options.doctype(), options.embedded()) + .build()?; + Ok(Self { options, parser }) + } + fn options(&self) -> &Options { + &self.options + } + fn parser_options(&self) -> &acdc_parser::Options<'static> { + &self.parser + } + fn name(&self) -> &'static str { + "native-json" + } + fn supports_text_output(&self) -> bool { + true + } + fn derive_output_path( + &self, + input: &Path, + _: acdc_parser::ast::DocumentRef<'_>, + ) -> Result, Self::Error> { + Ok(Some(input.with_extension("ast.json"))) + } + fn write_to( + &self, + doc: acdc_parser::ast::DocumentRef<'_>, + writer: W, + _: Option<&Path>, + _: Option<&Path>, + _: &mut acdc_converters_core::Diagnostics<'_>, + ) -> Result<(), Self::Error> { + Ok(serde_json::to_writer(writer, &doc)?) + } +} + +#[test] +fn static_converter_uses_cli_arguments_the_shared_pipeline_and_its_own_output_path() -> TestResult { + use acdc_converters_core::{postprocess::TextPostprocessor, registry::ConverterSpec}; + use clap::{CommandFactory as _, FromArgMatches as _}; + + let mut converters = selection::builtins()?; + converters.register( + ConverterSpec::new("native-json", ()).with_aliases(&["nj"]), + |()| selection::Runner::converter(NativeJson::new), + )?; + let temp = tempfile::tempdir()?; + let file = temp.path().join("doc.adoc"); + std::fs::write( + &file, + "ifdef::backend-native-json[]\nSelected before parsing.\nendif::[]", + )?; + let mut catalog = ExtensionCatalog::default(); + catalog.register( + "wrap", + Extensions::default().with_postprocessor(TextPostprocessor::new( + "native-json", + |text, _, _| { + let doc: serde_json::Value = serde_json::from_str(text)?; + *text = serde_json::to_string(&serde_json::json!({"wrapped":doc}))?; + Ok(()) + }, + )), + )?; + let command = TestArgs::command().mut_arg("backend", |arg| { + arg.value_parser(selection::values(converters.backend_spellings())) + }); + let matches = command.try_get_matches_from([ + OsString::from("convert"), + "--backend".into(), + "nj".into(), + "--extension".into(), + "wrap".into(), + file.into_os_string(), + ])?; + let args = TestArgs::from_arg_matches(&matches)?.args; + run_with_registries(&args, &catalog, &converters)?; + let json = std::fs::read_to_string(temp.path().join("doc.ast.json"))?; + assert!( + serde_json::from_str::(&json)? + .get("wrapped") + .is_some() + ); + assert!(json.contains("Selected before parsing.")); + Ok(()) +} + +#[cfg(all(feature = "html", feature = "markdown"))] +#[test] +fn cli_backend_spellings_and_variant_errors_follow_the_registry() -> TestResult { + let catalog = selection::installed()?; + for (backend, variant, canonical, canonical_variant) in [ + ("html5s", None, "html", "semantic"), + ("md", Some("cm"), "markdown", "commonmark"), + ("markdown", Some("github-flavored"), "markdown", "gfm"), + ("md", None, "markdown", "gfm"), + ] { + let mut flags = vec!["--backend", backend, "--stdin"]; + if let Some(v) = variant { + flags.extend(["--variant", v]); + } + let args = args(flags.into_iter().map(OsString::from))?; + assert!(std::ptr::eq( + catalog.resolve(&args.backend, args.variant.as_deref())?, + catalog.resolve(canonical, Some(canonical_variant))? + )); + } + for (backend, variant, diagnostic) in [ + ("html5s", "semantic", "does not accept a variant"), + ("html", "gfm", "not supported by backend 'html'"), + ("md", "standard", "not supported by backend 'markdown'"), + ] { + let args = + args(["--backend", backend, "--variant", variant, "missing.adoc"].map(OsString::from))?; + let error = run_with_extensions(&args, &ExtensionCatalog::default()) + .err() + .ok_or("expected a selection error")?; + assert!(error.to_string().contains(diagnostic), "{error}"); + } + Ok(()) +} diff --git a/acdc-cli/src/subcommands/convert/selection.rs b/acdc-cli/src/subcommands/convert/selection.rs new file mode 100644 index 000000000..658ad2aa5 --- /dev/null +++ b/acdc-cli/src/subcommands/convert/selection.rs @@ -0,0 +1,138 @@ +//! Bind statically linked converter choices to the input and output routes of this CLI. +use std::sync::OnceLock; + +use acdc_converters_core::registry::{ConverterRegistry, SelectionError}; +use clap::builder::{ + PossibleValue, PossibleValuesParser, StringValueParser, TypedValueParser as _, ValueParser, +}; + +use super::{ + Args, ConversionSummary, Extensions, MietteResult, Options, OptionsBuilder, error, + run_converter, +}; + +type Run = dyn Fn( + &Args, + &Options, + OptionsBuilder<'static>, + Option<&Extensions>, + ) -> MietteResult + + Send + + Sync; + +pub(super) struct Runner { + pub(super) run: Box, + #[cfg(feature = "pdf")] + pub(super) pdf_options: bool, +} + +impl Runner { + fn new( + run: impl Fn( + &Args, + &Options, + OptionsBuilder<'static>, + Option<&Extensions>, + ) -> MietteResult + + Send + + Sync + + 'static, + ) -> Self { + Self { + run: Box::new(run), + #[cfg(feature = "pdf")] + pdf_options: false, + } + } + + /// Adapt a static converter factory once, retaining its typed pipeline for each input. + pub(super) fn converter(factory: F) -> Self + where + P: acdc_converters_core::Converter<'static>, + P::Error: Send + 'static, + F: Fn(Options, OptionsBuilder<'static>) -> Result + Send + Sync + 'static, + { + Self::new(move |args, opts, parser, extensions| { + run_converter(args, opts, parser, extensions, &factory) + }) + } +} + +pub(super) fn builtins() -> Result, SelectionError> { + #[cfg(any(feature = "manpage", feature = "pdf", feature = "markdown"))] + use acdc_converters_core::Converter as _; + + let mut backends = ConverterRegistry::default(); + #[cfg(feature = "html")] + backends.register(acdc_converters_html::REGISTRATION, |variant| { + Runner::converter(move |opts, parser| { + acdc_converters_html::Converter::new_with_variant(opts, parser, variant) + }) + })?; + #[cfg(feature = "markdown")] + backends.register(acdc_converters_markdown::REGISTRATION, |variant| { + Runner::converter(move |opts, parser| { + acdc_converters_markdown::Converter::new(opts, parser) + .map(|converter| converter.with_variant(variant)) + }) + })?; + #[cfg(feature = "manpage")] + backends.register(acdc_converters_manpage::REGISTRATION, |()| { + Runner::converter(acdc_converters_manpage::Converter::new) + })?; + #[cfg(feature = "terminal")] + backends.register(acdc_converters_terminal::REGISTRATION, |()| { + Runner::new(|args, options, parser, extensions| { + super::run_terminal_with_pager(args, options, parser, extensions) + .map_err(|e| error::display(&e)) + }) + })?; + #[cfg(feature = "pdf")] + backends.register(acdc_converters_pdf::REGISTRATION, |()| { + let run = |args: &Args, + options: &Options, + parser: OptionsBuilder<'static>, + extensions: Option<&Extensions>| { + let pdf_options = super::pdf_options_from_args(args); + run_converter(args, options, parser, extensions, move |opts, attrs| { + acdc_converters_pdf::Converter::new(opts, attrs) + .map(|converter| converter.with_pdf_options(pdf_options.clone())) + }) + }; + Runner { + run: Box::new(run), + pdf_options: true, + } + })?; + Ok(backends) +} + +pub(super) fn installed() -> MietteResult<&'static ConverterRegistry> { + static INSTALLED: OnceLock, SelectionError>> = OnceLock::new(); + INSTALLED + .get_or_init(builtins) + .as_ref() + .map_err(error::display) +} + +pub(super) fn values(spellings: impl Iterator) -> ValueParser { + PossibleValuesParser::new( + spellings.map(|(name, visible)| PossibleValue::new(name).hide(!visible)), + ) + .map(String::into_boxed_str) + .into() +} + +pub(super) fn backend_parser() -> ValueParser { + installed().map_or_else( + |_| StringValueParser::new().map(String::into_boxed_str).into(), + |catalog| values(catalog.backend_spellings()), + ) +} + +pub(super) fn variant_parser() -> ValueParser { + installed().map_or_else( + |_| StringValueParser::new().map(String::into_boxed_str).into(), + |catalog| values(catalog.variant_spellings()), + ) +} diff --git a/converters/README.adoc b/converters/README.adoc index bb75f9555..e8f3a154f 100644 --- a/converters/README.adoc +++ b/converters/README.adoc @@ -6,6 +6,25 @@ - `link:./pdf[pdf]` - `AsciiDoc` PDF backend backed by the Rust Typst engine - `link:./terminal[terminal]` - `AsciiDoc` terminal printer backend (à la *nix command `cat`) +== Selecting a static converter + +Each converter crate exports a `REGISTRATION` with its backend names and typed +variants. Register it in `acdc_converters_core::registry::ConverterRegistry` +and bind each choice to a factory. A statically linked external crate can supply +its own `ConverterSpec` and factory through the same interface. + +Resolve the backend before opening an input. For example, `html5s` selects HTML's +semantic variant and `md` accepts the same variants as `markdown`. A duplicate +name or alias fails registration. To replace a family, call `replace` with its +canonical name. Successful replacement retires old aliases. A conflicting +replacement preserves the original selection. + +The selected factory configures the converter, whose `BackendProfile` supplies +the intrinsic attributes seen by conditionals and includes. After rendering, +`ConversionResult::output_path` gives callers the actual file to open. It can +depend on the document, as it does for a manpage's section number. A stdout +conversion has no file path. + == Library processing with extensions Configure the backend before parsing and wrap it in diff --git a/converters/core/src/registry.rs b/converters/core/src/registry.rs index c590f3925..c7160fc9e 100644 --- a/converters/core/src/registry.rs +++ b/converters/core/src/registry.rs @@ -77,7 +77,19 @@ pub enum SelectionError { /// No backend or alias matches this spelling. #[error("backend '{0}' is not available")] Unavailable(String), - /// A plain backend or fixed shortcut does not allow an explicit variant. + /// A fixed backend shortcut already selects a specific variant. + #[error( + "--backend {shortcut} does not accept a variant — it is a backwards-compat alias for `--backend {backend} --variant {variant}`. Drop --variant, or use `--backend {backend}` with the variant of your choice." + )] + FixedVariant { + /// Shortcut used for the selection. + shortcut: String, + /// Canonical backend. + backend: &'static str, + /// Variant selected by the shortcut. + variant: &'static str, + }, + /// A plain backend does not allow an explicit variant. #[error("backend '{0}' does not accept a variant")] NoVariants(String), /// A variant belongs to another backend or has an unknown spelling. @@ -248,7 +260,14 @@ impl ConverterRegistry { .families .get(canonical) .ok_or_else(|| SelectionError::Unavailable(name.to_owned()))?; - if variant.is_some() && (fixed.is_some() || family.variants.is_empty()) { + if let (Some(pinned), Some(_)) = (fixed, variant) { + return Err(SelectionError::FixedVariant { + shortcut: name.to_owned(), + backend: canonical, + variant: pinned, + }); + } + if variant.is_some() && family.variants.is_empty() { return Err(SelectionError::NoVariants(name.to_owned())); } let Some(requested) = fixed.or(variant) else { @@ -310,7 +329,11 @@ mod tests { )); assert_eq!( catalog.resolve("format2", Some("alt")), - Err(SelectionError::NoVariants("format2".into())) + Err(SelectionError::FixedVariant { + shortcut: "format2".into(), + backend: "format", + variant: "alternate" + }) ); assert!(matches!( catalog.resolve("format", Some("other")), diff --git a/converters/html/examples/extension_pipeline.rs b/converters/html/examples/extension_pipeline.rs index 86b9f972f..2f31b6137 100644 --- a/converters/html/examples/extension_pipeline.rs +++ b/converters/html/examples/extension_pipeline.rs @@ -5,8 +5,9 @@ use std::error::Error; use acdc_converters_core::{ Converter as _, Diagnostics, Options, pipeline::{ExtensionCatalog, Pipeline}, + registry::ConverterRegistry, }; -use acdc_converters_html::Converter; +use acdc_converters_html::{Converter, REGISTRATION}; use acdc_parser::{ Options as ParserOptions, extensions::{ @@ -38,7 +39,12 @@ fn main() -> Result<(), Box> { // Availability alone does not activate a package or invoke its factories. let selected = available.select(["greetings"])?.ok_or("empty selection")?; - let pipeline = Pipeline::new(Converter::new( + let mut backends = ConverterRegistry::default(); + backends.register(REGISTRATION, |variant| { + move |options, parser| Converter::new_with_variant(options, parser, variant) + })?; + let make_converter = backends.resolve("html", None)?; + let pipeline = Pipeline::new(make_converter( Options::builder().embedded(true).build(), ParserOptions::builder(), )?) diff --git a/converters/pdf/CHANGELOG.md b/converters/pdf/CHANGELOG.md index 685b26c71..de0e91697 100644 --- a/converters/pdf/CHANGELOG.md +++ b/converters/pdf/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- Applications can register this converter using its built-in backend names and variant choices. +- Applications can register the PDF backend by name and determine its default file destination before processing a batch. - Extension-generated caption and captured-title links now use explicit labels, preserving title formatting and source attributes while following final captions diff --git a/converters/pdf/src/converter.rs b/converters/pdf/src/converter.rs index aa80c0923..d3eabbb01 100644 --- a/converters/pdf/src/converter.rs +++ b/converters/pdf/src/converter.rs @@ -11,6 +11,15 @@ use acdc_parser::ast::DocumentRef; use crate::{Converter, Error, PDF_BACKEND, PdfOptions}; +impl Converter<'_> { + /// Destination a file input would use when the caller requests derived output. + /// Applications can check companion paths for conflicts before reading a batch. + #[must_use] + pub fn default_output_path(input: &Path) -> PathBuf { + input.with_extension("pdf") + } +} + impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { type Error = Error; @@ -47,7 +56,7 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { input: &Path, _doc: DocumentRef<'_>, ) -> Result, Error> { - let pdf_path = input.with_extension("pdf"); + let pdf_path = Self::default_output_path(input); if pdf_path == input { return Err(Error::OutputPathSameAsInput(input.to_path_buf())); } From eb78958c9a78291d6596ddd67b826c5693fed8f2 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 10:05:39 +0100 Subject: [PATCH 50/55] fix(parser): honor enclosing section boundaries in streamed quotes --- acdc-parser/CHANGELOG.md | 4 +- acdc-parser/src/grammar/document/compound.rs | 103 ++++++++++++------ .../src/grammar/document/coordinator.rs | 28 ++--- acdc-parser/src/grammar/document/delimited.rs | 57 ++++++++-- acdc-parser/src/grammar/document/peg.rs | 6 + acdc-parser/src/grammar/document/source.rs | 26 +++-- acdc-parser/tests/extensions/parity.rs | 57 ++++++++++ acdc-parser/tests/extensions/recovery.rs | 7 +- 8 files changed, 222 insertions(+), 66 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index c18f58f19..7210178cb 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -31,7 +31,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 was silently dropped while the macro's attribute changes and deferred request survived, so `finish()` or a tree processor failed at a location no longer in the document. Content without executed extensions still recovers with a - warning. + warning. A styled quote spanning a conditional now follows the same section + boundaries with or without extensions. acdc warns at the interrupting heading + and resumes after the quote. Asciidoctor retains the content inside the quote. - Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. A style registered with `BlockStyle::compound` can also request that its body be parsed as children of an open block. - Block styles can report a warning at the styled block's source location and continue parsing with fallback content. diff --git a/acdc-parser/src/grammar/document/compound.rs b/acdc-parser/src/grammar/document/compound.rs index 5f19e1765..b6d2afaa7 100644 --- a/acdc-parser/src/grammar/document/compound.rs +++ b/acdc-parser/src/grammar/document/compound.rs @@ -7,9 +7,9 @@ use crate::{ use super::{ RecognitionError, - construction::{ConstructionMode, DelimitedConstruction}, + construction::DelimitedConstruction, coordinator::{BlockCursor, Execution}, - delimited::resolve_delimited_close, + delimited::{DelimitedParams, resolve_delimited_close}, document_parser, metadata::assign_block_caption, source::SourceInput, @@ -32,7 +32,7 @@ impl BlockCursor { // Build the accepted shell with the existing builder without issuing an // unterminated-block warning at the temporary end of the input window. construction.params.close = Some((params.end, params.open_delim)); - let (mut block, _) = match construction.start(state) { + let (mut block, request) = match construction.start(state) { Ok(started) => started, Err(error) => return Ok(Err(error)), }; @@ -41,9 +41,13 @@ impl BlockCursor { Ok(false) => return Ok(Ok(())), Err(error) => return Ok(Err(error)), } - let mut child = BlockCursor::new(self.offset, ConstructionMode::Ordered); - child.base_offset = self.base_offset; - let previous_context = std::mem::replace(&mut state.block_context, BlockContext::Compound); + let mut child = BlockCursor::content( + self.offset, + self.base_offset, + request.and_then(|r| r.parent_section_level), + ); + let context = request.map_or(BlockContext::Compound, |r| r.context); + let previous_context = std::mem::replace(&mut state.block_context, context); let previous_scope = std::mem::replace( &mut state.source_scope_offset, params.content_start + params.offset, @@ -51,6 +55,7 @@ impl BlockCursor { input.push_boundary(params.open_delim); let mut body = Vec::new(); let callbacks = accepted.block_callbacks(); + let toc_start = state.toc_entries.len(); let result = child.collect(input, state, &mut body, accepted); input.pop_boundary(); state.block_context = previous_context; @@ -58,8 +63,7 @@ impl BlockCursor { let mut end = match result { Ok(Ok(end)) => end, Ok(Err(error)) => return Ok(Err(error)), - // Compound children cannot stop at a section heading, so no known - // input reaches this. Still report executed processors first. + // Report an executed processor before propagating a child grammar failure. Err(error) => { return match accepted.discarded_callback(callbacks, "Compound block content") { Some(error) => Ok(Err(error)), @@ -67,6 +71,7 @@ impl BlockCursor { }; } }; + let unparsed = state.input.get(child.offset..); while let Some(line) = source_tail(state, end).and_then(|tail| tail.split_inclusive('\n').next()) { @@ -75,47 +80,77 @@ impl BlockCursor { } end += line.len(); } - let close = source_tail(state, end) + let mut close = source_tail(state, end) .and_then(|tail| tail.split_inclusive('\n').next()) .filter(|line| { document_parser::source_block_close(line, state, params.open_delim, false).is_ok() }); + // If the child sequence stopped at a heading, consume the rest of its + // quote without running processors in the discarded text. + let recovery = if close.is_none() + && let (Some(request), Some(tail)) = (request, unparsed) + && let Some(warning) = + request.section_boundary_warning(tail, child.base_offset + child.offset, state) + { + if let Some(error) = accepted.discarded_callback(callbacks, request.error_context) { + return Ok(Err(error)); + } + body.clear(); + state.toc_entries.truncate(toc_start); + (end, close) = match input.delimited_boundary(end, params.open_delim, false, state) { + Ok(boundary) => boundary, + Err(error) => return Ok(Err(error)), + }; + Some(warning) + } else { + None + }; params.close = close.map(|_| (end - params.offset, params.open_delim)); params.end = end - params.offset + close.map_or(0, |line| line.trim_end_matches('\n').len()); - let close_location = match resolve_delimited_close(state, ¶ms) { - Ok(location) => location, - Err(error) => return Ok(Err(error)), - }; - let Some(source) = retain_body(state, params.content_start + params.offset, end) else { - return Ok(Err(Error::Parse( - Box::new(state.create_error_source_location(block.location().clone())), - "missing committed compound source".into(), - ))); - }; - *block.location_mut() = - state.create_block_location(params.start, params.end, params.offset); - if let Block::DelimitedBlock(delimited) = &mut block { - delimited.close_delimiter_location = close_location; - delimited.source_text = Some(source); + if let Err(error) = finish_compound(state, ¶ms, end, &mut block, body) { + return Ok(Err(error)); + } + if let Some(warning) = recovery { + state.add_warning(warning); } - let Some(slot) = crate::extensions::compound_body_mut(&mut block) else { - return Ok(Err(Error::Parse( - Box::new(state.create_error_source_location(block.location().clone())), - "compound builder returned no child content slot".into(), - ))); - }; - *slot = body; - child.offset = - end - child.base_offset + close.map_or(0, |line| line.trim_end_matches('\n').len()); - self.offset = child.offset; self.base_offset = child.base_offset; + self.offset = params.end + params.offset - self.base_offset; assign_block_caption(state, &mut block); output.push(block); Ok(Ok(())) } } +fn finish_compound<'a>( + state: &mut ParserState<'a>, + params: &DelimitedParams<'a>, + end: usize, + block: &mut Block<'a>, + body: Vec>, +) -> Result<(), Error> { + let close_location = resolve_delimited_close(state, params)?; + let Some(source) = retain_body(state, params.content_start + params.offset, end) else { + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "missing committed compound source".into(), + )); + }; + *block.location_mut() = state.create_block_location(params.start, params.end, params.offset); + if let Block::DelimitedBlock(delimited) = block { + delimited.close_delimiter_location = close_location; + delimited.source_text = Some(source); + } + let Some(slot) = crate::extensions::compound_body_mut(block) else { + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "compound builder returned no child content slot".into(), + )); + }; + *slot = body; + Ok(()) +} + pub(super) fn retain_body<'a>( state: &ParserState<'a>, start: usize, diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index bde1fa8fc..7cfe771ba 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -157,6 +157,16 @@ impl BlockCursor { } } + /// Ordered child cursor with the section boundary supplied by its builder. + pub(super) fn content(offset: usize, base_offset: usize, level: Option) -> Self { + Self { + offset, + base_offset, + parent: BlockParent { level, kind: None }, + mode: ConstructionMode::Ordered, + } + } + #[cfg(test)] pub(super) fn advance<'a>( &mut self, @@ -480,15 +490,7 @@ where state: &mut ParserState<'a>, request: ContentRequest<'a>, ) -> Result>, Error> { - let mut cursor = BlockCursor { - offset: 0, - base_offset: request.offset, - parent: BlockParent { - level: request.parent_section_level, - kind: None, - }, - mode: ConstructionMode::Ordered, - }; + let mut cursor = BlockCursor::content(0, request.offset, request.parent_section_level); let mut blocks = Vec::new(); let toc_start = state.toc_entries.len(); let callbacks = self.accepted.block_callbacks(); @@ -518,13 +520,7 @@ where // Recovery discards this child tree. Retain no provisional TOC // entries for headings that cannot survive in the document. state.toc_entries.truncate(toc_start); - crate::grammar::inline_processing::adjust_and_log_parse_error( - &error, - request.source, - request.offset, - state, - request.error_context, - ); + request.warn_recovery(&error, state); Ok(Vec::new()) } } diff --git a/acdc-parser/src/grammar/document/delimited.rs b/acdc-parser/src/grammar/document/delimited.rs index a96a3c1dd..e76496431 100644 --- a/acdc-parser/src/grammar/document/delimited.rs +++ b/acdc-parser/src/grammar/document/delimited.rs @@ -34,6 +34,53 @@ pub(super) struct ContentRequest<'a> { pub(super) error_context: &'static str, } +impl<'a> ContentRequest<'a> { + /// An enclosing section ends the child sequence before the quote closes. + /// Report the heading itself regardless of how the PEG input was split. + pub(super) fn section_boundary_warning( + &self, + tail: &'a str, + offset: usize, + state: &mut ParserState<'a>, + ) -> Option { + if !matches!(self.kind, ContentKind::Blocks) || self.context != BlockContext::Document { + return None; + } + let position = document_parser::content_section_boundary( + tail, + state, + offset, + self.parent_section_level, + ) + .ok()?; + let location = + state.create_error_source_location(state.create_location(position, position)); + Some(crate::Warning::new( + crate::WarningKind::ContentRecovery { + message: "A section at the enclosing level or higher interrupts the quote. Its body was discarded.".into(), + }, + Some(location), + )) + } + + pub(super) fn warn_recovery( + &self, + error: &super::RecognitionError, + state: &mut ParserState<'a>, + ) { + let offset = error.location.offset; + if let Some(warning) = self + .source + .get(offset..) + .and_then(|tail| self.section_boundary_warning(tail, self.offset + offset, state)) + { + state.add_warning(warning); + return; + } + adjust_and_log_parse_error(error, self.source, self.offset, state, self.error_context); + } +} + pub(super) trait ContentParser<'a> { /// Buffered cells have already passed through the table decoder. fn raw_cell_separator(&self) -> Option { @@ -65,6 +112,7 @@ impl<'a> ContentParser<'a> for GrammarContent { state: &mut ParserState<'a>, request: ContentRequest<'a>, ) -> Result>, Error> { + let toc_start = state.toc_entries.len(); let result = match request.kind { ContentKind::Compound => document_parser::compound_blocks( request.source, @@ -81,13 +129,8 @@ impl<'a> ContentParser<'a> for GrammarContent { ), }; result.unwrap_or_else(|error| { - adjust_and_log_parse_error( - &error, - request.source, - request.offset, - state, - request.error_context, - ); + state.toc_entries.truncate(toc_start); + request.warn_recovery(&error, state); Ok(Vec::new()) }) } diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 32215c20f..83583284b 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -198,6 +198,12 @@ peg::parser! { peg::RuleResult::Failed }} + // Locate a section boundary after the last accepted child, using the + // same level and metadata rules as block recognition. + #[no_eof] + pub(in crate::grammar::document) rule content_section_boundary(offset: usize, parent: Option) -> usize + = eol()* start:position!() &same_or_higher_level_section(offset, parent) { offset + start } + pub(in crate::grammar::document) rule block_sequence_end(offset: usize) = resume_at(offset) eol()* diff --git a/acdc-parser/src/grammar/document/source.rs b/acdc-parser/src/grammar/document/source.rs index 0cb1d43fe..d73b7d973 100644 --- a/acdc-parser/src/grammar/document/source.rs +++ b/acdc-parser/src/grammar/document/source.rs @@ -441,20 +441,32 @@ impl<'a> SourceInput<'a> { Ok(end.min(self.index.len())) } - fn delimited_end( + /// Locate the matching close without constructing children, respecting table cell boundaries. + pub(super) fn delimited_boundary( &mut self, mut offset: usize, delimiter: &str, table: bool, state: &mut ParserState<'a>, - ) -> Result { - while let Some(next) = self.line(offset, state)? { - offset += next.len(); - if document_parser::source_block_close(next, state, delimiter, table).is_ok() { - break; + ) -> Result<(usize, Option<&'a str>), Error> { + while let Some(line) = self.line(offset, state)? { + if document_parser::source_block_close(line, state, delimiter, table).is_ok() { + return Ok((offset, Some(line))); } + offset += line.len(); } - Ok(offset.min(self.index.len())) + Ok((offset.min(self.index.len()), None)) + } + + fn delimited_end( + &mut self, + offset: usize, + delimiter: &str, + table: bool, + state: &mut ParserState<'a>, + ) -> Result { + let (end, close) = self.delimited_boundary(offset, delimiter, table, state)?; + Ok(end + close.map_or(0, str::len)) } fn metadata_end( diff --git a/acdc-parser/tests/extensions/parity.rs b/acdc-parser/tests/extensions/parity.rs index d4fc34020..4bad89555 100644 --- a/acdc-parser/tests/extensions/parity.rs +++ b/acdc-parser/tests/extensions/parity.rs @@ -137,3 +137,60 @@ fn unquoted_none_arguments_follow_compatibility_mode() -> TestResult { } Ok(()) } + +#[test] +fn streamed_styled_quote_recovers_at_its_parent_section_boundary() -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let registry = greet_registry(&calls)?; + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (intro, ending) in [ + ("\\greet::[]", "____\n\nAfter."), + ("=== Child\n\n\\greet::[]", "____\n\nAfter."), + ("\\greet::[]", ""), + ] { + let source = format!( + "= Doc\n\n== A\n\n[quote]\n____\n{intro}\n\nifdef::x[]\nX.\nendif::[]\n\n== B\n\ngreet::discarded[]\n{ending}" + ); + let ordinary = acdc_parser::parse(&source, &options)?; + let extended = registry.parse(&source, &options)?.finish()?; + assert!( + ordinary + .warnings() + .iter() + .any(|w| matches!(w.kind, WarningKind::ContentRecovery { .. })) + ); + assert_eq!(extended.warnings(), ordinary.warnings(), "{mode:?}"); + assert_eq!( + serde_json::to_value(extended.document())?, + serde_json::to_value(ordinary.document())?, + "{mode:?}" + ); + assert_eq!(extended.document().toc_entries().len(), 1); + assert_eq!(ordinary.document().toc_entries().len(), 1); + } + } + assert_eq!(calls.load(Ordering::SeqCst), 0); + Ok(()) +} + +#[test] +fn streamed_styled_quote_retains_a_deeper_section() -> TestResult { + let source = "== A\n\n[quote]\n____\n\\greet::[]\n\nifdef::x[]\nX.\nendif::[]\n\n=== Child\n\ntext\n____\n\nAfter."; + let calls = Arc::new(AtomicUsize::new(0)); + let registry = greet_registry(&calls)?; + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let ordinary = acdc_parser::parse(source, &options)?; + let extended = registry.parse(source, &options)?.finish()?; + assert_eq!(ordinary.document().toc_entries().len(), 2); + assert_eq!(extended.document().toc_entries().len(), 2); + assert_eq!(extended.warnings(), ordinary.warnings(), "{mode:?}"); + assert_eq!( + serde_json::to_value(extended.document())?, + serde_json::to_value(ordinary.document())?, + "{mode:?}" + ); + } + Ok(()) +} diff --git a/acdc-parser/tests/extensions/recovery.rs b/acdc-parser/tests/extensions/recovery.rs index dda5bed04..b2fb8894f 100644 --- a/acdc-parser/tests/extensions/recovery.rs +++ b/acdc-parser/tests/extensions/recovery.rs @@ -15,7 +15,7 @@ use super::TestResult; /// Native parsing recovers each source by dropping the content that holds /// `greet::[]` at the given line. -const DISCARDED: [(&str, u32); 6] = [ +const DISCARDED: [(&str, u32); 7] = [ // A `[quote]` body inherits the section context and stops at `== B`. ( "= Doc\n\n== A\n\n[quote]\n____\ngreet::[]\n\n== B\n\ntext\n____\n\nAfter.", @@ -40,6 +40,11 @@ const DISCARDED: [(&str, u32); 6] = [ "term:: def\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n|===\n|===\n====\n\nAfter.", 7, ), + // The processor runs before a conditional splits the quote into reader windows. + ( + "== A\n\n[quote]\n____\ngreet::[]\n\nifdef::x[]\nX.\nendif::[]\n\n== B\n\ntext\n____", + 5, + ), ]; fn greet_registry(calls: &Arc) -> Result> { From 419212a62acb64e81f8bd6a109678babcfec6604 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 10:25:06 +0100 Subject: [PATCH 51/55] fix(parser): recover failed children in streamed compounds SC-588 --- acdc-parser/CHANGELOG.md | 6 + acdc-parser/src/grammar/document/compound.rs | 130 +++++++++--------- .../src/grammar/document/coordinator.rs | 4 +- acdc-parser/src/grammar/document/delimited.rs | 33 ++--- acdc-parser/src/grammar/document/peg.rs | 2 +- acdc-parser/src/grammar/document/table.rs | 2 - acdc-parser/src/grammar/inline_processing.rs | 43 +++--- acdc-parser/tests/extensions/recovery.rs | 79 ++++++++++- 8 files changed, 186 insertions(+), 113 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index 7210178cb..f77e8153f 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -34,6 +34,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 warning. A styled quote spanning a conditional now follows the same section boundaries with or without extensions. acdc warns at the interrupting heading and resumes after the quote. Asciidoctor retains the content inside the quote. +- With block extensions active, a child syntax error in a compound spanning a + conditional or include now produces a warning, discards the body, and resumes + after the closing delimiter. If a block processor already ran in that body, + acdc reports an error at its invocation. For example, after a list item the + extension parser reports a missing term for `::: orphan`. The ordinary parser + retains that line as text, and asciidoctor reads `:` as its term. - Extensions can register a style for listing and literal blocks, read the body through `RawBlockInput` before substitutions, and return an ordinary block or consume the input. A style registered with `BlockStyle::compound` can also request that its body be parsed as children of an open block. - Block styles can report a warning at the styled block's source location and continue parsing with fallback content. diff --git a/acdc-parser/src/grammar/document/compound.rs b/acdc-parser/src/grammar/document/compound.rs index b6d2afaa7..2a1e8a0b9 100644 --- a/acdc-parser/src/grammar/document/compound.rs +++ b/acdc-parser/src/grammar/document/compound.rs @@ -2,11 +2,10 @@ use crate::{ Block, Error, - grammar::{ParserState, state::BlockContext}, + grammar::{ParserState, inline_processing::parse_error_warning}, }; use super::{ - RecognitionError, construction::DelimitedConstruction, coordinator::{BlockCursor, Execution}, delimited::{DelimitedParams, resolve_delimited_close}, @@ -26,32 +25,26 @@ impl BlockCursor { '_, impl FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, >, - ) -> Result, RecognitionError> { + ) -> Result<(), Error> { let mut params = construction.params; // The closing delimiter is resolved after the child cursor finishes. // Build the accepted shell with the existing builder without issuing an // unterminated-block warning at the temporary end of the input window. construction.params.close = Some((params.end, params.open_delim)); - let (mut block, request) = match construction.start(state) { - Ok(started) => started, - Err(error) => return Ok(Err(error)), + let (mut block, request) = construction.start(state)?; + let Some(request) = request else { + return Err(Error::Parse( + Box::new(state.create_error_source_location(block.location().clone())), + "streamed compound builder requested no child content".into(), + )); }; - match accepted.run(&mut block, state, output) { - Ok(true) => {} - Ok(false) => return Ok(Ok(())), - Err(error) => return Ok(Err(error)), + if !accepted.run(&mut block, state, output)? { + return Ok(()); } - let mut child = BlockCursor::content( - self.offset, - self.base_offset, - request.and_then(|r| r.parent_section_level), - ); - let context = request.map_or(BlockContext::Compound, |r| r.context); - let previous_context = std::mem::replace(&mut state.block_context, context); - let previous_scope = std::mem::replace( - &mut state.source_scope_offset, - params.content_start + params.offset, - ); + let mut child = + BlockCursor::content(self.offset, self.base_offset, request.parent_section_level); + let previous_context = std::mem::replace(&mut state.block_context, request.context); + let previous_scope = std::mem::replace(&mut state.source_scope_offset, request.offset); input.push_boundary(params.open_delim); let mut body = Vec::new(); let callbacks = accepted.block_callbacks(); @@ -60,66 +53,73 @@ impl BlockCursor { input.pop_boundary(); state.block_context = previous_context; state.source_scope_offset = previous_scope; - let mut end = match result { - Ok(Ok(end)) => end, - Ok(Err(error)) => return Ok(Err(error)), - // Report an executed processor before propagating a child grammar failure. - Err(error) => { - return match accepted.discarded_callback(callbacks, "Compound block content") { - Some(error) => Ok(Err(error)), - None => Err(error), + let (mut end, mut close, recovery) = match result { + Ok(Err(error)) => return Err(error), + Ok(Ok(end)) => { + let (end, close) = compound_close(state, end, params.open_delim); + let warning = if close.is_none() { + state.input.get(child.offset..).and_then(|tail| { + request.section_boundary_warning( + tail, + child.base_offset + child.offset, + state, + ) + }) + } else { + None }; + (end, close, warning) } - }; - let unparsed = state.input.get(child.offset..); - while let Some(line) = - source_tail(state, end).and_then(|tail| tail.split_inclusive('\n').next()) - { - if !line.trim().is_empty() { - break; + Err(error) => { + let warning = parse_error_warning( + &error, + state.input_offset(0), + state, + request.error_context, + ); + // A nested cursor may have changed windows before failing. Find + // the owner's close in the committed source, starting at its body. + (request.offset, None, Some(warning)) } - end += line.len(); - } - let mut close = source_tail(state, end) - .and_then(|tail| tail.split_inclusive('\n').next()) - .filter(|line| { - document_parser::source_block_close(line, state, params.open_delim, false).is_ok() - }); - // If the child sequence stopped at a heading, consume the rest of its - // quote without running processors in the discarded text. - let recovery = if close.is_none() - && let (Some(request), Some(tail)) = (request, unparsed) - && let Some(warning) = - request.section_boundary_warning(tail, child.base_offset + child.offset, state) - { + }; + if recovery.is_some() { if let Some(error) = accepted.discarded_callback(callbacks, request.error_context) { - return Ok(Err(error)); + return Err(error); } body.clear(); state.toc_entries.truncate(toc_start); - (end, close) = match input.delimited_boundary(end, params.open_delim, false, state) { - Ok(boundary) => boundary, - Err(error) => return Ok(Err(error)), - }; - Some(warning) - } else { - None - }; + (end, close) = input.delimited_boundary(end, params.open_delim, false, state)?; + } params.close = close.map(|_| (end - params.offset, params.open_delim)); params.end = end - params.offset + close.map_or(0, |line| line.trim_end_matches('\n').len()); - if let Err(error) = finish_compound(state, ¶ms, end, &mut block, body) { - return Ok(Err(error)); - } + finish_compound(state, ¶ms, end, &mut block, body)?; if let Some(warning) = recovery { state.add_warning(warning); } - self.base_offset = child.base_offset; - self.offset = params.end + params.offset - self.base_offset; + self.base_offset = params.offset; + self.offset = params.end; assign_block_caption(state, &mut block); output.push(block); - Ok(Ok(())) + Ok(()) + } +} + +fn compound_close<'a>( + state: &mut ParserState<'a>, + mut end: usize, + delimiter: &str, +) -> (usize, Option<&'a str>) { + while let Some(line) = + source_tail(state, end).and_then(|tail| tail.split_inclusive('\n').next()) + { + if !line.trim().is_empty() { + let close = document_parser::source_block_close(line, state, delimiter, false).is_ok(); + return (end, close.then_some(line)); + } + end += line.len(); } + (end, None) } fn finish_compound<'a>( diff --git a/acdc-parser/src/grammar/document/coordinator.rs b/acdc-parser/src/grammar/document/coordinator.rs index 7cfe771ba..ba76c17cc 100644 --- a/acdc-parser/src/grammar/document/coordinator.rs +++ b/acdc-parser/src/grammar/document/coordinator.rs @@ -289,13 +289,13 @@ impl BlockCursor { )); } BlockStepKind::Delimited(construction) if source.streaming_compound() => { - return self.construct_streamed_compound( + return Ok(self.construct_streamed_compound( source, state, construction, output, accepted, - ); + )); } kind @ (BlockStepKind::Block(_) | BlockStepKind::Delimited(_) diff --git a/acdc-parser/src/grammar/document/delimited.rs b/acdc-parser/src/grammar/document/delimited.rs index e76496431..c658e3090 100644 --- a/acdc-parser/src/grammar/document/delimited.rs +++ b/acdc-parser/src/grammar/document/delimited.rs @@ -77,7 +77,7 @@ impl<'a> ContentRequest<'a> { state.add_warning(warning); return; } - adjust_and_log_parse_error(error, self.source, self.offset, state, self.error_context); + adjust_and_log_parse_error(error, self.offset, state, self.error_context); } } @@ -282,22 +282,23 @@ fn parse_block_content<'input>( error_context: &'static str, parser: &mut impl ContentParser<'input>, ) -> Result>, Error> { - if content.trim().is_empty() { - Ok(Vec::new()) - } else { - parse_content( - state, - ContentRequest { - source: content, - offset: content_start + offset, - parent_section_level: block_metadata.parent_section_level, - context: BlockContext::Compound, - kind: ContentKind::Compound, - error_context, - }, - parser, - ) + // Empty source can be a streamed opener. Its builder still needs the + // child request to know the parsing context and where the body starts. + if !content.is_empty() && content.trim().is_empty() { + return Ok(Vec::new()); } + parse_content( + state, + ContentRequest { + source: content, + offset: content_start + offset, + parent_section_level: block_metadata.parent_section_level, + context: BlockContext::Compound, + kind: ContentKind::Compound, + error_context, + }, + parser, + ) } /// Source ranges and delimiters for a block. diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 83583284b..4bc48dca2 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -2190,7 +2190,7 @@ peg::parser! { #[no_eof] pub(in crate::grammar::document) rule first_description_list_item(offset: usize, base: usize, metadata: &BlockParsingMetadata<'input>) -> (DescriptionItemHead<'input>, Option>, usize) = resume_at(offset) description_list_ahead(base) parent:enter_description_list(base) - head:description_list_head(base, metadata) end:position!() { (head, parent, end) } + head:(description_list_head(base, metadata) / expected!("description list term")) end:position!() { (head, parent, end) } #[no_eof] pub(in crate::grammar::document) rule next_description_list_item(offset: usize, base: usize, metadata: &BlockParsingMetadata<'input>, parent: Option>) -> (Option>, usize) diff --git a/acdc-parser/src/grammar/document/table.rs b/acdc-parser/src/grammar/document/table.rs index c9351734a..d8c60fe8e 100644 --- a/acdc-parser/src/grammar/document/table.rs +++ b/acdc-parser/src/grammar/document/table.rs @@ -700,7 +700,6 @@ fn parse_normal_cell<'a>( result.unwrap_or_else(|error| { adjust_and_log_parse_error( &error, - content, offset, state, "Failed parsing table cell content as blocks", @@ -826,7 +825,6 @@ fn parse_table_cell_with_parser<'a>( .unwrap_or_else(|error| { adjust_and_log_parse_error( &error, - content, cell_start_offset, state, "Failed parsing table cell content as blocks", diff --git a/acdc-parser/src/grammar/inline_processing.rs b/acdc-parser/src/grammar/inline_processing.rs index 079311a40..380c1aef3 100644 --- a/acdc-parser/src/grammar/inline_processing.rs +++ b/acdc-parser/src/grammar/inline_processing.rs @@ -149,22 +149,10 @@ fn position_offset(input: &str, position: &Position) -> usize { /// This function converts those positions to the correct positions in the original document. fn adjust_peg_error_position( err: &peg::error::ParseError, - parsed_text: &str, doc_start_offset: usize, state: &ParserState, ) -> Error { - // Calculate the byte offset within the substring where the error occurred - let mut byte_offset = 0; - for (line_idx, line) in parsed_text.lines().enumerate() { - if line_idx + 1 == err.location.line { - byte_offset += err.location.column - 1; // column is 1-indexed - break; - } - byte_offset += line.len() + 1; // +1 for newline - } - - // Add the substring's starting position to get the absolute document position - let absolute_offset = doc_start_offset + byte_offset; + let absolute_offset = doc_start_offset + err.location.offset; // Resolve file and line from source ranges (for included content) let (file, position) = @@ -198,24 +186,32 @@ fn adjust_peg_error_position( /// Records a content-recovery warning at the original source position. pub(super) fn adjust_and_log_parse_error( err: &peg::error::ParseError, - parsed_text: &str, doc_start_offset: usize, state: &ParserState, context: &str, ) { - let adjusted_error = adjust_peg_error_position(err, parsed_text, doc_start_offset, state); - state.add_warning(crate::Warning::new( - crate::WarningKind::ContentRecovery { - message: format!("{context}: {adjusted_error}").into(), - }, - adjusted_error.source_location().cloned(), - )); + state.add_warning(parse_error_warning(err, doc_start_offset, state, context)); tracing::error!( doc_start_offset, "inline parse error; see returned diagnostics" ); } +pub(super) fn parse_error_warning( + err: &peg::error::ParseError, + doc_start_offset: usize, + state: &ParserState, + context: &str, +) -> crate::Warning { + let adjusted_error = adjust_peg_error_position(err, doc_start_offset, state); + crate::Warning::new( + crate::WarningKind::ContentRecovery { + message: format!("{context}: {adjusted_error}").into(), + }, + adjusted_error.source_location().cloned(), + ) +} + #[tracing::instrument(skip_all, fields(content_start = content_start, end = end, offset = offset))] fn preprocess_inline_content<'a>( state: &mut ParserState<'a>, @@ -505,7 +501,7 @@ fn parse_inline_syntax<'a>( let warnings = inline_peg_state.take_inline_warnings(); let mut inlines = inlines - .map_err(|error| adjust_peg_error_position(&error, text, location.absolute_start, state))?; + .map_err(|error| adjust_peg_error_position(&error, location.absolute_start, state))?; inlines = super::inlines::typography::resolve_plain( inlines, @@ -670,8 +666,7 @@ fn parse_bibliography_label<'a>( } state.add_warning(warning); } - let content = - parsed.map_err(|error| adjust_peg_error_position(&error, label, offset, state))?; + let content = parsed.map_err(|error| adjust_peg_error_position(&error, offset, state))?; let mut content = super::inlines::typography::resolve_plain(content, &child, false); for inline in &mut content { super::location_walk::walk_inline_locations_mut(inline, &mut |location| { diff --git a/acdc-parser/tests/extensions/recovery.rs b/acdc-parser/tests/extensions/recovery.rs index b2fb8894f..e99a21b0b 100644 --- a/acdc-parser/tests/extensions/recovery.rs +++ b/acdc-parser/tests/extensions/recovery.rs @@ -5,6 +5,7 @@ use std::sync::{ use acdc_parser::{ CompatibilityMode, Error, Options, WarningKind, + ast::{BlockKind, BlockRef}, extensions::{ BlockBuilder, BlockMacro, BlockMacroOutput, DocumentEditor, MacroExecutionContext, MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, @@ -13,9 +14,8 @@ use acdc_parser::{ use super::TestResult; -/// Native parsing recovers each source by dropping the content that holds -/// `greet::[]` at the given line. -const DISCARDED: [(&str, u32); 7] = [ +/// The extension reader discards content containing `greet::[]` at the given line. +const DISCARDED: [(&str, u32); 8] = [ // A `[quote]` body inherits the section context and stops at `== B`. ( "= Doc\n\n== A\n\n[quote]\n____\ngreet::[]\n\n== B\n\ntext\n____\n\nAfter.", @@ -45,6 +45,11 @@ const DISCARDED: [(&str, u32); 7] = [ "== A\n\n[quote]\n____\ngreet::[]\n\nifdef::x[]\nX.\nendif::[]\n\n== B\n\ntext\n____", 5, ), + // The child list has a description marker with no term. + ( + "====\ngreet::[]\n\nifdef::x[]\nX.\nendif::[]\n\n* Item\n::: orphan\n====", + 2, + ), ]; fn greet_registry(calls: &Arc) -> Result> { @@ -135,3 +140,71 @@ fn recovery_without_executed_macros_keeps_native_content_recovery() -> TestResul } Ok(()) } + +#[rstest::rstest] +#[case::quote("[quote]\n____", "____")] +#[case::example("====", "====")] +fn compound_child_grammar_failure_recovers_through_the_closing_delimiter( + #[case] open: &str, + #[case] close: &str, + #[values("", "ifdef::missing[]\nomitted\nendif::[]\n\n")] split: &str, + #[values(CompatibilityMode::Asciidoctor, CompatibilityMode::Draft)] mode: CompatibilityMode, +) -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let registry = greet_registry(&calls)?; + let options = Options::builder().with_compatibility_mode(mode).build()?; + let source = format!( + "== Parent\n\n{open}\n=== Inner\n\n{split}* item\n::: orphan\n\ngreet::discarded[]\n{close}\n\n== After\n\ngreet::after[]" + ); + let parsed = registry.parse(&source, &options)?.finish()?; + let [warning] = parsed.warnings() else { + return Err(format!( + "expected one recovery warning for {source}: {:?}", + parsed.warnings() + ) + .into()); + }; + assert!( + matches!(&warning.kind, WarningKind::ContentRecovery { message } + if message.contains("expected description list term")) + ); + let failed_line = source + .lines() + .position(|line| line == "::: orphan") + .ok_or("missing malformed list item")? + + 1; + let location = warning + .location + .as_ref() + .ok_or("missing warning location")?; + assert_eq!(location.location.start.line as usize, failed_line); + assert_eq!(location.location.start.column, 1); + let doc = parsed.document(); + assert_eq!(doc.toc_entries().len(), 2); + let mut sections = doc.blocks(); + let Some(BlockKind::Section(parent)) = sections.next().map(BlockRef::kind) else { + return Err("missing parent section".into()); + }; + let mut blocks = parent.blocks(); + match blocks.next().map(BlockRef::kind) { + Some(BlockKind::Quote(quote)) => { + assert_eq!(quote.blocks().count(), 0); + } + Some(BlockKind::Example(example)) => { + assert_eq!(example.blocks().count(), 0); + } + _ => return Err("missing recovered compound".into()), + } + assert!(blocks.next().is_none()); + let Some(BlockKind::Section(after)) = sections.next().map(BlockRef::kind) else { + return Err("missing section after the delimiter".into()); + }; + assert!( + after + .blocks() + .any(|b| matches!(b.kind(), BlockKind::Paragraph(_))) + ); + assert!(sections.next().is_none()); + assert_eq!(calls.load(Ordering::Relaxed), 1); + Ok(()) +} From 46112ecbd3daa2f0a47fdb624d43238b1c79b081 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 10:34:50 +0100 Subject: [PATCH 52/55] fix(parser): recognize adjacent table delimiters in list attachments SC-587 --- acdc-parser/CHANGELOG.md | 4 + acdc-parser/src/grammar/document/peg.rs | 140 ++---------------- acdc-parser/src/grammar/document/table.rs | 2 - .../src/grammar/document/table/streaming.rs | 71 ++++----- .../tests/blocks/unterminated_tables.rs | 16 ++ acdc-parser/tests/extensions/parity.rs | 30 +++- acdc-parser/tests/extensions/recovery.rs | 12 +- 7 files changed, 97 insertions(+), 178 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index f77e8153f..c3cc44a57 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Adjacent matching table delimiters now produce an empty table without a + warning, matching asciidoctor. With extensions active, the table stays in its + list attachment and a preceding block macro runs once. + - Extensions can register full and short inline macros or a pair of custom delimiters. Registered calls in macro-enabled text retain their source span and arguments for conversion. A short macro receives its bracket content as diff --git a/acdc-parser/src/grammar/document/peg.rs b/acdc-parser/src/grammar/document/peg.rs index 4bc48dca2..d02132daa 100644 --- a/acdc-parser/src/grammar/document/peg.rs +++ b/acdc-parser/src/grammar/document/peg.rs @@ -1460,7 +1460,7 @@ peg::parser! { // Reuse block-start rules before selected attributes can register inline content. rule attribute_block_form(offset: usize) -> AttributeBlockForm<'input> = form:&(open:block_open() (eol() / ![_]) { AttributeBlockForm::Delimited(open.0, open.2) }) { form } - / &((table_delimiter() / comma_table_delimiter() / colon_table_delimiter()) (eol() / ![_])) { AttributeBlockForm::Table } + / &(table_delimiter() (eol() / ![_])) { AttributeBlockForm::Table } / &(media_block_ahead_true() / at_list_item_start() / at_callout_list_item() / check_line_is_description_list(offset) / toc_block_ahead() / ("<<<" &eol()*<2,2>) / "> " / thematic_break_marker()) { AttributeBlockForm::NonParagraph } @@ -1752,14 +1752,6 @@ peg::parser! { rule sidebar_delimiter() -> &'input str = delim:$("*"*<4,>) { delim } rule table_delimiter() -> &'input str = delim:$((['|' | ',' | ':' | '!'] "="*<3,>)) { delim } - // Opening rules select the table's default separator. Content scanning - // compares the complete opening token, retaining nested tables with a - // different delimiter in the outer table's body. - rule pipe_table_delimiter() -> &'input str = delim:$("|" "="*<3,>) { delim } - rule excl_table_delimiter() -> &'input str = delim:$("!" "="*<3,>) { delim } - rule comma_table_delimiter() -> &'input str = delim:$("," "="*<3,>) { delim } - rule colon_table_delimiter() -> &'input str = delim:$(":" "="*<3,>) { delim } - rule pass_delimiter() -> &'input str = delim:$("+"*<4,>) { delim } rule markdown_code_delimiter() -> &'input str = delim:$("`"*<3,>) { delim } rule quote_delimiter() -> &'input str = delim:$("_"*<4,>) { delim } @@ -1772,135 +1764,27 @@ peg::parser! { } rule until_table_delimiter(open_delim: &str) -> &'input str - = content:$((!(eol() matching_table_delimiter(open_delim)) [_])*) { content } + = &matching_table_delimiter(open_delim) { "" } + / content:$((!(eol() matching_table_delimiter(open_delim)) [_])*) { content } rule markdown_language() -> &'input str = lang:$((['a'..='z'] / ['A'..='Z'] / ['0'..='9'] / "_" / "+" / "-")+) { lang } - // Table block dispatcher - tries each delimiter-specific variant in order. - // This enables nested tables: |=== outer can contain !=== inner because - // each rule only looks for its own closing delimiter. - // - // Terminated variants are tried first; unterminated fallbacks only match - // when an opening delimiter runs to end-of-input without a close. rule table_block(start: usize, offset: usize, block_metadata: &BlockParsingMetadata<'input>) -> Result, Error> = params:table_params(start, offset) { parse_table_block_impl(¶ms, state, block_metadata) } + // A matching delimiter closes even an empty table. Without one the + // body runs to EOF, including when the opener itself is the last line. rule table_params(start: usize, offset: usize) -> TableParseParams<'input> - = pipe_table_params(start, offset) - / excl_table_params(start, offset) - / comma_table_params(start, offset) - / colon_table_params(start, offset) - / unterminated_pipe_table_params(start, offset) - / unterminated_excl_table_params(start, offset) - / unterminated_comma_table_params(start, offset) - / unterminated_colon_table_params(start, offset) - - rule pipe_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:pipe_table_delimiter() eol() - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) - { - TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: "|", - closing: TableClosing::Terminated { close_delim, close_start }, - } - } - - rule excl_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:excl_table_delimiter() eol() - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) - { - TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: "!", - closing: TableClosing::Terminated { close_delim, close_start }, - } - } - - rule comma_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:comma_table_delimiter() eol() - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) - { - TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: ",", - closing: TableClosing::Terminated { close_delim, close_start }, - } - } - - rule colon_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:colon_table_delimiter() eol() - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - eol() close_start:position!() close_delim:matching_table_delimiter(open_delim) - { - TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: ":", - closing: TableClosing::Terminated { close_delim, close_start }, - } - } - - // Unterminated table fallbacks: match an opening table delimiter - // that runs to end-of-input without a closing delimiter. These - // alternatives are tried only after all terminated variants fail, - // so a document with a valid close never takes this path. When - // taken, `parse_table_block_impl` emits an `UnterminatedTable` - // warning and still produces a table, matching asciidoctor's - // recovery behavior. - // - // The `(eol() / ![_])` after the open delimiter accepts both - // `|===\n...` and `|===`: the preprocessor's `normalize` - // strips a single trailing newline (mirroring `str::lines`), so a - // file ending with just `|===\n` reaches the grammar as `|===`. - rule unterminated_pipe_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:pipe_table_delimiter() (eol() / ![_]) - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - ![_] - { - TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: "|", - closing: TableClosing::Unterminated, - } - } - - rule unterminated_excl_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:excl_table_delimiter() (eol() / ![_]) - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - ![_] - { - TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: "!", - closing: TableClosing::Unterminated, - } - } - - rule unterminated_comma_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:comma_table_delimiter() (eol() / ![_]) - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - ![_] - { - TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: ",", - closing: TableClosing::Unterminated, - } - } - - rule unterminated_colon_table_params(start: usize, offset: usize) -> TableParseParams<'input> - = table_start:position!() open_delim:colon_table_delimiter() (eol() / ![_]) - content_start:position!() content:until_table_delimiter(open_delim) content_end:position!() - ![_] + = table_start:position!() open_delim:table_delimiter() (eol() / ![_]) + content_start:position!() content:until_table_delimiter(open_delim) + closing:(eol()? close_start:position!() close_delim:matching_table_delimiter(open_delim) { + TableClosing::Terminated { close_delim, close_start } + })? { TableParseParams { - start, offset, table_start, content_start, content_end, end: span_end, - open_delim, content, default_separator: ":", - closing: TableClosing::Unterminated, + start, offset, table_start, content_start, end: span_end, open_delim, content, + default_separator: &open_delim[..1], closing: closing.unwrap_or(TableClosing::Unterminated), } } diff --git a/acdc-parser/src/grammar/document/table.rs b/acdc-parser/src/grammar/document/table.rs index d8c60fe8e..43046b229 100644 --- a/acdc-parser/src/grammar/document/table.rs +++ b/acdc-parser/src/grammar/document/table.rs @@ -41,7 +41,6 @@ pub(super) struct TableParseParams<'a> { pub(super) offset: usize, pub(super) table_start: usize, pub(super) content_start: usize, - pub(super) content_end: usize, pub(super) end: usize, pub(super) open_delim: &'a str, pub(super) content: &'a str, @@ -301,7 +300,6 @@ fn parse_table_with_cells<'input>( offset, table_start, content_start, - content_end: _content_end, end, open_delim, content, diff --git a/acdc-parser/src/grammar/document/table/streaming.rs b/acdc-parser/src/grammar/document/table/streaming.rs index 3c33010e0..32e3ccb30 100644 --- a/acdc-parser/src/grammar/document/table/streaming.rs +++ b/acdc-parser/src/grammar/document/table/streaming.rs @@ -20,9 +20,9 @@ use super::super::{ source::SourceInput, }; use super::{ - CellParser, InitialAttributes, PreparedTableCellParagraph, TableClosing, TableSettings, - construction::TableConstruction, parse_table_cell_with_parser, parse_table_with_cells, - table_settings, + CellParser, InitialAttributes, PreparedTableCellParagraph, TableClosing, TableParseParams, + TableSettings, construction::TableConstruction, parse_table_cell_with_parser, + parse_table_with_cells, table_settings, }; struct CellReader<'i, 'h, 'callback, 'a, F> { @@ -342,21 +342,7 @@ impl BlockCursor { cells: HashMap::new(), }; let (end, close) = reader.collect(input, state, start, accepted)?; - params.end = end - params.offset + close.map_or(0, str::len); - params.content_end = end.saturating_sub(usize::from(close.is_some())) - params.offset; - params.content = - retain_body(state, start, params.content_end + params.offset).ok_or_else(|| { - Error::Extension( - Box::new(state.create_error_source_location(location)), - "missing committed table source".into(), - ) - })?; - params.closing = close.map_or(TableClosing::Unterminated, |close_delim| { - TableClosing::Terminated { - close_delim, - close_start: end - params.offset, - } - }); + params.finish_stream(state, end, close)?; let mut parser = CompletedCells { cells: reader.cells, parser: super::super::coordinator::CursorContent { accepted }, @@ -410,23 +396,7 @@ impl BlockCursor { } end += line.len(); } - params.end = end - params.offset + close.map_or(0, str::len); - params.content_end = end.saturating_sub(usize::from(close.is_some())) - params.offset; - params.content = - retain_body(state, start, params.content_end + params.offset).ok_or_else(|| { - Error::Extension( - Box::new( - state.create_error_source_location(state.create_location(start, start)), - ), - "missing buffered table source".into(), - ) - })?; - params.closing = close.map_or(TableClosing::Unterminated, |close_delim| { - TableClosing::Terminated { - close_delim, - close_start: end - params.offset, - } - }); + params.finish_stream(state, end, close)?; self.offset = params.end; self.base_offset = params.offset; let (mut block, content) = construction.start(state)?; @@ -442,3 +412,34 @@ impl BlockCursor { Ok(()) } } + +impl<'a> TableParseParams<'a> { + fn finish_stream( + &mut self, + state: &ParserState<'a>, + end: usize, + close: Option<&'a str>, + ) -> Result<(), Error> { + let start = self.content_start + self.offset; + let body = retain_body(state, start, end).ok_or_else(|| { + let location = state.create_block_location(self.start, self.end, self.offset); + Error::Extension( + Box::new(state.create_error_source_location(location)), + "missing committed table source".into(), + ) + })?; + self.content = if close.is_some() { + body.strip_suffix('\n').unwrap_or(body) + } else { + body + }; + self.end = end - self.offset + close.map_or(0, str::len); + self.closing = close.map_or(TableClosing::Unterminated, |close_delim| { + TableClosing::Terminated { + close_delim, + close_start: end - self.offset, + } + }); + Ok(()) + } +} diff --git a/acdc-parser/tests/blocks/unterminated_tables.rs b/acdc-parser/tests/blocks/unterminated_tables.rs index e68aac81f..d4027f130 100644 --- a/acdc-parser/tests/blocks/unterminated_tables.rs +++ b/acdc-parser/tests/blocks/unterminated_tables.rs @@ -152,3 +152,19 @@ fn empty_open_delimiter_at_eof() -> TestResult { ); Ok(()) } + +#[rstest::rstest] +fn adjacent_matching_delimiters_close_an_empty_table( + #[values("|===", "!===", ",===", ":====")] delimiter: &str, +) -> TestResult { + let source = format!("{delimiter}\n{delimiter}"); + let parsed = acdc_parser::parse(&source, &Options::default())?; + assert_eq!(parsed.warnings(), &[]); + let block = parsed.document().blocks().next().ok_or("missing table")?; + let acdc_parser::ast::BlockKind::Table(table) = block.kind() else { + return Err("expected an empty table".into()); + }; + assert_eq!(table.rows().count(), 0); + assert!(table.close_delimiter_location().is_some()); + Ok(()) +} diff --git a/acdc-parser/tests/extensions/parity.rs b/acdc-parser/tests/extensions/parity.rs index 4bad89555..a66b7d1ac 100644 --- a/acdc-parser/tests/extensions/parity.rs +++ b/acdc-parser/tests/extensions/parity.rs @@ -18,9 +18,10 @@ fn greet_registry(calls: &Arc) -> Result, _: &mut MacroExecutionContext| { + move |invocation: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { calls.fetch_add(1, Ordering::SeqCst); - Ok(BlockBuilder::paragraph("hello").into()) + // Echo the source so parity tests can compare the entire document. + Ok(BlockBuilder::paragraph(invocation.source.to_string()).into()) } }))?; Ok(builder.build()) @@ -194,3 +195,28 @@ fn streamed_styled_quote_retains_a_deeper_section() -> TestResult { } Ok(()) } + +#[rstest::rstest] +#[case::unordered("* item")] +#[case::description("term:: def")] +fn table_in_streamed_list_attachment( + #[case] item: &str, + #[values(CompatibilityMode::Draft, CompatibilityMode::Asciidoctor)] mode: CompatibilityMode, +) -> TestResult { + let calls = Arc::new(AtomicUsize::new(0)); + let registry = greet_registry(&calls)?; + let options = Options::builder().with_compatibility_mode(mode).build()?; + let source = format!( + "{item}\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n|===\n|===\n====\n\nAfter." + ); + let ordinary = acdc_parser::parse(&source, &options)?; + let extended = registry.parse(&source, &options)?.finish()?; + assert_eq!(calls.load(Ordering::Relaxed), 1); + assert!(ordinary.warnings().is_empty(), "{:?}", ordinary.warnings()); + assert_eq!(extended.warnings(), ordinary.warnings()); + assert_eq!( + serde_json::to_value(extended.document())?, + serde_json::to_value(ordinary.document())? + ); + Ok(()) +} diff --git a/acdc-parser/tests/extensions/recovery.rs b/acdc-parser/tests/extensions/recovery.rs index e99a21b0b..f3f41f844 100644 --- a/acdc-parser/tests/extensions/recovery.rs +++ b/acdc-parser/tests/extensions/recovery.rs @@ -15,7 +15,7 @@ use acdc_parser::{ use super::TestResult; /// The extension reader discards content containing `greet::[]` at the given line. -const DISCARDED: [(&str, u32); 8] = [ +const DISCARDED: [(&str, u32); 6] = [ // A `[quote]` body inherits the section context and stops at `== B`. ( "= Doc\n\n== A\n\n[quote]\n____\ngreet::[]\n\n== B\n\ntext\n____\n\nAfter.", @@ -30,16 +30,6 @@ const DISCARDED: [(&str, u32); 8] = [ "= Doc\n\n== A\n\nterm:: def\n+\n[quote]\n____\ngreet::[]\n\n== B\n____\n\nAfter.", 9, ), - // The conditional makes the attached example stream. List recovery then - // drops the attachment after its child macro has executed. - ( - "* item\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n|===\n|===\n====\n\nAfter.", - 7, - ), - ( - "term:: def\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n|===\n|===\n====\n\nAfter.", - 7, - ), // The processor runs before a conditional splits the quote into reader windows. ( "== A\n\n[quote]\n____\ngreet::[]\n\nifdef::x[]\nX.\nendif::[]\n\n== B\n\ntext\n____", From c6016f9cbae4c809be9d19a2bb108069e90dd15e Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 10:38:57 +0100 Subject: [PATCH 53/55] fix(parser): stop streamed tables at the enclosing compound delimiter SC-587 --- acdc-parser/CHANGELOG.md | 4 +- acdc-parser/src/grammar/document/source.rs | 95 ++++++++++++++----- .../src/grammar/document/table/streaming.rs | 32 +++---- acdc-parser/tests/extensions/parity.rs | 23 ++++- 4 files changed, 107 insertions(+), 47 deletions(-) diff --git a/acdc-parser/CHANGELOG.md b/acdc-parser/CHANGELOG.md index c3cc44a57..7c551bd79 100644 --- a/acdc-parser/CHANGELOG.md +++ b/acdc-parser/CHANGELOG.md @@ -9,7 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Adjacent matching table delimiters now produce an empty table without a warning, matching asciidoctor. With extensions active, the table stays in its - list attachment and a preceding block macro runs once. + list attachment and a preceding block macro runs once. If the table has no + closing delimiter, acdc warns at its opener and resumes after the enclosing + compound block. - Extensions can register full and short inline macros or a pair of custom delimiters. Registered calls in macro-enabled text retain their source span diff --git a/acdc-parser/src/grammar/document/source.rs b/acdc-parser/src/grammar/document/source.rs index d73b7d973..14b28fd05 100644 --- a/acdc-parser/src/grammar/document/source.rs +++ b/acdc-parser/src/grammar/document/source.rs @@ -108,7 +108,16 @@ struct SourceStart<'a> { compound: bool, } +pub(super) enum DelimitedLine<'a> { + Body(&'a str), + End { + offset: usize, + close: Option<&'a str>, + }, +} + struct CellRead<'a> { + enclosing_compound: Option<&'a str>, separator: char, delimiter: &'a str, start: usize, @@ -166,18 +175,26 @@ impl<'a> SourceInput<'a> { { return Ok(None); } - let Some(line) = self.raw_line(offset, state)? else { + let result = self.read_line(offset, state); + self.failed |= result.is_err(); + let Some(line) = result? else { return Ok(None); }; if let Some(cell) = self.cells.last_mut() { - let boundary = if document_parser::source_block_close(line, state, cell.delimiter, true) - .is_ok() - { - Some(0) - } else { - crate::blocks::table::next_cell_boundary(line, cell.separator, offset != cell.start) + let boundary = + if closes_enclosing_compound(line, offset, cell.enclosing_compound, state) + || document_parser::source_block_close(line, state, cell.delimiter, true) + .is_ok() + { + Some(0) + } else { + crate::blocks::table::next_cell_boundary( + line, + cell.separator, + offset != cell.start, + ) .map(|(end, _, _)| end) - }; + }; if let Some(end) = boundary { cell.end = Some(offset + end); return Ok((end > 0).then(|| &line[..end])); @@ -186,16 +203,6 @@ impl<'a> SourceInput<'a> { Ok(Some(line)) } - pub(super) fn raw_line( - &mut self, - offset: usize, - state: &mut ParserState<'a>, - ) -> Result, Error> { - let result = self.read_line(offset, state); - self.failed |= result.is_err(); - result - } - fn read_line( &mut self, offset: usize, @@ -441,6 +448,35 @@ impl<'a> SourceInput<'a> { Ok(end.min(self.index.len())) } + pub(super) fn delimited_line( + &mut self, + offset: usize, + delimiter: &str, + table: bool, + state: &mut ParserState<'a>, + ) -> Result, Error> { + let Some(line) = self.line(offset, state)? else { + return Ok(DelimitedLine::End { + offset: offset.min(self.available_end()), + close: None, + }); + }; + if table && closes_enclosing_compound(line, offset, self.boundary(), state) { + // The newline before the enclosing close belongs to the compound. + return Ok(DelimitedLine::End { + offset: offset - 1, + close: None, + }); + } + if document_parser::source_block_close(line, state, delimiter, table).is_ok() { + return Ok(DelimitedLine::End { + offset, + close: Some(line), + }); + } + Ok(DelimitedLine::Body(line)) + } + /// Locate the matching close without constructing children, respecting table cell boundaries. pub(super) fn delimited_boundary( &mut self, @@ -449,13 +485,12 @@ impl<'a> SourceInput<'a> { table: bool, state: &mut ParserState<'a>, ) -> Result<(usize, Option<&'a str>), Error> { - while let Some(line) = self.line(offset, state)? { - if document_parser::source_block_close(line, state, delimiter, table).is_ok() { - return Ok((offset, Some(line))); + loop { + match self.delimited_line(offset, delimiter, table, state)? { + DelimitedLine::Body(line) => offset += line.len(), + DelimitedLine::End { offset, close } => return Ok((offset, close)), } - offset += line.len(); } - Ok((offset.min(self.index.len()), None)) } fn delimited_end( @@ -830,6 +865,7 @@ impl<'a> SourceInput<'a> { } pub(super) fn begin_cell(&mut self, separator: char, delimiter: &'a str, start: usize) { self.cells.push(CellRead { + enclosing_compound: self.boundary(), separator, delimiter, start, @@ -893,6 +929,19 @@ impl<'a> BlockInput<'a> for SourceInput<'a> { } } +fn closes_enclosing_compound( + line: &str, + offset: usize, + delimiter: Option<&str>, + state: &ParserState<'_>, +) -> bool { + delimiter.is_some_and(|delimiter| { + line.trim_end_matches('\n') == delimiter + && offset > 0 + && state.source_byte(offset - 1) == Some(b'\n') + }) +} + fn is_prose_line(line: &str) -> bool { line.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) && !line.contains("::") diff --git a/acdc-parser/src/grammar/document/table/streaming.rs b/acdc-parser/src/grammar/document/table/streaming.rs index 32e3ccb30..bf608be07 100644 --- a/acdc-parser/src/grammar/document/table/streaming.rs +++ b/acdc-parser/src/grammar/document/table/streaming.rs @@ -17,7 +17,7 @@ use super::super::{ coordinator::{BlockCursor, Execution}, delimited::{ContentParser, ContentRequest}, document_parser, - source::SourceInput, + source::{DelimitedLine, SourceInput}, }; use super::{ CellParser, InitialAttributes, PreparedTableCellParagraph, TableClosing, TableParseParams, @@ -249,10 +249,11 @@ impl<'a> TableReader<'a> { where F: FnMut(&mut Block<'a>, &mut ParserState<'a>, &mut Vec>) -> Result, { - while let Some(line) = input.raw_line(offset, state)? { - if document_parser::source_block_close(line, state, self.delimiter, true).is_ok() { - return Ok((offset, Some(line.trim_end_matches('\n')))); - } + loop { + let line = match input.delimited_line(offset, self.delimiter, true, state)? { + DelimitedLine::Body(line) => line, + DelimitedLine::End { offset, close } => return Ok((offset, close)), + }; if let Some((_, content_start, spec)) = next_cell_boundary(line, self.separator, true) { spec.validate(offset, offset + content_start) .map_err(|violation| { @@ -285,7 +286,6 @@ impl<'a> TableReader<'a> { offset += line.len(); } } - Ok((offset, None)) } } @@ -319,10 +319,9 @@ impl BlockCursor { ); } let start = params.content_start + params.offset; - let first = match input.raw_line(start, state) { - Ok(Some(line)) => line, - Ok(None) => "", - Err(error) => return Err(error), + let first = match input.delimited_line(start, params.open_delim, true, state)? { + DelimitedLine::Body(line) => line, + DelimitedLine::End { .. } => "", }; let mut lines = vec![first.trim_end_matches('\n')]; lines.extend(input.table_header_lookahead()); @@ -387,15 +386,7 @@ impl BlockCursor { { let params = &mut construction.params; let start = params.content_start + params.offset; - let mut end = start; - let mut close = None; - while let Some(line) = input.raw_line(end, state)? { - if document_parser::source_block_close(line, state, params.open_delim, true).is_ok() { - close = Some(line.trim_end_matches('\n')); - break; - } - end += line.len(); - } + let (end, close) = input.delimited_boundary(start, params.open_delim, true, state)?; params.finish_stream(state, end, close)?; self.offset = params.end; self.base_offset = params.offset; @@ -420,7 +411,10 @@ impl<'a> TableParseParams<'a> { end: usize, close: Option<&'a str>, ) -> Result<(), Error> { + // An opener immediately before the enclosing close has no body newline. + self.content_start = self.content_start.min(end - self.offset); let start = self.content_start + self.offset; + let close = close.map(|line| line.trim_end_matches('\n')); let body = retain_body(state, start, end).ok_or_else(|| { let location = state.create_block_location(self.start, self.end, self.offset); Error::Extension( diff --git a/acdc-parser/tests/extensions/parity.rs b/acdc-parser/tests/extensions/parity.rs index a66b7d1ac..df7575e0e 100644 --- a/acdc-parser/tests/extensions/parity.rs +++ b/acdc-parser/tests/extensions/parity.rs @@ -201,18 +201,33 @@ fn streamed_styled_quote_retains_a_deeper_section() -> TestResult { #[case::description("term:: def")] fn table_in_streamed_list_attachment( #[case] item: &str, + #[values( + "|===\n|===", + "|===", + "|===\n|Cell", + "[cols=a]\n|===\n|Cell", + "[separator=;]\n|===\n;Cell", + ",===\nCell", + "|===\n|====" + )] + table: &str, #[values(CompatibilityMode::Draft, CompatibilityMode::Asciidoctor)] mode: CompatibilityMode, ) -> TestResult { let calls = Arc::new(AtomicUsize::new(0)); let registry = greet_registry(&calls)?; let options = Options::builder().with_compatibility_mode(mode).build()?; - let source = format!( - "{item}\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n|===\n|===\n====\n\nAfter." - ); + let source = + format!("{item}\n+\n====\nifdef::x[]\nX.\nendif::[]\ngreet::[]\n{table}\n====\n\nAfter."); let ordinary = acdc_parser::parse(&source, &options)?; let extended = registry.parse(&source, &options)?.finish()?; assert_eq!(calls.load(Ordering::Relaxed), 1); - assert!(ordinary.warnings().is_empty(), "{:?}", ordinary.warnings()); + if table.ends_with("\n|===") { + assert_eq!(ordinary.warnings(), &[]); + } else { + assert!( + matches!(ordinary.warnings(), [warning] if matches!(warning.kind, WarningKind::UnterminatedTable { .. })) + ); + } assert_eq!(extended.warnings(), ordinary.warnings()); assert_eq!( serde_json::to_value(extended.document())?, From 6c80f1f899899256c43db172023c27ec93cde5e1 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 10:46:55 +0100 Subject: [PATCH 54/55] docs: describe the extension lifecycle and converter registration --- ARCHITECTURE.adoc | 55 ++++++++++++++++++++++++++++------------------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/ARCHITECTURE.adoc b/ARCHITECTURE.adoc index b791d7481..28ebdd993 100644 --- a/ARCHITECTURE.adoc +++ b/ARCHITECTURE.adoc @@ -88,8 +88,16 @@ It handles document structure (header, sections, blocks), block-level elements ( ==== Registered extensions -The parser owns an optional registry of block-macro descriptors and factories. -Recognition records invocations and their source-position attributes without +The parser owns an optional extension registry. Source preprocessors edit the +normalized entry text before the reader interprets directives. Include processors +can supply bytes for a resolved target under the reader's access and size limits. +Block styles receive a preprocessed listing or literal body and can emit an +ordinary block, consume the input, or ask the parser to read child blocks. +Reference normalizers can rewrite a cross-reference target before resolution. +The link:acdc-parser/README.adoc#registered-extensions[parser guide] describes +the ordering and limits of these callbacks. + +Block-macro recognition records invocations and their source-position attributes without calling extension code during speculative grammar matching. The host runs macros once at committed block boundaries in source order, applying requested attribute changes before later conditionals and includes, then repairs captions and catalogs. @@ -117,8 +125,9 @@ input. Selected packages preserve selection order and their registration order. `Pipeline` coordinates parser-owned source processing, committed callbacks, tree processors, and finalization for strings, files, and readers. Conversion -prepares deferred display content through the shared display service before -calling the backend. CLI batches, stdin, terminal output, and pagers use these +prepares deferred display content and expands surviving registered inline macros +before calling the backend. A copied title or catalog label reuses the expansion +of its original invocation. CLI batches, stdin, terminal output, and pagers use these same entry points. Inactive pipelines call the ordinary parser directly. Working sessions permit checked edits through document-local handles. Borrowed @@ -140,12 +149,20 @@ Native block renderers are also immutable registrations with fresh mutable handlers per conversion. `Extensions` combines parser and renderer capabilities; renderer-only selections retain ordinary parsing. Backends dispatch selected renderers in order and use ordinary rendering when every handler declines. +An accepting renderer can replace the block or delegate once to wrap the output +of the remaining renderers and the backend. HTML supplies streaming output, diagnostics, metadata escaping, and caption/title services. Renderers read attributes from the active traversal so accepted body assignments apply in source order and cell-local values expire on exit. Selected renderers supply their CSP script hashes. No handler can edit the shared parsed document through this rendering interface. +Full HTML documents run docinfo hooks at the head, header, and footer, after +file-based docinfo at each position. A hook supplies trusted backend markup and +escapes any document values it inserts. For converters that support UTF-8 text +output, selecting a postprocessor buffers the completed document. Postprocessors +edit it in registration order before the pipeline writes it to the destination. + ==== Inline preprocessing Inline content needs special handling, as specified in https://gitlab.eclipse.org/eclipse/asciidoc-lang/asciidoc-lang/-/blob/main/spec/sdrs/sdr-005-formal-grammar-for-inline-syntax.adoc[SDR-005: Formal Grammar for Inline Syntax]. @@ -206,7 +223,7 @@ Programmatically constructed nodes can carry caller-supplied or default location === Stage 3: converters Converters (`converters/`) transform the AST into various output formats. -They implement the `Processable` trait in link:converters/core/src/lib.rs[`converters/core`]. +They implement the `Converter` trait in link:converters/core/src/lib.rs[`converters/core`]. The trait owns converter setup and conversion; parser options are validated before parsing. The converters are: @@ -324,23 +341,17 @@ Reindented includes retain preprocessed byte offsets, so use their original line === Adding new converters -If you want to add a new converter, implement the `Processable` trait. The trait requires: - -* `document_attributes_defaults()` - Provide converter-specific default attributes (optional override) -* `new()` - Initialize the converter with its options and a parser options builder -* `convert()` - Convert a parsed document, writing output to the destination -* `document_attributes()` - Access the document attributes - -The best way to understand how this works is to look at an existing converter. -The Terminal converter (`converters/terminal/src/lib.rs`) is a good starting point - it's relatively straightforward and shows all the essential patterns. - -To add a new converter: - -. Create a new crate under `converters/` -. Add dependencies on `acdc-converters-core` and `acdc-parser` -. Define your options and error types -. Implement the `Processable` trait -. Walk the AST to generate your output format +Implement `acdc_converters_core::Converter` in a crate under `converters/`. +Its constructor configures the parser options, including the backend's intrinsic +attributes. Its `write_to()` method renders a prepared document to the supplied +writer and reports warnings through the diagnostic sink. The +link:converters/terminal/src/lib.rs[terminal converter] implements this contract. + +To expose a statically linked converter by name, publish a `ConverterSpec` with +its canonical name, aliases, and supported variants. The application registers +the spec and its runner in a `ConverterRegistry`. It resolves the selection +before reading input so only the selected runner constructs a converter. +See the link:converters/core/src/registry.rs[registration example]. === Adding new grammar rules From 1a814cb71fa594169be3b1dd59ad3e6fde8200af Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Mon, 23 Nov 2026 11:48:00 +0100 Subject: [PATCH 55/55] feat(converters): target output hooks by backend family or variant Let renderers, docinfo hooks, and text postprocessors select a canonical backend family or a single variant. Preserve existing string registrations and include CSP hashes only for matching HTML renderers. --- converters/README.adoc | 35 ++++++ converters/core/CHANGELOG.md | 2 + converters/core/src/backend.rs | 43 ++++++- converters/core/src/docinfo.rs | 20 +++- converters/core/src/lib.rs | 9 +- converters/core/src/pipeline.rs | 10 +- converters/core/src/pipeline/registrations.rs | 52 +++++++-- converters/core/src/postprocess.rs | 49 ++++++-- converters/core/src/render.rs | 16 ++- converters/core/tests/postprocessing.rs | 7 +- converters/html/CHANGELOG.md | 2 + converters/html/src/lib.rs | 18 ++- converters/html/tests/render_extensions.rs | 105 +++++++++++++++++- converters/markdown/CHANGELOG.md | 2 + converters/markdown/src/lib.rs | 6 +- converters/markdown/tests/integration_test.rs | 67 ++++++++++- 16 files changed, 399 insertions(+), 44 deletions(-) diff --git a/converters/README.adoc b/converters/README.adoc index e8f3a154f..781f715ce 100644 --- a/converters/README.adoc +++ b/converters/README.adoc @@ -69,6 +69,41 @@ Native block renderers use the same selection. They receive a fresh handler for each conversion and can use the backend's streaming output, title/caption, and metadata services. Declined blocks use ordinary rendering. +=== Targeting output hooks + +Use `BackendTarget::family("html")` for every HTML variant, or +`BackendTarget::variant("html", "semantic")` for semantic HTML alone. +`BlockRenderer::for_target`, `DocinfoHook::for_target`, and +`TextPostprocessor::for_target` accept the same targets. Use canonical family +and variant names from the converter registration. For example, the CLI shortcut +`html5s` selects the `html` family and the `semantic` variant, and +`--backend md --variant cm` selects `markdown` and `commonmark`. + +[source,rust] +---- +use acdc_converters_core::{BackendTarget, postprocess::TextPostprocessor}; + +let footer = TextPostprocessor::for_target( + BackendTarget::variant("markdown", "gfm"), + |output, _, _| { + output.push_str("\nGenerated with acdc.\n"); + Ok(()) + }, +); +---- + +Matching hooks run in registration order within each selected package. +HTML includes script hashes from matching block renderers and runs docinfo +hooks only for a full document. The string constructors for block renderers +and docinfo hooks select a family. The string constructor for text +postprocessors selects the converter's display name: `"html"` selects standard +HTML, `"html5s"` selects semantic HTML, and `"markdown"` selects both Markdown +variants. + +A converter with variants implements `Converter::hook_target()` to report its +canonical family and current variant. A converter without variants defaults to +its `Converter::name()` as the family. + == Development prerequisites Converter tests are run with `cargo nextest run --all-features`. The terminal diff --git a/converters/core/CHANGELOG.md b/converters/core/CHANGELOG.md index da3d86bdb..2fcdc8df1 100644 --- a/converters/core/CHANGELOG.md +++ b/converters/core/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Output hooks can target every variant of a backend family or a single canonical variant through `BackendTarget` and the `for_target` constructors. + - Applications can register statically linked converters, resolve names and variants before parsing, and explicitly replace a registration. - Selected UTF-8 postprocessors can edit complete output in order before it reaches its destination. Conversions stream as usual when no matching processor is selected. diff --git a/converters/core/src/backend.rs b/converters/core/src/backend.rs index 175a64252..369ccb439 100644 --- a/converters/core/src/backend.rs +++ b/converters/core/src/backend.rs @@ -1,9 +1,50 @@ -//! Backend profiles and their intrinsic document attributes. +//! Backend hook targets and intrinsic document attributes. use acdc_parser::AttributeValue; use crate::Doctype; +/// Canonical converter family and optional variant used to select output hooks. +/// Family registrations apply to every variant. Variant registrations require +/// both names to match. Use registration names such as `html` and `semantic`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BackendTarget<'a> { + /// Canonical family name, such as `html` or `markdown`. + pub family: &'a str, + /// Canonical variant name, such as `semantic` or `commonmark`. + pub variant: Option<&'a str>, +} + +impl<'a> BackendTarget<'a> { + /// Select the whole family, or identify a converter without variants. + #[must_use] + pub const fn family(family: &'a str) -> Self { + Self { + family, + variant: None, + } + } + + /// Select or identify one variant within a family. + #[must_use] + pub const fn variant(family: &'a str, variant: &'a str) -> Self { + Self { + family, + variant: Some(variant), + } + } + + pub(crate) fn matches(self, active: BackendTarget<'_>) -> bool { + self.family == active.family && (self.variant.is_none() || self.variant == active.variant) + } +} + +impl<'a, S: AsRef + ?Sized> From<&'a S> for BackendTarget<'a> { + fn from(family: &'a S) -> Self { + Self::family(family.as_ref()) + } +} + /// Intrinsic properties of a converter backend. /// /// These values mirror Asciidoctor's backend traits. Applying them makes the diff --git a/converters/core/src/docinfo.rs b/converters/core/src/docinfo.rs index d956d64e6..7e12a3520 100644 --- a/converters/core/src/docinfo.rs +++ b/converters/core/src/docinfo.rs @@ -3,7 +3,7 @@ use std::{fmt, sync::Arc}; use acdc_parser::ast::DocumentRef; -use crate::{Diagnostics, TraversalContext, render::RenderError}; +use crate::{BackendTarget, Diagnostics, TraversalContext, render::RenderError}; /// Full HTML supports these positions, in order. Embedded HTML has no document frame. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -39,14 +39,14 @@ pub type DocinfoProcessor = /// A docinfo factory for an explicitly selected backend family. #[derive(Clone)] pub struct DocinfoHook { - pub(crate) backend: &'static str, + pub(crate) target: BackendTarget<'static>, pub(crate) factory: Arc Box + Send + Sync>, } impl fmt::Debug for DocinfoHook { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("DocinfoHook") - .field("backend", &self.backend) + .field("target", &self.target) .finish_non_exhaustive() } } @@ -55,12 +55,24 @@ impl DocinfoHook { /// Create one mutable callback per full document, shared by its insertion points. /// Registration and embedded conversions never execute the factory. pub fn new(backend: &'static str, factory: impl Fn() -> F + Send + Sync + 'static) -> Self + where + F: FnMut(DocinfoContext<'_>, &mut Diagnostics<'_>) -> Result, RenderError> + + 'static, + { + Self::for_target(BackendTarget::family(backend), factory) + } + + /// Register a factory for a canonical backend family or one of its variants. + pub fn for_target( + target: BackendTarget<'static>, + factory: impl Fn() -> F + Send + Sync + 'static, + ) -> Self where F: FnMut(DocinfoContext<'_>, &mut Diagnostics<'_>) -> Result, RenderError> + 'static, { Self { - backend, + target, factory: Arc::new(move || Box::new(factory())), } } diff --git a/converters/core/src/lib.rs b/converters/core/src/lib.rs index f1cb75051..180ec7dfa 100644 --- a/converters/core/src/lib.rs +++ b/converters/core/src/lib.rs @@ -69,7 +69,7 @@ pub mod visitor; mod warning; pub mod xref; -pub use backend::BackendProfile; +pub use backend::{BackendProfile, BackendTarget}; pub use doctype::Doctype; pub use document_attributes::TraversalContext; pub use inline_text::InlineTextTransform; @@ -663,6 +663,13 @@ pub trait Converter<'a>: Sized { #[must_use] fn name(&self) -> &'static str; + /// Canonical family and active variant for output-hook selection. + /// Converters with variants override this independently of their display name. + #[must_use] + fn hook_target(&self) -> BackendTarget<'_> { + BackendTarget::family(self.name()) + } + /// Whether completed output can be delivered to a selected UTF-8 text processor. /// The default keeps opaque and binary converters on their own output paths. fn supports_text_output(&self) -> bool { diff --git a/converters/core/src/pipeline.rs b/converters/core/src/pipeline.rs index 4806a7557..551a28260 100644 --- a/converters/core/src/pipeline.rs +++ b/converters/core/src/pipeline.rs @@ -155,7 +155,7 @@ impl<'options, C: Converter<'options>> Pipeline { fn has_postprocessors(&self) -> bool { self.extensions - .postprocessors(self.converter.name()) + .postprocessors(self.converter.name(), self.converter.hook_target()) .next() .is_some() } @@ -202,7 +202,10 @@ impl<'options, C: Converter<'options>> Pipeline { }, ) })?; - for processor in self.extensions.postprocessors(backend) { + for processor in self + .extensions + .postprocessors(backend, self.converter.hook_target()) + { (processor.process)(&mut text, context, diagnostics) .map_err(|source| IoError::other(PostprocessError::Callback { backend, source }))?; } @@ -298,6 +301,9 @@ impl<'options, C: Converter<'options>> Converter<'options> for Pipeline { fn name(&self) -> &'static str { self.converter.name() } + fn hook_target(&self) -> crate::BackendTarget<'_> { + self.converter.hook_target() + } fn supports_text_output(&self) -> bool { self.converter.supports_text_output() } diff --git a/converters/core/src/pipeline/registrations.rs b/converters/core/src/pipeline/registrations.rs index 3bd9a0661..0e3a411e2 100644 --- a/converters/core/src/pipeline/registrations.rs +++ b/converters/core/src/pipeline/registrations.rs @@ -1,6 +1,7 @@ use acdc_parser::extensions::Registry; use crate::{ + BackendTarget, docinfo::{DocinfoHook, DocinfoProcessor}, postprocess::TextPostprocessor, render::{BlockRenderer, RenderSession}, @@ -43,10 +44,14 @@ impl Extensions { self } - pub(super) fn postprocessors(&self, backend: &str) -> impl Iterator { + pub(super) fn postprocessors( + &self, + name: &'static str, + active: BackendTarget<'_>, + ) -> impl Iterator { self.postprocessors .iter() - .filter(move |p| p.backend == backend) + .filter(move |p| p.matches(name, active)) } /// Append a docinfo hook. At each insertion point hooks run in selection @@ -59,17 +64,26 @@ impl Extensions { /// Whether a backend family has selected renderers or supported docinfo hooks. #[must_use] - pub fn has_render_hooks(&self, backend: &str, full_document: bool) -> bool { - self.renderers.iter().any(|r| r.backend == backend) - || (full_document && self.docinfo.iter().any(|r| r.backend == backend)) + pub fn has_render_hooks<'a>( + &self, + backend: impl Into>, + full_document: bool, + ) -> bool { + let active = backend.into(); + self.renderers.iter().any(|r| r.target.matches(active)) + || (full_document && self.docinfo.iter().any(|r| r.target.matches(active))) } /// Instantiate docinfo processors for a backend's available insertion points. #[must_use] - pub fn docinfo_processors(&self, backend: &str) -> Vec> { + pub fn docinfo_processors<'a>( + &self, + backend: impl Into>, + ) -> Vec> { + let active = backend.into(); self.docinfo .iter() - .filter(|r| r.backend == backend) + .filter(|r| r.target.matches(active)) .map(|r| (r.factory)()) .collect() } @@ -89,22 +103,38 @@ impl Extensions { && self.postprocessors.is_empty() } - /// Trusted script hashes requested by selected HTML block renderers. + /// Trusted script hashes from renderers registered for the whole HTML family. pub fn html_script_hashes(&self) -> impl Iterator + '_ { + self.html_script_hashes_for_variant(None) + } + + /// Trusted hashes for renderers matching the active HTML family and variant. + pub fn html_script_hashes_for_variant<'a>( + &'a self, + variant: Option<&'a str>, + ) -> impl Iterator + 'a { + let active = BackendTarget { + family: "html", + variant, + }; self.renderers .iter() - .filter(|r| r.backend == "html") + .filter(move |r| r.target.matches(active)) .flat_map(|r| r.html_script_hashes().iter().copied()) } /// Construct document-local renderers for a backend family, in registration order. /// Other backends invoke no factories. Empty selections allocate no session. #[must_use] - pub fn render_session(&self, backend: &str) -> Option { + pub fn render_session<'a>( + &self, + backend: impl Into>, + ) -> Option { + let active = backend.into(); let processors: Vec<_> = self .renderers .iter() - .filter(|registration| registration.backend == backend) + .filter(|registration| registration.target.matches(active)) .map(|registration| (registration.factory)()) .collect(); (!processors.is_empty()).then_some(RenderSession::new(processors)) diff --git a/converters/core/src/postprocess.rs b/converters/core/src/postprocess.rs index bee2ee8ac..43195099d 100644 --- a/converters/core/src/postprocess.rs +++ b/converters/core/src/postprocess.rs @@ -1,9 +1,9 @@ //! Ordered transformations of one completed UTF-8 document. //! //! Selected hooks edit the rendered text in place after all docinfo insertions. -//! Register against the converter name: `html`, `html5s`, `markdown`, `manpage`, -//! or `terminal`. Both Markdown variants use `markdown`. Other converters can opt -//! in through [`crate::Converter::supports_text_output`]. +//! Use [`TextPostprocessor::for_target`] for a canonical family or variant. +//! [`TextPostprocessor::new`] matches the converter's display name. Other +//! converters can opt in through [`crate::Converter::supports_text_output`]. //! If rendering or a callback fails, the pipeline discards the text before writing //! the destination. Earlier diagnostics, companion files and other external effects //! persist. Once writing starts, ordinary destination I/O errors may leave partial output. @@ -12,7 +12,7 @@ use std::{fmt, path::Path, sync::Arc}; use acdc_parser::ast::DocumentRef; -use crate::{Diagnostics, render::RenderError}; +use crate::{BackendTarget, Diagnostics, render::RenderError}; /// The converter and paths used for this document. Streams can have no path. #[derive(Clone, Copy)] @@ -56,24 +56,30 @@ type Callback = dyn Fn(&mut String, PostprocessContext<'_>, &mut Diagnostics<'_> + Send + Sync; -/// A callback for one named backend. The pipeline calls it once per document. +#[derive(Debug, Clone, Copy)] +enum Target { + Name(&'static str), + Backend(BackendTarget<'static>), +} + +/// A callback for one named backend, family, or variant. The pipeline calls it once per document. /// Local variables are per call; explicitly captured shared state belongs to the author. #[derive(Clone)] pub struct TextPostprocessor { - pub(crate) backend: &'static str, + target: Target, pub(crate) process: Arc, } impl fmt::Debug for TextPostprocessor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TextPostprocessor") - .field("backend", &self.backend) + .field("target", &self.target) .finish_non_exhaustive() } } impl TextPostprocessor { - /// Register a complete-text transformation without executing it. + /// Match the exact display name returned by [`crate::Converter::name`]. pub fn new( backend: &'static str, process: impl Fn( @@ -86,8 +92,33 @@ impl TextPostprocessor { + 'static, ) -> Self { Self { - backend, + target: Target::Name(backend), process: Arc::new(process), } } + + /// Match a canonical family or one of its variants. + pub fn for_target( + target: BackendTarget<'static>, + process: impl Fn( + &mut String, + PostprocessContext<'_>, + &mut Diagnostics<'_>, + ) -> Result<(), RenderError> + + Send + + Sync + + 'static, + ) -> Self { + Self { + target: Target::Backend(target), + process: Arc::new(process), + } + } + + pub(crate) fn matches(&self, name: &str, active: BackendTarget<'_>) -> bool { + match self.target { + Target::Name(expected) => expected == name, + Target::Backend(target) => target.matches(active), + } + } } diff --git a/converters/core/src/render.rs b/converters/core/src/render.rs index 36573b3eb..c3b3b3c95 100644 --- a/converters/core/src/render.rs +++ b/converters/core/src/render.rs @@ -4,7 +4,7 @@ use std::{fmt, io::Write, sync::Arc}; use acdc_parser::ast::BlockRef; -use crate::{Diagnostics, Options, TraversalContext}; +use crate::{BackendTarget, Diagnostics, Options, TraversalContext}; /// A native renderer or host-service failure, preserving its original source. pub type RenderError = Box; @@ -12,7 +12,7 @@ pub type RenderError = Box; /// A backend-specific renderer factory. Constructing it executes no processor. #[derive(Clone)] pub struct BlockRenderer { - pub(crate) backend: &'static str, + pub(crate) target: BackendTarget<'static>, html_script_hashes: &'static [&'static str], pub(crate) factory: Arc Box + Send + Sync>, } @@ -21,7 +21,7 @@ impl fmt::Debug for BlockRenderer { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("BlockRenderer") - .field("backend", &self.backend) + .field("target", &self.target) .finish_non_exhaustive() } } @@ -32,9 +32,17 @@ impl BlockRenderer { pub fn new( backend: &'static str, factory: impl Fn() -> P + Send + Sync + 'static, + ) -> Self { + Self::for_target(BackendTarget::family(backend), factory) + } + + /// Register a factory for a canonical backend family or one of its variants. + pub fn for_target( + target: BackendTarget<'static>, + factory: impl Fn() -> P + Send + Sync + 'static, ) -> Self { Self { - backend, + target, html_script_hashes: &[], factory: Arc::new(move || Box::new(factory())), } diff --git a/converters/core/tests/postprocessing.rs b/converters/core/tests/postprocessing.rs index c211b7442..ac0ad8f1f 100644 --- a/converters/core/tests/postprocessing.rs +++ b/converters/core/tests/postprocessing.rs @@ -1,6 +1,6 @@ //! Check delivery boundaries and measure the output buffer independently of parser allocations. use acdc_converters_core::{ - Converter, Diagnostics, Options, OutputDestination, + BackendTarget, Converter, Diagnostics, Options, OutputDestination, pipeline::{ExtensionCatalog, Extensions, Pipeline}, postprocess::{PostprocessError, TextPostprocessor}, }; @@ -111,9 +111,14 @@ fn only_selected_postprocessors_allocate_a_complete_output_buffer() -> TestResul .with_postprocessor(TextPostprocessor::new("other", |_, _, _| { Err("unexpected callback".into()) })); + let wrong_variant = Extensions::default().with_postprocessor(TextPostprocessor::for_target( + BackendTarget::variant("chunked", "alternate"), + |_, _, _| Err("unexpected variant callback".into()), + )); for (extensions, active) in [ (Extensions::default(), false), (wrong, false), + (wrong_variant, false), ( catalog .select(["first", "second", "first"])? diff --git a/converters/html/CHANGELOG.md b/converters/html/CHANGELOG.md index 6ca485157..897cefd5b 100644 --- a/converters/html/CHANGELOG.md +++ b/converters/html/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Block renderers, docinfo hooks, and text postprocessors can select both HTML variants with `BackendTarget::family("html")`, or just `standard` or `semantic` with `BackendTarget::variant`. Only matching renderers contribute CSP script hashes. + - Applications can register this converter using its built-in backend names and variant choices. - Selected text postprocessors can transform a complete HTML document or embedded fragment after rendering. diff --git a/converters/html/src/lib.rs b/converters/html/src/lib.rs index 7f2f36fc9..cf0c3a3d0 100644 --- a/converters/html/src/lib.rs +++ b/converters/html/src/lib.rs @@ -10,7 +10,8 @@ use std::{ #[cfg(feature = "highlighting")] use acdc_converters_core::substitutions::TextBoundaries; use acdc_converters_core::{ - BackendProfile, Converter as _, Diagnostics, Options, TraversalContext, WarningSource, + BackendProfile, BackendTarget, Converter as _, Diagnostics, Options, TraversalContext, + WarningSource, registry::{ConverterSpec, Variant}, section::contains_index_section, xref::XrefGuard, @@ -327,6 +328,7 @@ impl<'a> Converter<'a> { ) -> Result<(), Error> { let prepared = acdc_converters_core::display::prepare(doc)?; let document = prepared.document(); + let active = self.hook_target(); let converter = Converter { toc_entries: document.toc_entries().map(TocEntry::from).collect(), references: document.references().into(), @@ -351,9 +353,11 @@ impl<'a> Converter<'a> { index_term_counter: Rc::new(Cell::new(0)), index_catalog_counter: Rc::new(Cell::new(0)), index_entries: Rc::new(RefCell::new(Vec::new())), - extension_script_hashes: extensions.html_script_hashes().collect(), + extension_script_hashes: extensions + .html_script_hashes_for_variant(active.variant) + .collect(), render_session: extensions - .render_session("html") + .render_session(active) .map(|session| Rc::new(RefCell::new(session))), variant: self.variant, }; @@ -365,7 +369,7 @@ impl<'a> Converter<'a> { diagnostics.reborrow(), ); if !options.embedded { - visitor.docinfo_processors = extensions.docinfo_processors("html"); + visitor.docinfo_processors = extensions.docinfo_processors(active); } acdc_converters_core::visitor::DocumentVisitor::visit_document( &mut visitor, @@ -582,7 +586,7 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { &self, extensions: &acdc_converters_core::pipeline::Extensions, ) -> bool { - extensions.has_render_hooks("html", !self.options.embedded()) + extensions.has_render_hooks(self.hook_target(), !self.options.embedded()) } fn write_to_with_extensions( @@ -631,6 +635,10 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { true } + fn hook_target(&self) -> BackendTarget<'_> { + BackendTarget::variant("html", self.variant.as_str()) + } + fn name(&self) -> &'static str { match self.variant { HtmlVariant::Semantic => "html5s", diff --git a/converters/html/tests/render_extensions.rs b/converters/html/tests/render_extensions.rs index c35c3caa5..4f9dfdf97 100644 --- a/converters/html/tests/render_extensions.rs +++ b/converters/html/tests/render_extensions.rs @@ -6,15 +6,18 @@ use std::{ sync::{ Arc, Mutex, atomic::{AtomicUsize, Ordering}, + mpsc, }, }; use acdc_converters_core::{ - Converter as _, Diagnostics, Options, + BackendTarget, Converter as _, Diagnostics, Options, + docinfo::{DocinfoContext, DocinfoHook, DocinfoPosition}, pipeline::{ExtensionCatalog, Extensions, Pipeline}, + postprocess::TextPostprocessor, render::{BlockRenderProcessor, BlockRenderer, Next, RenderContext, RenderError}, }; -use acdc_converters_html::Converter; +use acdc_converters_html::{Converter, HtmlVariant}; use acdc_parser::{ Options as ParserOptions, ast::{BlockKind, BlockRef}, @@ -273,3 +276,101 @@ fn decorators_wrap_the_next_handler_and_declines_only_emit_diagnostics() -> Test assert_eq!(warnings.len(), 1); Ok(()) } + +#[test] +fn variant_target_filters_renderers_docinfo_factories_and_csp() -> TestResult { + const HASH: &str = "sha256-0123456789abcdef"; + let semantic = BackendTarget::variant("html", "semantic"); + let renders = Arc::new(AtomicUsize::new(0)); + let frames = Arc::new(AtomicUsize::new(0)); + let renderer_count = Arc::clone(&renders); + let docinfo_count = Arc::clone(&frames); + let renderer = BlockRenderer::for_target(semantic, move || { + renderer_count.fetch_add(1, Ordering::SeqCst); + Counter { + calls: Rc::new(Cell::new(0)), + } + }) + .with_html_script_hashes(&[HASH]); + let docinfo = DocinfoHook::for_target(semantic, move || { + docinfo_count.fetch_add(1, Ordering::SeqCst); + |ctx: DocinfoContext<'_>, _: &mut Diagnostics<'_>| { + Ok((ctx.position == DocinfoPosition::Footer) + .then(|| "".to_owned())) + } + }); + let renderer_only = Extensions::default().with_renderer(renderer); + let docinfo_only = Extensions::default().with_docinfo(docinfo.clone()); + let selection = renderer_only.clone().with_docinfo(docinfo); + for variant in [HtmlVariant::Standard, HtmlVariant::Semantic] { + let selected = variant == HtmlVariant::Semantic; + for embedded in [false, true] { + let converter = Converter::new_with_variant( + Options::builder().embedded(embedded).build(), + ParserOptions::builder(), + variant, + )?; + assert_eq!(converter.uses_render_extensions(&renderer_only), selected); + assert_eq!( + converter.uses_render_extensions(&docinfo_only), + selected && !embedded + ); + let p = Pipeline::new(converter).with_extensions(selection.clone()); + let text = render(&p, "= Title\n:csp:\n\nParagraph.")?; + assert_eq!(text.contains("native:1"), selected); + assert_eq!( + text.contains(""), + selected && !embedded + ); + assert_eq!(text.contains(HASH), selected && !embedded); + } + } + assert_eq!(renders.load(Ordering::SeqCst), 2); + assert_eq!(frames.load(Ordering::SeqCst), 1); + Ok(()) +} + +#[test] +fn html_postprocessors_match_family_variant_and_existing_display_names_in_order() -> TestResult { + let (calls, recorded_calls) = mpsc::channel(); + let mut selection = Extensions::default(); + for (target, hook_name) in [ + (BackendTarget::family("html"), "family"), + (BackendTarget::variant("html", "semantic"), "semantic"), + (BackendTarget::variant("html", "standard"), "standard"), + (BackendTarget::family("html5s"), "wrong-family"), + ] { + let calls = calls.clone(); + selection = + selection.with_postprocessor(TextPostprocessor::for_target(target, move |_, _, _| { + calls.send(hook_name)?; + Ok(()) + })); + } + for name in ["html", "html5s"] { + let calls = calls.clone(); + selection = selection.with_postprocessor(TextPostprocessor::new(name, move |_, ctx, _| { + assert_eq!(ctx.backend, name); + calls.send(name)?; + Ok(()) + })); + } + for (variant, expected) in [ + (HtmlVariant::Standard, ["family", "standard", "html"]), + (HtmlVariant::Semantic, ["family", "semantic", "html5s"]), + ] { + let converter = Converter::new_with_variant( + Options::builder().embedded(true).build(), + ParserOptions::builder(), + variant, + )?; + let p = Pipeline::new(converter).with_extensions(selection.clone()); + assert_eq!( + p.hook_target(), + BackendTarget::variant("html", variant.as_str()) + ); + render(&p, "Paragraph.")?; + assert_eq!(recorded_calls.try_iter().collect::>(), expected); + } + Ok(()) +} diff --git a/converters/markdown/CHANGELOG.md b/converters/markdown/CHANGELOG.md index ca46f883e..63ae1981d 100644 --- a/converters/markdown/CHANGELOG.md +++ b/converters/markdown/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Text postprocessors can select CommonMark or GitHub Flavored Markdown independently with `BackendTarget::variant("markdown", "commonmark")` or `BackendTarget::variant("markdown", "gfm")`. + - Applications can register this converter using its built-in backend names and variant choices. - Selected text postprocessors can transform the completed Markdown for either variant. diff --git a/converters/markdown/src/lib.rs b/converters/markdown/src/lib.rs index 8490a893e..8f402ed88 100644 --- a/converters/markdown/src/lib.rs +++ b/converters/markdown/src/lib.rs @@ -110,7 +110,7 @@ use std::{ }; use acdc_converters_core::{ - BackendProfile, Diagnostics, Options, TraversalContext, WarningSource, + BackendProfile, BackendTarget, Diagnostics, Options, TraversalContext, WarningSource, registry::{ConverterSpec, Variant}, section::contains_index_section, visitor::DocumentVisitor, @@ -406,6 +406,10 @@ impl<'a> acdc_converters_core::Converter<'a> for Converter<'a> { true } + fn hook_target(&self) -> BackendTarget<'_> { + BackendTarget::variant("markdown", self.variant.as_str()) + } + fn name(&self) -> &'static str { "markdown" } diff --git a/converters/markdown/tests/integration_test.rs b/converters/markdown/tests/integration_test.rs index 3a9f55e5b..a2e4363c5 100644 --- a/converters/markdown/tests/integration_test.rs +++ b/converters/markdown/tests/integration_test.rs @@ -1,8 +1,14 @@ -use std::path::{Path, PathBuf}; +use std::{ + io, + path::{Path, PathBuf}, + sync::mpsc, +}; use acdc_converters_core::{ - Converter as _, Diagnostics, GeneratorMetadata, Options as ConverterOptions, Warning, - WarningSource, + BackendTarget, Converter as _, Diagnostics, GeneratorMetadata, Options as ConverterOptions, + Warning, WarningSource, + pipeline::{Extensions, Pipeline}, + postprocess::TextPostprocessor, }; use acdc_converters_dev::output::remove_lines_trailing_whitespace; use acdc_converters_html as html; @@ -17,6 +23,61 @@ mod support; type Error = Box; +#[test] +fn markdown_postprocessors_match_canonical_family_and_variant_in_order() -> Result<(), Error> { + let (calls, recorded_calls) = mpsc::channel(); + let name_calls = calls.clone(); + let mut selection = Extensions::default().with_postprocessor(TextPostprocessor::new( + "markdown", + move |_, ctx, _| { + assert_eq!(ctx.backend, "markdown"); + name_calls.send("markdown")?; + Ok(()) + }, + )); + for (target, hook_name) in [ + (BackendTarget::family("markdown"), "family"), + (BackendTarget::variant("markdown", "gfm"), "gfm"), + ( + BackendTarget::variant("markdown", "commonmark"), + "commonmark", + ), + (BackendTarget::variant("markdown", "cm"), "alias"), + (BackendTarget::variant("html", "gfm"), "other-family"), + ] { + let calls = calls.clone(); + selection = + selection.with_postprocessor(TextPostprocessor::for_target(target, move |_, _, _| { + calls.send(hook_name)?; + Ok(()) + })); + } + for (variant, expected) in [ + ( + MarkdownVariant::CommonMark, + ["markdown", "family", "commonmark"], + ), + ( + MarkdownVariant::GitHubFlavored, + ["markdown", "family", "gfm"], + ), + ] { + let converter = Converter::new(ConverterOptions::default(), ParserOptions::builder())? + .with_variant(variant); + let p = Pipeline::new(converter).with_extensions(selection.clone()); + let doc = p.parse("Paragraph.")?; + p.write_to( + doc.document(), + io::sink(), + None, + None, + &mut Diagnostics::new(&p.warning_source(), &mut Vec::new()), + )?; + assert_eq!(recorded_calls.try_iter().collect::>(), expected); + } + Ok(()) +} + #[test] fn decoded_media_links_keep_literal_values_in_markdown() -> Result<(), Error> { let input = include_str!("fixtures/source/decoded_output_controls.adoc");