From d966016524e9b1fea41fbd85d086887ecef0bf65 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sun, 22 Nov 2026 20:21:18 +0100 Subject: [PATCH] feat(extensions): generate native linked lists of document elements Include the extension crate, CLI activation, documentation, CI and integration tests. --- .github/workflows/ci.yml | 15 +- AGENTS.md | 1 + Cargo.lock | 13 + Cargo.toml | 3 + acdc-cli/AGENTS.md | 2 +- acdc-cli/CHANGELOG.md | 7 + acdc-cli/Cargo.toml | 4 +- acdc-cli/README.adoc | 25 ++ acdc-cli/src/subcommands/convert.rs | 14 +- .../src/subcommands/convert/pipeline_tests.rs | 49 +++ acdc-cli/tests/lists.rs | 295 ++++++++++++++ converters/pdf/Cargo.toml | 1 + converters/pdf/tests/integration_test.rs | 43 ++ extensions/lists/CHANGELOG.md | 32 ++ extensions/lists/Cargo.toml | 24 ++ extensions/lists/README.adoc | 124 ++++++ .../lists/examples/generate_fixtures.rs | 23 ++ extensions/lists/examples/render.rs | 39 ++ extensions/lists/src/lib.rs | 211 ++++++++++ extensions/lists/tests/allocations.rs | 34 ++ extensions/lists/tests/composition.rs | 126 ++++++ extensions/lists/tests/defaults.rs | 379 ++++++++++++++++++ extensions/lists/tests/empty_sections.rs | 259 ++++++++++++ extensions/lists/tests/fixtures.rs | 26 ++ extensions/lists/tests/fixtures/default.adoc | 35 ++ .../tests/fixtures/default.semantic.html | 31 ++ .../tests/fixtures/default.standard.html | 37 ++ .../lists/tests/fixtures/empty_sections.adoc | 27 ++ .../fixtures/empty_sections.semantic.html | 19 + .../fixtures/empty_sections.standard.html | 27 ++ .../lists/tests/fixtures/include_warning.adoc | 3 + .../tests/fixtures/includes/unknown.adoc | 1 + extensions/lists/tests/fixtures/nested.adoc | 24 ++ .../lists/tests/fixtures/nested.semantic.html | 41 ++ .../lists/tests/fixtures/nested.standard.html | 39 ++ extensions/lists/tests/support/mod.rs | 45 +++ 36 files changed, 2073 insertions(+), 5 deletions(-) create mode 100644 acdc-cli/tests/lists.rs create mode 100644 extensions/lists/CHANGELOG.md create mode 100644 extensions/lists/Cargo.toml create mode 100644 extensions/lists/README.adoc create mode 100644 extensions/lists/examples/generate_fixtures.rs create mode 100644 extensions/lists/examples/render.rs create mode 100644 extensions/lists/src/lib.rs create mode 100644 extensions/lists/tests/allocations.rs create mode 100644 extensions/lists/tests/composition.rs create mode 100644 extensions/lists/tests/defaults.rs create mode 100644 extensions/lists/tests/empty_sections.rs create mode 100644 extensions/lists/tests/fixtures.rs create mode 100644 extensions/lists/tests/fixtures/default.adoc create mode 100644 extensions/lists/tests/fixtures/default.semantic.html create mode 100644 extensions/lists/tests/fixtures/default.standard.html create mode 100644 extensions/lists/tests/fixtures/empty_sections.adoc create mode 100644 extensions/lists/tests/fixtures/empty_sections.semantic.html create mode 100644 extensions/lists/tests/fixtures/empty_sections.standard.html create mode 100644 extensions/lists/tests/fixtures/include_warning.adoc create mode 100644 extensions/lists/tests/fixtures/includes/unknown.adoc create mode 100644 extensions/lists/tests/fixtures/nested.adoc create mode 100644 extensions/lists/tests/fixtures/nested.semantic.html create mode 100644 extensions/lists/tests/fixtures/nested.standard.html create mode 100644 extensions/lists/tests/support/mod.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b68b2b393..09da7e814 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: converters: - '.github/workflows/ci.yml' - 'converters/**' + - 'extensions/**' - 'acdc-parser/**' - 'Cargo.toml' - 'Cargo.lock' @@ -43,6 +44,7 @@ jobs: - 'acdc-execute/**' - 'acdc-parser/**' - 'converters/**' + - 'extensions/**' - 'Cargo.toml' - 'Cargo.lock' lsp: @@ -62,6 +64,7 @@ jobs: - '.github/workflows/ci.yml' - 'converters/core/**' - 'converters/pdf/**' + - 'extensions/lists/**' - 'acdc-parser/**' - 'Cargo.toml' - 'Cargo.lock' @@ -156,8 +159,10 @@ jobs: run: | sudo apt-get update sudo apt-get install -y groff mandoc - - name: Run converter tests - run: cargo nextest run -p acdc-converters-core -p acdc-converters-html -p acdc-converters-manpage -p acdc-converters-terminal -p acdc-converters-markdown --all-features --verbose + - name: Run converter and native extension tests + run: cargo nextest run -p acdc-converters-core -p acdc-converters-html -p acdc-converters-manpage -p acdc-converters-terminal -p acdc-converters-markdown -p acdc-extensions-lists --all-features --verbose + - name: Run native lists without optional capabilities + run: cargo nextest run -p acdc-extensions-lists --no-default-features --verbose - name: Run HTML tests - no default features run: cargo nextest run -p acdc-converters-html --no-default-features --verbose - name: Run HTML tests - highlighting @@ -201,6 +206,12 @@ jobs: run: cargo nextest run -p acdc-cli -p acdc-execute --all-features --verbose --no-tests warn --test-threads 1 # we've added this until https://github.com/nextest-rs/nextest/pull/3553 gets merged - name: Run execute-only tests run: cargo nextest run -p acdc-cli -p acdc-execute --no-default-features --features execute --verbose --test-threads 1 + - name: Test native lists availability and activation + run: | + cargo nextest run -p acdc-cli --no-default-features --features html --test lists --verbose + cargo nextest run -p acdc-cli --no-default-features --features html,lists --test lists --verbose + cargo nextest run -p acdc-cli --no-default-features --features terminal,lists -E 'test(pipeline_cli_native_lists)' --verbose + cargo check -p acdc-cli --no-default-features --features lists,network - name: Test execute with the parser network capability run: cargo nextest run -p acdc-execute --no-default-features --features acdc-parser/network -E 'test(substitution_is_independent_of_optional_capabilities)' --verbose - name: Smoke-test backend-only CLI builds diff --git a/AGENTS.md b/AGENTS.md index 4dcdf96fb..fa13469fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,7 @@ crate; check the CLI manifest for backend and tool selection. | `asg` | off | parser, CLI | Checked upstream and named acdc ASG export; independent of compatibility mode | | `tck` | off | CLI | Fixed Draft-mode TCK adapter; enables `asg` | | `network` | off | parser, html, pdf | Remote includes and HTML/PDF image access; caller permission and safe mode still apply | +| `lists` | off | CLI | Makes native `list-of` macros available; requires explicit `--extension lists` activation | | `highlighting` | off | html, terminal | giallo source highlighting | | `terminal` | off | html | Renders terminal previews into HTML; the cli exposes it as `html-terminal` | | `emulator` | off | terminal | Runs terminal output through a libghostty-vt terminal emulator and captures the rendered screen grid (static previews + session replays); the cli exposes it as `terminal-emulator` | diff --git a/Cargo.lock b/Cargo.lock index f9e46c0a9..036f326e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,6 +13,7 @@ dependencies = [ "acdc-converters-pdf", "acdc-converters-terminal", "acdc-execute", + "acdc-extensions-lists", "acdc-lint", "acdc-parser", "chrono", @@ -118,6 +119,7 @@ version = "0.1.0" dependencies = [ "acdc-converters-core", "acdc-converters-dev", + "acdc-extensions-lists", "acdc-parser", "acdc-pdf-images", "acdc-pdf-render", @@ -178,6 +180,17 @@ dependencies = [ "thiserror", ] +[[package]] +name = "acdc-extensions-lists" +version = "0.1.0" +dependencies = [ + "acdc-converters-core", + "acdc-converters-html", + "acdc-parser", + "serde_json", + "stats_alloc", +] + [[package]] name = "acdc-lint" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 8a727d2c6..badfea12c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = [ "converters/pdf", "converters/pdf/crates/*", "converters/terminal", + "extensions/lists", ] default-members = [ "acdc-cli", @@ -31,6 +32,7 @@ default-members = [ "converters/pdf", "converters/pdf/crates/*", "converters/terminal", + "extensions/lists", ] resolver = "2" @@ -50,6 +52,7 @@ acdc-converters-terminal = { path = "converters/terminal", default-features = fa acdc-execute = { path = "acdc-execute", default-features = false } acdc-lint = { path = "acdc-lint", default-features = false } acdc-parser = { path = "acdc-parser", default-features = false } +acdc-extensions-lists = { path = "extensions/lists", default-features = false } base64 = "0.23" chrono = "0.4" clap = { version = "4.5", features = ["derive"] } diff --git a/acdc-cli/AGENTS.md b/acdc-cli/AGENTS.md index 0ad2a4d59..6e2da1e3a 100644 --- a/acdc-cli/AGENTS.md +++ b/acdc-cli/AGENTS.md @@ -7,7 +7,7 @@ and explicit `subs=` settings work in every build. The former `pre-spec-subs` and `setext` Cargo features and `--setext` flag are removed. Asciidoctor mode supports Setext headings. See `acdc-parser/AGENTS.md` and `converters/AGENTS.md`. -`network` enables parser remote includes and forwards to selected execute, lint, +`network` enables parser remote includes and forwards to selected execute, lists, lint, HTML and PDF crates. HTML/PDF image access still follows the converter's network policy, caller permission and safe mode. diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 5e2b968a6..d362a74ca 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -11,6 +11,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Selected native text postprocessors run per input, including when multiple terminal documents share a pager. +- Builds with the optional `lists` feature accept `convert --extension lists` + for native linked lists of document elements across enabled backends. Files, + stdin, and batches preserve formatted titles, stable links, and empty-section + options. Compilation alone leaves calls inactive; unavailable selections fail + before input is read. The Ruby `enhanced_rendering` option is intentionally + unsupported because acdc always preserves title formatting. + - 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/Cargo.toml b/acdc-cli/Cargo.toml index d38c834b3..eecef26ce 100644 --- a/acdc-cli/Cargo.toml +++ b/acdc-cli/Cargo.toml @@ -18,6 +18,7 @@ doc = false [dependencies] acdc-converters-core.workspace = true acdc-execute = { workspace = true, optional = true } +acdc-extensions-lists = { workspace = true, optional = true } acdc-converters-html = { workspace = true, optional = true } acdc-lint = { workspace = true, optional = true } acdc-parser.workspace = true @@ -54,6 +55,7 @@ terminal = ["dep:acdc-converters-terminal"] # Terminal converter with ANSI co # Document tools lint = ["dep:acdc-lint"] # AsciiDoc lint command +lists = ["dep:acdc-extensions-lists"] # Native list-of block macros; activate with --extension lists # Syntax highlighting for source blocks in selected HTML and terminal backends. highlighting = [ @@ -77,7 +79,7 @@ asg = ["acdc-parser/asg"] # Checked upstream and acdc ASG expor tck = ["asg"] # AsciiDoc Test Compatibility Kit adapter # Network access -network = ["acdc-parser/network", "acdc-execute?/network", "acdc-lint?/network", "acdc-converters-pdf?/network", "acdc-converters-html?/network"] # Enable remote includes and embedded HTML/PDF images +network = ["acdc-parser/network", "acdc-execute?/network", "acdc-extensions-lists?/network", "acdc-lint?/network", "acdc-converters-pdf?/network", "acdc-converters-html?/network"] # Enable remote includes and embedded HTML/PDF images # Feature groups for convenience all-backends = ["html", "manpage", "markdown", "pdf", "terminal"] # Enable all output converters diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index d558dc300..5f1a332f3 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -128,6 +128,27 @@ 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 optional `lists` build feature makes `--extension lists` available for every +compiled backend. Build it with `cargo build -p acdc-cli --features lists`, then: + +[source,console] +.... +acdc convert --extension lists document.adoc +acdc convert --backend pdf --extension lists document.adoc +printf 'list-of::section[]\n\n== First section\n' | acdc convert --extension lists --stdin -o - +.... + +Use `list-of::image[]`, `list-of::table[]`, or another supported element name to +generate linked entries, including targets later in the document. Authored IDs +are preserved; generated IDs are deterministic and collision-safe. Titles retain +their formatting and source-position attributes. `hide_empty_section=true` (or +the first positional argument) removes the nearest section when no matching +blocks exist. String values such as `false` still enable hiding, matching the +Ruby extension. Omit the argument to keep the section. The Ruby +`enhanced_rendering` toggle is unsupported because formatting is automatic; +remove it when migrating. See the link:../extensions/lists/README.adoc[lists guide] +for supported contexts, arguments, library registration, and reference differences. + 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 @@ -515,6 +536,10 @@ echo '{"contents":"= Hello","path":"test.adoc","type":"block"}' \ | no | HTML terminal previews and session/replay rendering. +| `lists` +| no +| Makes native `list-of` macros available; select them with `--extension lists`. + | `terminal-emulator` | no | Ghostty-backed terminal session rendering; selects the terminal backend. diff --git a/acdc-cli/src/subcommands/convert.rs b/acdc-cli/src/subcommands/convert.rs index f3acb41df..1bc150d92 100644 --- a/acdc-cli/src/subcommands/convert.rs +++ b/acdc-cli/src/subcommands/convert.rs @@ -285,7 +285,19 @@ impl Args { } pub(crate) fn run(args: &Args) -> MietteResult<()> { - run_with_extensions(args, &ExtensionCatalog::default()) + let available = ExtensionCatalog::default(); + #[cfg(feature = "lists")] + let available = { + let mut available = available; + available + .register( + "lists", + acdc_extensions_lists::registry().map_err(|error| error::display(&error))?, + ) + .map_err(|error| error::display(&error))?; + available + }; + run_with_extensions(args, &available) } fn run_with_extensions(args: &Args, available: &ExtensionCatalog) -> MietteResult<()> { diff --git a/acdc-cli/src/subcommands/convert/pipeline_tests.rs b/acdc-cli/src/subcommands/convert/pipeline_tests.rs index 0e1b88401..3de4ea12c 100644 --- a/acdc-cli/src/subcommands/convert/pipeline_tests.rs +++ b/acdc-cli/src/subcommands/convert/pipeline_tests.rs @@ -233,6 +233,55 @@ fn pipeline_cli_terminal_reader_files_and_pager_share_processing() -> TestResult Ok(()) } +#[cfg(all(feature = "lists", feature = "terminal", unix))] +#[test] +fn pipeline_cli_native_lists_use_terminal_reader_and_pager_paths() -> TestResult { + let directory = tempfile::tempdir()?; + let source = "list-of::quote[]\n\n.Native title\n[#target]\n[quote]\n____\nQuoted.\n____\n"; + let input = directory.path().join("input.adoc"); + let reader_output = directory.path().join("reader.txt"); + let pager_output = directory.path().join("pager.txt"); + std::fs::write(&input, source)?; + let mut catalog = ExtensionCatalog::default(); + catalog.register("lists", acdc_extensions_lists::registry()?)?; + let selected = catalog.select(["lists"])?; + for mode in [ + acdc_parser::CompatibilityMode::Asciidoctor, + acdc_parser::CompatibilityMode::Draft, + ] { + 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().with_compatibility_mode(mode), + )?, + selected.as_ref(), + ); + assert_eq!( + run_terminal_reader(&converter, source.as_bytes(), || None)?.warning_count, + 0 + ); + let reader = std::fs::read_to_string(&reader_output)?; + assert_eq!(reader.matches("Native title").count(), 2, "{reader}"); + assert!(!reader.contains("list-of::")); + let child = pager(&pager_output)?; + assert_eq!( + run_terminal_reader(&converter, source.as_bytes(), || Some(child))?.warning_count, + 0 + ); + assert_eq!(std::fs::read_to_string(&pager_output)?, reader); + let child = pager(&pager_output)?; + assert_eq!( + run_terminal_through_pager(&converter, &options, std::slice::from_ref(&input), child)?, + 0 + ); + assert_eq!(std::fs::read_to_string(&pager_output)?, reader); + } + Ok(()) +} + /// A downstream converter chooses its own parser profile, serialization, and suffix. struct NativeJson { options: Options, diff --git a/acdc-cli/tests/lists.rs b/acdc-cli/tests/lists.rs new file mode 100644 index 000000000..0806c7b2e --- /dev/null +++ b/acdc-cli/tests/lists.rs @@ -0,0 +1,295 @@ +#![cfg(feature = "html")] + +use std::{ + error::Error, + fs, + io::{self, Write}, + path::Path, + process::{Command, Output, Stdio}, +}; + +type TestResult = Result<(), Box>; + +const SOURCE: &str = "= Lists\n:word: Early\n\nlist-of::quote[]\n\n.A *bold* {word} & title\n[#authored]\n[quote]\n____\nQuoted.\n____\n\n:word: Late\n"; + +fn run(directory: &Path, args: &[&str], input: Option<&str>) -> Result> { + let mut child = Command::new(env!("CARGO_BIN_EXE_acdc")) + .current_dir(directory) + .args(args) + .env_remove("ACDC_LOG") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + let written = child + .stdin + .take() + .ok_or("stdin")? + .write_all(input.unwrap_or_default().as_bytes()); + let output = child.wait_with_output()?; + if let Err(error) = written + && (error.kind() != io::ErrorKind::BrokenPipe || output.status.success()) + { + return Err(error.into()); + } + Ok(output) +} + +fn success(output: &Output) { + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn lists_are_inactive_without_explicit_selection() -> TestResult { + let directory = tempfile::tempdir()?; + fs::write(directory.path().join("inactive.adoc"), SOURCE)?; + for mode in ["asciidoctor", "draft"] { + for input in ["--stdin", "inactive.adoc"] { + let output = run( + directory.path(), + &[ + "convert", + "--backend", + "html", + "--compatibility-mode", + mode, + input, + "--embedded", + "--fail-on-warnings", + "-o", + "-", + ], + Some(SOURCE), + )?; + success(&output); + let html = String::from_utf8(output.stdout)?; + assert!(html.contains("list-of::quote[]")); + assert!(!html.contains("href=\"#authored\"")); + } + } + Ok(()) +} + +#[cfg(not(feature = "lists"))] +#[test] +fn lists_unavailable_selection_fails_before_reading_input() -> TestResult { + let directory = tempfile::tempdir()?; + for input in ["missing.adoc", "--stdin"] { + let output = run( + directory.path(), + &[ + "convert", + "--backend", + "html", + "--extension", + "lists", + input, + ], + Some("list-of::quote[enhanced_rendering=true]"), + )?; + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8(output.stderr)?; + assert!( + stderr.contains("extension `lists` is not available"), + "{stderr}" + ); + assert!(!stderr.contains("title formatting is automatic")); + assert_eq!(output.stdout, [] as [u8; 0]); + } + Ok(()) +} + +#[cfg(feature = "lists")] +#[test] +fn lists_files_batches_and_stdin_preserve_formatting_in_both_modes_and_variants() -> TestResult { + let directory = tempfile::tempdir()?; + fs::write(directory.path().join("first.adoc"), SOURCE)?; + fs::write( + directory.path().join("second.adoc"), + SOURCE.replace("Early", "Second"), + )?; + for mode in ["asciidoctor", "draft"] { + for variant in ["standard", "semantic"] { + let mut args = vec![ + "convert", + "--backend", + "html", + "--variant", + variant, + "--compatibility-mode", + mode, + "--extension", + "lists", + "--extension", + "lists", + "--embedded", + "--fail-on-warnings", + ]; + args.extend(["first.adoc", "second.adoc"]); + success(&run(directory.path(), &args, None)?); + for (file, word) in [("first.html", "Early"), ("second.html", "Second")] { + let html = fs::read_to_string(directory.path().join(file))?; + assert_eq!(html.matches("href=\"#authored\"").count(), 1, "{html}"); + assert!(html.contains(&format!("A bold {word} & title"))); + assert!(!html.contains("list-of::")); + assert!(!html.contains("<strong>")); + } + args.truncate(args.len() - 2); + args.extend(["--stdin", "-o", "-"]); + let output = run(directory.path(), &args, Some(SOURCE))?; + success(&output); + let html = String::from_utf8(output.stdout)?; + assert_eq!(html.matches("href=\"#authored\"").count(), 1); + assert!(html.contains("A bold Early & title")); + } + } + Ok(()) +} + +#[cfg(feature = "lists")] +#[test] +fn lists_warnings_retain_included_locations_and_batch_output() -> TestResult { + let directory = tempfile::tempdir()?; + fs::write(directory.path().join("entry.adoc"), "include::part.adoc[]")?; + fs::write(directory.path().join("part.adoc"), "\n\nlist-of::unknown[]")?; + fs::write(directory.path().join("good.adoc"), SOURCE)?; + let output = run( + directory.path(), + &[ + "convert", + "--backend", + "html", + "--extension", + "lists", + "--embedded", + "--fail-on-warnings", + "entry.adoc", + "good.adoc", + ], + None, + )?; + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8(output.stderr)?; + assert_eq!( + stderr.matches("unknown list-of element: unknown").count(), + 1, + "{stderr}" + ); + assert!(stderr.contains("part.adoc"), "{stderr}"); + assert!( + fs::read_to_string(directory.path().join("entry.html"))?.contains("list-of::unknown[]") + ); + assert!(fs::read_to_string(directory.path().join("good.html"))?.contains("href=\"#authored\"")); + Ok(()) +} + +#[cfg(feature = "lists")] +#[test] +fn lists_reject_enhanced_rendering_with_migration_guidance() -> TestResult { + let directory = tempfile::tempdir()?; + for mode in ["asciidoctor", "draft"] { + let output = run( + directory.path(), + &[ + "convert", + "--backend", + "html", + "--extension", + "lists", + "--compatibility-mode", + mode, + "--stdin", + "-o", + "-", + ], + Some("list-of::quote[enhanced_rendering=false]"), + )?; + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8(output.stderr)?; + assert!( + stderr.contains("does not support enhanced_rendering"), + "{stderr}" + ); + assert!(stderr.contains("remove this option"), "{stderr}"); + assert_eq!(output.stdout, [] as [u8; 0]); + } + Ok(()) +} + +#[cfg(feature = "lists")] +#[test] +fn lists_preserve_escaped_and_verbatim_calls() -> TestResult { + let directory = tempfile::tempdir()?; + let source = format!( + "{SOURCE}\n\\list-of::quote[]\n\n----\nlist-of::quote[]\n----\n\n....\nlist-of::quote[]\n....\n" + ); + let output = run( + directory.path(), + &[ + "convert", + "--extension", + "lists", + "--stdin", + "--embedded", + "-o", + "-", + ], + Some(&source), + )?; + success(&output); + let html = String::from_utf8(output.stdout)?; + assert_eq!(html.matches("href=\"#authored\"").count(), 1, "{html}"); + assert_eq!(html.matches("list-of::quote[]").count(), 3, "{html}"); + Ok(()) +} + +#[cfg(feature = "lists")] +#[test] +fn lists_render_ordinary_nodes_through_each_enabled_backend() -> TestResult { + let directory = tempfile::tempdir()?; + let source = "= lists(1)\n\n== NAME\nlists - native lists\n\n== SYNOPSIS\n*lists*\n\n== DESCRIPTION\n\nlist-of::quote[]\n\n.Uniquetarget\n[#authored]\n[quote]\n____\nQuoted.\n____\n"; + let backends: &[&str] = &[ + #[cfg(feature = "manpage")] + "manpage", + #[cfg(feature = "markdown")] + "markdown", + #[cfg(feature = "terminal")] + "terminal", + #[cfg(feature = "pdf")] + "pdf", + ]; + for backend in backends { + for mode in ["asciidoctor", "draft"] { + let mut args = vec![ + "convert", + "--backend", + backend, + "--extension", + "lists", + "--compatibility-mode", + mode, + "--stdin", + "--fail-on-warnings", + "-o", + "-", + ]; + if *backend == "terminal" { + args.push("--no-pager"); + } + let output = run(directory.path(), &args, Some(source))?; + success(&output); + if *backend == "pdf" { + assert!(output.stdout.starts_with(b"%PDF-")); + } else { + let text = String::from_utf8(output.stdout)?; + assert_eq!(text.matches("Uniquetarget").count(), 2, "{backend}: {text}"); + assert!(!text.contains("list-of::"), "{backend}: {text}"); + } + } + } + Ok(()) +} diff --git a/converters/pdf/Cargo.toml b/converters/pdf/Cargo.toml index 2033a37e1..410857039 100644 --- a/converters/pdf/Cargo.toml +++ b/converters/pdf/Cargo.toml @@ -26,6 +26,7 @@ unicode-width.workspace = true [dev-dependencies] acdc-converters-dev.workspace = true +acdc-extensions-lists.workspace = true pretty_assertions.workspace = true rstest.workspace = true diff --git a/converters/pdf/tests/integration_test.rs b/converters/pdf/tests/integration_test.rs index 4b1fac5f2..65bc5f785 100644 --- a/converters/pdf/tests/integration_test.rs +++ b/converters/pdf/tests/integration_test.rs @@ -19,6 +19,49 @@ use support::converter as cli_fixture_converter; type Error = Box; +#[test] +fn native_lists_keep_formatted_titles_and_real_pdf_destinations() -> Result<(), Error> { + let source = "= Lists\n:word: Early\n\nlist-of::quote[]\n\nlist-of::quote[]\n\n<<<\n\n.First *{word}* & title\n[#authored,reftext=Other]\n[quote]\n____\nFirst body.\n____\n\n<<<\n\n.Second title\n[quote]\n____\nSecond body.\n____\n\n:word: Late\n"; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let working = acdc_extensions_lists::registry()?.parse( + source, + &Options::builder().with_compatibility_mode(mode).build()?, + )?; + let ids: Vec<_> = working + .query() + .select(acdc_parser::extensions::BlockContext::Quote) + .filter_map(|view| view.output_id().map(str::to_owned)) + .collect(); + assert_eq!(ids.len(), 2); + assert_eq!(ids.first().map(String::as_str), Some("authored")); + let parsed = working.finish()?; + assert!(parsed.warnings().is_empty(), "{:?}", parsed.warnings()); + for _ in 0..2 { + let pdf = render_parsed(&parsed)?; + assert_eq!(pdf.get_pages().len(), 3); + let targets = named_destinations(&pdf)?; + for id in &ids { + assert!(targets.contains_key(id), "missing destination {id}"); + } + let pages = internal_link_pages(&pdf, 1)?; + assert!(pages.iter().all(|page| matches!(page, 2 | 3)), "{pages:?}"); + for target_page in [2, 3] { + assert!(pages.iter().filter(|page| **page == target_page).count() >= 2); + } + let text = pdf + .extract_text(&[1])? + .split_whitespace() + .collect::(); + assert_eq!(text.matches("FirstEarly&title").count(), 2, "{text}"); + assert_eq!(text.matches("Secondtitle").count(), 2, "{text}"); + assert!(!text.contains("Late")); + assert!(!text.contains("Other")); + assert!(!text.contains("list-of::")); + } + } + Ok(()) +} + #[test] fn table_footnotes_keep_distinct_pdf_targets_for_each_owner() -> Result<(), Error> { let source = include_str!("fixtures/source/table_cell_footnotes.adoc"); diff --git a/extensions/lists/CHANGELOG.md b/extensions/lists/CHANGELOG.md new file mode 100644 index 000000000..878c29029 --- /dev/null +++ b/extensions/lists/CHANGELOG.md @@ -0,0 +1,32 @@ +# Changelog + +## [Unreleased] + +- `list-of` requests can be interleaved with other deferred macros. Each macro's + handler receives its own calls in source order. + +- Documents with repeated `list-of` requests allocate less memory during conversion. + +- CLI builds with `lists` can select the extension with `--extension lists` for + any enabled converter. The library's optional `network` feature enables remote + includes under the parser's caller-permission and safe-mode rules. + +- Register `list-of::[]` to generate linked caption and title lines for + document elements through any converter. Existing IDs are preserved; generated + IDs are deterministic and reused by repeated requests. Unknown elements produce + a located warning and readable call text. Empty lists disappear while their + sections remain. +- Unknown-element recovery preserves the supplied arguments, quotes, and + unexpanded attribute references in the call text. +- `hide_empty_section` removes the nearest section only when no matching blocks + exist; untitled matching blocks keep it. The first positional slot selects the + same policy. As in the pinned Ruby reference, string values such as `false`, + `0`, and `""` enable hiding. Outside sections, only the empty output is removed. + Nested calls and table cells follow section scope, and pending calls inside a + removed section are canceled. Unlike the reference, extra nonempty positional + arguments are rejected and root-level hiding calls keep the document. +- Titles retain their parsed formatting and original attribute context. Unlike + the Ruby extension's default mode, rendered HTML tags are not copied into text + and escaped again. Uncaptioned titles appear once, as the link label. The Ruby + `enhanced_rendering` toggle is intentionally unsupported; supplying it reports + that title formatting is automatic and asks the caller to remove the option. diff --git a/extensions/lists/Cargo.toml b/extensions/lists/Cargo.toml new file mode 100644 index 000000000..6c4a08118 --- /dev/null +++ b/extensions/lists/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "acdc-extensions-lists" +version = "0.1.0" +edition.workspace = true +description = "Native linked lists of document elements for acdc" +readme = "README.adoc" +license = "MIT OR Apache-2.0" +publish = false + +[features] +default = [] +network = ["acdc-parser/network"] + +[dependencies] +acdc-parser.workspace = true + +[dev-dependencies] +acdc-converters-core.workspace = true +acdc-converters-html.workspace = true +serde_json.workspace = true +stats_alloc = "0.1" + +[lints] +workspace = true diff --git a/extensions/lists/README.adoc b/extensions/lists/README.adoc new file mode 100644 index 000000000..4be18c293 --- /dev/null +++ b/extensions/lists/README.adoc @@ -0,0 +1,124 @@ += Native lists extension for acdc + +`acdc-extensions-lists` implements `list-of::[]` through the native +extension API. Register `acdc_extensions_lists::registry()?` with the parser or +as `lists` in converter core's `ExtensionCatalog`, then attach the selected +extensions to a configured `Pipeline`. Each parse gets its own processor state. +The CLI exposes the same registrations through its optional `lists` build feature +and explicit `--extension lists` selection. + +[source,asciidoc] +---- +list-of::image[] + +.A diagram +[#diagram] +image::diagram.svg[] +---- + +The generated paragraph contains one linked line per titled or captioned target, +with explicit hard breaks. Captioned entries link their caption and put the title +after it. Other entries link their title. All backends render ordinary nodes. + +Supported element names are `image`, `table`, `listing`, `literal`, `example`, +`quote`, `verse`, `sidebar`, `open`, `pass`, `stem`, `audio`, `video`, `admonition`, +`paragraph`, `section`, `olist`, `ulist`, `dlist`, and `colist`. Selection includes +nested containers and AsciiDoc table cells, and follows semantic block styles. +Requests may precede their targets. Untitled, uncaptioned targets are omitted. + +Requests run in source order and capture their own membership and title context. +Later processors do not refresh those snapshots. The host preserves authored IDs, +assigns collision-safe deterministic IDs, reuses them for repeated requests, and +follows surviving targets if their IDs change. Final caption numbers come from +the host. Empty lists keep their containing section by default. +Unknown names return a located warning and retain the accepted `list-of` call +as literal text, including its arguments, quotes, and unexpanded target. + +== CLI activation + +[source,console] +---- +cargo build -p acdc-cli --features lists +acdc convert --extension lists document.adoc +acdc convert --extension lists --backend terminal --no-pager document.adoc +acdc convert --extension lists --stdin -o - < document.adoc +---- + +Select the relevant backend at build time too; for example, +`--features lists,terminal` or `--features lists,pdf`. Files, stdin, and batches +use the shared pipeline. Repeating `--extension lists` activates it once. +The feature is off by default. A compiled but unselected extension keeps ordinary +parsing behavior, and selecting an unavailable name fails before reading input. +The library's optional `network` feature enables parser remote includes; caller +permission and safe mode still apply. The CLI's `network` feature forwards it +without enabling another backend. + +== Empty-section behavior + +Use `list-of::image[hide_empty_section=true]` or `list-of::image[true]` to remove +the nearest containing section when there are no matching blocks. Matching +untitled blocks keep the section even though they produce no list entries. +Removing a section cancels pending calls in its subtree. Later calls observe the +surviving document; earlier list captures remain snapshots. + +The first positional slot maps to `hide_empty_section`, following the pinned +reference. Named arguments take precedence. Strings follow Ruby truthiness: +`false`, `0`, `nil`, and an explicitly empty quoted string all enable hiding. +Omit the argument to keep the section. Library-supplied boolean `false` and nil +attribute defaults disable hiding. Additional nonempty positional slots are +rejected; an empty slot does not shift a later argument into the first slot. + +Calls in nested containers remove the nearest containing section. A call outside +a section removes only its empty output. AsciiDoc table cells have their own +section scope and never remove an outer document section. The host repairs the +TOC, reference catalog, and footnotes; surviving section and caption ordinals are +preserved. + +== Reference and deliberate differences + +The reference is +https://github.com/Alwinator/asciidoctor-lists/blob/cd926c536bb0fd36985e1f7bff125e9b59fdbdb0/lib/asciidoctor-lists/extensions.rb[asciidoctor-lists at cd926c5], +characterized with Asciidoctor 2.0.26. The native extension uses deterministic IDs +instead of UUIDs. Titles retain ordinary parsed formatting and their original +attribute context. The Ruby default copies rendered title strings into newly +parsed AsciiDoc, which can expose escaped HTML tags. The native extension renders +the title once. A title with an explicitly empty caption appears once as a link; +the reference can duplicate it. Generated paragraphs retain authored block +metadata such as titles, IDs, and roles; the reference drops that metadata. + +The native extension hides the nearest section for nested calls. The reference +can remove an immediate container instead, and a root-level hiding call can +fail. Native root-level calls keep the surrounding document. `list-of::section[]` +selects actual sections; it excludes the document header, which the reference +can include with a link to a destination absent from embedded HTML. Unlike the +reference, additional nonempty positional arguments are rejected. + +Title formatting is always preserved in acdc. The Ruby `enhanced_rendering` +compatibility toggle is intentionally unsupported: remove that named argument +when migrating a call. Supplying it produces an error explaining that formatting +is automatic. There is no mode that reparses rendered backend markup as title +source. + +Custom captions containing `{counter:...}` currently retain that literal text, +as they do in ordinary acdc parsing. The pinned enhanced-rendering sample relies +on those counters; native formatted titles and bibliography links work after +removing the unsupported toggle, while counter expansion remains a parser and +conversion-session limitation. + +The link:./examples/render.rs[library example] renders a source file through the +shared HTML pipeline: + +[source,console] +---- +cargo run -p acdc-extensions-lists --example render -- document.adoc +---- + +New HTML expectations for this crate can be generated by exact source stem: + +[source,console] +---- +cargo run -p acdc-extensions-lists --example generate_fixtures --all-features -- empty_sections +---- + +Review every generated file. Existing expectations require approval before +regeneration, as elsewhere in the repository. diff --git a/extensions/lists/examples/generate_fixtures.rs b/extensions/lists/examples/generate_fixtures.rs new file mode 100644 index 000000000..977995df3 --- /dev/null +++ b/extensions/lists/examples/generate_fixtures.rs @@ -0,0 +1,23 @@ +//! Generate only this package's new, explicitly selected HTML expectations. + +use std::{fs, path::Path}; + +use acdc_converters_html::HtmlVariant; +use acdc_parser::CompatibilityMode; + +#[path = "../tests/support/mod.rs"] +mod support; + +fn main() -> Result<(), Box> { + let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + for name in std::env::args().skip(1) { + let source = fs::read_to_string(fixtures.join(format!("{name}.adoc")))?; + for variant in [HtmlVariant::Standard, HtmlVariant::Semantic] { + let output = support::render(&source, CompatibilityMode::Asciidoctor, variant)?; + let path = fixtures.join(format!("{name}.{}.html", variant.as_str())); + fs::write(&path, output)?; + println!("Generated {}", path.display()); + } + } + Ok(()) +} diff --git a/extensions/lists/examples/render.rs b/extensions/lists/examples/render.rs new file mode 100644 index 000000000..58d09f13c --- /dev/null +++ b/extensions/lists/examples/render.rs @@ -0,0 +1,39 @@ +//! Explicit native lists registration through the shared pipeline. + +use std::{error::Error, path::Path}; + +use acdc_converters_core::{ + Converter as _, Diagnostics, Options, + pipeline::{ExtensionCatalog, Pipeline}, +}; +use acdc_converters_html::Converter; +use acdc_parser::Options as ParserOptions; + +fn main() -> Result<(), Box> { + let path = std::env::args_os().nth(1).ok_or("provide a source file")?; + let mut available = ExtensionCatalog::default(); + available.register("lists", acdc_extensions_lists::registry()?)?; + let selected = available.select(["lists"])?.ok_or("empty selection")?; + let pipeline = Pipeline::new(Converter::new( + Options::builder().embedded(true).build(), + ParserOptions::builder(), + )?) + .with_extensions(selected); + let parsed = pipeline.parse_file(Path::new(&path))?; + 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/extensions/lists/src/lib.rs b/extensions/lists/src/lib.rs new file mode 100644 index 000000000..351b4eada --- /dev/null +++ b/extensions/lists/src/lib.rs @@ -0,0 +1,211 @@ +//! Native `list-of::[]` block macros. +//! +//! Register [`registry`] with the parser directly, or select it through converter +//! core's extension catalog and pipeline. Construction uses ordinary paragraphs, +//! cross references, and hard line breaks, so every backend shares the same list. + +use acdc_parser::{ + AttributeValue, Error, + ast::CaptionRef, + extensions::{ + BlockBuilder, BlockContext, BlockMacro, BlockMacroOutput, BlockMacroProcessor, + DeferredBlock, DisplayIntent, DocumentEditor, InlineSpec, MacroExecutionContext, + MacroInvocation, RegistrationError, Registry, TargetId, TreeProcessor, + TreeProcessorRegistration, + }, +}; + +/// Register the deferred macro and its document-local tree processor. +/// +/// # Errors +/// Returns an error if a built-in name conflicts with this registration. +pub fn registry() -> Result { + let mut builder = Registry::builder(); + builder.register( + BlockMacro::new("list-of", || Defer).with_positional_attributes(["hide_empty_section"]), + )?; + builder.register_tree_processor(TreeProcessorRegistration::for_macro("list-of", || Lists))?; + Ok(builder.build()) +} + +struct Defer; + +impl BlockMacroProcessor for Defer { + fn process( + &mut self, + invocation: &MacroInvocation<'_>, + _: &mut MacroExecutionContext, + ) -> Result { + if invocation.attributes.get("enhanced_rendering").is_some() { + return Err("list-of does not support enhanced_rendering; title formatting is automatic, so remove this option".into()); + } + if invocation.positional.iter().skip(1).any(Option::is_some) { + return Err("list-of supports one positional argument: hide_empty_section".into()); + } + Ok(BlockMacroOutput::Deferred) + } +} + +struct Lists; + +#[derive(Clone, Copy)] +enum EmptySection { + Keep, + Hide, +} + +enum Request { + Generate { + output: TargetId, + context: BlockContext, + empty_section: EmptySection, + }, + Unknown { + output: TargetId, + element: String, + source: String, + }, +} + +impl From<&DeferredBlock> for Request { + fn from(request: &DeferredBlock) -> Self { + let output = request.target().clone(); + let invocation = &request.invocation; + if let Some(context) = context(invocation.target.trim()) { + let empty_section = match invocation.attributes.get("hide_empty_section") { + None | Some(AttributeValue::Bool(false) | AttributeValue::None) => { + EmptySection::Keep + } + Some(_) => EmptySection::Hide, + }; + Self::Generate { + output, + context, + empty_section, + } + } else { + Self::Unknown { + output, + element: invocation.target.to_string(), + source: invocation.source.to_string(), + } + } + } +} + +impl Request { + fn output(&self) -> &TargetId { + match self { + Self::Generate { output, .. } | Self::Unknown { output, .. } => output, + } + } +} + +impl TreeProcessor for Lists { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let requests: Vec<_> = editor.deferred_blocks().map(Request::from).collect(); + for request in requests { + // A previous request may have removed the containing section and + // consumed every remaining request in its subtree. + if editor.query().get(request.output()).is_none() { + continue; + } + let (output, block_context, empty_section) = match request { + Request::Generate { + output, + context, + empty_section, + } => (output, context, empty_section), + Request::Unknown { + output, + element, + source, + } => { + editor.warn(&output, format!("unknown list-of element: {element}"))?; + editor.replace_placeholder(&output, BlockBuilder::paragraph(source))?; + continue; + } + }; + // Snapshot this request's membership before assigning IDs or editing + // the placeholder. Later requests observe earlier completed edits. + let mut found = false; + let entries: Vec<_> = editor + .query() + .select(block_context) + .filter_map(|view| { + found = true; + let captioned = has_caption(view.caption()); + (captioned || view.title().is_some()).then(|| { + ( + view.target().clone(), + if captioned { + DisplayIntent::CaptionAndTitle + } else { + DisplayIntent::Title + }, + ) + }) + }) + .collect(); + if entries.is_empty() { + if !found + && matches!(empty_section, EmptySection::Hide) + && let Some(section) = editor + .query() + .get(&output) + .and_then(|view| view.containing_section()) + .cloned() + { + editor.remove_section(§ion)?; + continue; + } + editor.discard_placeholder(&output)?; + continue; + } + let mut content = Vec::with_capacity(entries.len() * 2); + for (target, intent) in entries { + content.push(editor.capture(&target)?.display(intent)); + content.push(InlineSpec::LineBreak); + } + editor.replace_placeholder(&output, BlockBuilder::paragraph_inlines(content))?; + } + Ok(()) + } +} + +fn has_caption(caption: Option>) -> bool { + match caption { + Some(CaptionRef::Numbered { + number: Some(_), .. + }) => true, + Some(CaptionRef::Custom(text)) => !text.is_empty(), + Some(CaptionRef::CustomContent(content)) => !content.is_empty(), + _ => false, + } +} + +fn context(element: &str) -> Option { + Some(match element { + "image" => BlockContext::Image, + "table" => BlockContext::Table, + "listing" => BlockContext::Listing, + "literal" => BlockContext::Literal, + "example" => BlockContext::Example, + "quote" => BlockContext::Quote, + "verse" => BlockContext::Verse, + "sidebar" => BlockContext::Sidebar, + "open" => BlockContext::Open, + "pass" => BlockContext::Passthrough, + "stem" => BlockContext::Stem, + "audio" => BlockContext::Audio, + "video" => BlockContext::Video, + "admonition" => BlockContext::Admonition, + "paragraph" => BlockContext::Paragraph, + "section" => BlockContext::Section, + "olist" => BlockContext::OrderedList, + "ulist" => BlockContext::UnorderedList, + "dlist" => BlockContext::DescriptionList, + "colist" => BlockContext::CalloutList, + _ => return None, + }) +} diff --git a/extensions/lists/tests/allocations.rs b/extensions/lists/tests/allocations.rs new file mode 100644 index 000000000..a5a236d94 --- /dev/null +++ b/extensions/lists/tests/allocations.rs @@ -0,0 +1,34 @@ +use std::{alloc::System, fmt::Write, hint::black_box}; + +use acdc_parser::Options; +use stats_alloc::{INSTRUMENTED_SYSTEM, Region, StatsAlloc}; + +#[global_allocator] +static GLOBAL: &StatsAlloc = &INSTRUMENTED_SYSTEM; + +#[test] +fn repeated_lists_stay_within_the_edit_allocation_budget() -> Result<(), Box> +{ + let registry = acdc_extensions_lists::registry()?; + let options = Options::default(); + let mut images = String::new(); + for number in 0..100 { + writeln!(images, ".Image {number}\nimage::target.svg[]\n")?; + } + let measure = |requests| -> Result { + let source = "list-of::image[]\n\n".repeat(requests) + &images; + let region = Region::new(GLOBAL); + let _ = black_box(registry.parse(&source, &options)?.finish()?); + Ok(region.change().bytes_allocated) + }; + measure(1)?; + let ten = measure(10)?; + let hundred = measure(100)?; + // Ten times the output, with headroom for allocator and target differences. + // Copying all earlier generated paragraphs on every edit exceeds this budget. + assert!( + hundred <= 16 * ten, + "10 requests: {ten} bytes, 100: {hundred} bytes" + ); + Ok(()) +} diff --git a/extensions/lists/tests/composition.rs b/extensions/lists/tests/composition.rs new file mode 100644 index 000000000..4803505a0 --- /dev/null +++ b/extensions/lists/tests/composition.rs @@ -0,0 +1,126 @@ +//! Ordering and document-local state with native lists and other processors. + +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +use acdc_parser::{ + CompatibilityMode, Error, Options, + extensions::{ + BlockBuilder, BlockContext, BlockMacro, BlockMacroOutput, DocumentEditor, + MacroExecutionContext, MacroInvocation, Registry, TreeProcessor, TreeProcessorRegistration, + }, +}; + +type TestResult = Result<(), Box>; + +struct Produce; + +impl TreeProcessor for Produce { + 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::listing("Generated code.") + .with_attributes("title=Generated") + .with_id("produced"), + )?; + } + Ok(()) + } +} + +#[test] +fn producers_before_and_after_lists_keep_registration_order_and_run_once() -> TestResult { + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + for producer_first in [true, false] { + let calls = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&calls); + let mut builder = Registry::builder(); + builder.register(BlockMacro::new("produce", move || { + let calls = Arc::clone(&counter); + move |_: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { + calls.fetch_add(1, Ordering::SeqCst); + Ok(BlockMacroOutput::Deferred) + } + }))?; + let registration = TreeProcessorRegistration::for_macro("produce", || Produce); + if producer_first { + builder.register_tree_processor(registration.clone())?; + } + builder.extend(&acdc_extensions_lists::registry()?)?; + if !producer_first { + builder.register_tree_processor(registration)?; + } + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut working = builder + .build() + .parse("list-of::listing[]\n\nproduce::[]", &options)?; + assert_eq!(working.query().select(BlockContext::Listing).count(), 1); + assert_eq!( + working.query().select(BlockContext::Paragraph).count(), + usize::from(producer_first) + ); + working.normalize()?; + working.normalize()?; + assert_eq!(working.finish()?.warnings(), []); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + } + Ok(()) +} + +#[test] +fn parallel_documents_share_registrations_without_sharing_titles_or_ids() -> TestResult { + let registry = acdc_extensions_lists::registry()?; + let mut workers = Vec::new(); + for index in 0..8 { + let registry = registry.clone(); + workers.push(std::thread::spawn(move || -> Result<_, String> { + let source = format!("list-of::image[]\n\n.Worker {index}\nimage::target.svg[]"); + let mut modes = Vec::new(); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let options = Options::builder() + .with_compatibility_mode(mode) + .build() + .map_err(|error| error.to_string())?; + let working = registry + .parse(&source, &options) + .map_err(|error| error.to_string())?; + let ids: Vec<_> = working + .query() + .select(BlockContext::Image) + .filter_map(|view| view.output_id().map(str::to_owned)) + .collect(); + let parsed = working.finish().map_err(|error| error.to_string())?; + assert_eq!(parsed.warnings(), []); + let tree = + serde_json::to_string(&parsed.document()).map_err(|error| error.to_string())?; + modes.push((ids, tree)); + } + Ok((index, modes)) + })); + } + let mut expected_ids = None; + for worker in workers { + let (index, modes) = worker.join().map_err(|_| "worker panicked")??; + for (ids, tree) in modes { + assert_eq!(ids.len(), 1); + if let Some(expected) = &expected_ids { + assert_eq!(&ids, expected); + } else { + expected_ids = Some(ids); + } + assert!(tree.contains(&format!("Worker {index}")), "{tree}"); + for other in (0..8).filter(|other| *other != index) { + assert!(!tree.contains(&format!("Worker {other}")), "{tree}"); + } + } + } + Ok(()) +} diff --git a/extensions/lists/tests/defaults.rs b/extensions/lists/tests/defaults.rs new file mode 100644 index 000000000..fec5b74ef --- /dev/null +++ b/extensions/lists/tests/defaults.rs @@ -0,0 +1,379 @@ +//! Library behavior through the public query, editor, and display contracts. + +use acdc_parser::{ + CompatibilityMode, Error, Options, SafeMode, WarningKind, + ast::{BlockKind, InlineKind}, + extensions::{ + BlockBuilder, BlockContext, DisplayIntent, DocumentEditor, ExtensionParseResult, Registry, + TreeProcessor, TreeProcessorRegistration, + }, +}; + +type TestResult = Result<(), Box>; + +fn modes() -> [CompatibilityMode; 2] { + [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] +} + +fn links(result: &ExtensionParseResult) -> Vec> { + result + .query() + .select(BlockContext::Paragraph) + .filter_map(|view| { + let BlockKind::Paragraph(paragraph) = view.block().kind() else { + return None; + }; + let links: Vec<_> = paragraph + .content() + .inlines() + .filter_map(|inline| { + let InlineKind::CrossReference(xref) = inline.kind() else { + return None; + }; + Some((xref.target().to_owned(), xref.generated_display()?.intent())) + }) + .collect(); + (!links.is_empty()).then_some(links) + }) + .collect() +} + +#[test] +fn requests_before_targets_reuse_collision_safe_ids_and_preserve_authored_ids() -> TestResult { + let source = "= Document\n\nlist-of::image[]\n\nlist-of::image[]\n\n.First\nimage::first.svg[]\n\n.Second\n[#authored,reftext='Custom reference']\nimage::second.svg[]\n\nimage::untitled.svg[]\n\n[#_acdc_3]\nReserved. See <<_acdc_3_2>>."; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let registry = acdc_extensions_lists::registry()?; + let first = registry.parse(source, &options)?; + let second = registry.parse(source, &options)?; + assert_eq!(links(&first), links(&second)); + let expected = vec![ + ("_acdc_3_3".into(), DisplayIntent::CaptionAndTitle), + ("authored".into(), DisplayIntent::CaptionAndTitle), + ]; + assert_eq!(links(&first), vec![expected.clone(), expected]); + assert_eq!( + first + .query() + .select(BlockContext::Image) + .last() + .ok_or("untitled")? + .output_id(), + None + ); + let parsed = first.finish()?; + assert_eq!(parsed.warnings().len(), 1); + assert!( + matches!(&parsed.warnings().first().ok_or("warning")?.kind, WarningKind::UnresolvedReference { target } if target == "_acdc_3_2") + ); + } + Ok(()) +} + +#[test] +fn supported_elements_select_semantic_contexts() -> TestResult { + let cases = [ + ("image", ".Title\nimage::one.svg[]"), + ("table", ".Title\n|===\n|Cell\n|==="), + ("listing", ".Title\n[source,rust]\nCode."), + ("literal", ".Title\n....\nLiteral.\n...."), + ("example", ".Title\n====\nExample.\n===="), + ("quote", ".Title\n[quote]\nQuoted."), + ("verse", ".Title\n[verse]\nA verse."), + ("sidebar", ".Title\n****\nSidebar.\n****"), + ("open", ".Title\n--\nOpen.\n--"), + ("pass", ".Title\n++++\nPassthrough.\n++++"), + ("stem", ".Title\n[stem]\n++++\nx+y\n++++"), + ("audio", ".Title\naudio::one.ogg[]"), + ("video", ".Title\nvideo::one.mp4[]"), + ("admonition", ".Title\nNOTE: Note."), + ("paragraph", ".Title\nParagraph."), + ("section", "== Title\n\nBody."), + ("olist", ".Title\n. One\n. Two"), + ("ulist", ".Title\n* One\n* Two"), + ("dlist", ".Title\nTerm:: Definition"), + ("colist", "----\nCode <1>\n----\n.Title\n<1> Explanation"), + ]; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (element, target) in cases { + let source = format!("= Document\n\nlist-of::{element}[]\n\n{target}"); + let result = acdc_extensions_lists::registry()?.parse(&source, &options)?; + assert_eq!( + links(&result).iter().map(Vec::len).sum::(), + 1, + "{mode:?}: {element}" + ); + assert!( + result.finish()?.warnings().is_empty(), + "{mode:?}: {element}" + ); + } + } + Ok(()) +} + +#[test] +fn selection_reaches_nested_containers_lists_and_asciidoc_cells() -> TestResult { + let containers = [ + "== Section\n\n.Target\nimage::one.svg[]", + "--\n.Target\nimage::one.svg[]\n--", + "====\n.Target\nimage::one.svg[]\n====", + "****\n.Target\nimage::one.svg[]\n****", + "[quote]\n____\n.Target\nimage::one.svg[]\n____", + "[NOTE]\n====\n.Target\nimage::one.svg[]\n====", + "* Item\n+\n.Target\nimage::one.svg[]", + ". Item\n+\n.Target\nimage::one.svg[]", + "Term:: Definition\n+\n.Target\nimage::one.svg[]", + "----\nCode <1>\n----\n<1> Explanation\n+\n.Target\nimage::one.svg[]", + "[cols=a]\n|===\n|\n.Target\nimage::one.svg[]\n|===", + ]; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for body in containers { + let source = format!("= Document\n\nlist-of::image[]\n\n{body}"); + let result = acdc_extensions_lists::registry()?.parse(&source, &options)?; + assert_eq!( + links(&result).iter().map(Vec::len).sum::(), + 1, + "{mode:?}: {body}" + ); + assert!(result.finish()?.warnings().is_empty(), "{mode:?}: {body}"); + } + } + Ok(()) +} + +#[test] +fn empty_lists_keep_the_section_and_unknown_elements_keep_readable_text() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let source = "= Document\n\n== Lists\n\nlist-of::image[]\n\nlist-of::unknown[]\n\n== Targets\n\nimage::untitled.svg[]"; + let result = acdc_extensions_lists::registry()?.parse(source, &options)?; + assert_eq!(result.query().select(BlockContext::Section).count(), 2); + let generated = links(&result); + assert!(generated.is_empty(), "unexpected links: {generated:?}"); + assert_eq!(result.query().select(BlockContext::Paragraph).count(), 1); + let parsed = result.finish()?; + assert_eq!(parsed.warnings().len(), 1); + let warning = parsed.warnings().first().ok_or("warning")?; + assert!( + matches!(&warning.kind, WarningKind::Other(message) if message == "unknown list-of element: unknown") + ); + assert_eq!( + warning + .source_location() + .ok_or("source")? + .location + .start + .line, + 7 + ); + let unknown = parsed.document().blocks().next().ok_or("lists section")?; + let BlockKind::Section(section) = unknown.kind() else { + return Err("section".into()); + }; + let BlockKind::Paragraph(paragraph) = + section.blocks().next().ok_or("readable call")?.kind() + else { + return Err("paragraph".into()); + }; + assert!( + matches!(paragraph.content().inlines().next().ok_or("call text")?.kind(), InlineKind::Plain(text) if text.text() == "list-of::unknown[]") + ); + } + Ok(()) +} + +#[test] +fn unknown_element_warning_retains_the_included_source_location() -> TestResult { + let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + for mode in modes() { + let options = Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let parsed = acdc_extensions_lists::registry()? + .parse_file(fixtures.join("include_warning.adoc"), &options)? + .finish()?; + assert_eq!(parsed.warnings().len(), 1); + let location = parsed + .warnings() + .first() + .ok_or("warning")? + .source_location() + .ok_or("location")?; + assert_eq!( + location.file.as_ref(), + Some(&fixtures.join("includes/unknown.adoc")) + ); + assert_eq!(location.location.start.line, 1); + } + Ok(()) +} + +#[test] +fn unknown_elements_preserve_the_call_arguments_and_unexpanded_target() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for call in [ + r#"list-of::not-a-context[custom="keep me"]"#, + r#"list-of::{kind}[custom='a,b',other="<&> *literal*"]"#, + ] { + let result = acdc_extensions_lists::registry()? + .parse( + &format!("= Document\n:kind: not-a-context\n\n{call}"), + &options, + )? + .finish()?; + assert_eq!(result.warnings().len(), 1); + let warning = result.warnings().first().ok_or("warning")?; + assert!( + matches!(&warning.kind, WarningKind::Other(message) if message == "unknown list-of element: not-a-context") + ); + assert_eq!( + warning + .source_location() + .ok_or("source")? + .location + .start + .line, + 4 + ); + let BlockKind::Paragraph(paragraph) = + result.document().blocks().next().ok_or("output")?.kind() + else { + return Err("paragraph".into()); + }; + let mut content = paragraph.content().inlines(); + assert!( + matches!(content.next().ok_or("call")?.kind(), InlineKind::Plain(text) if text.text() == call) + ); + assert!(content.next().is_none()); + } + } + Ok(()) +} + +#[test] +fn later_requests_observe_earlier_generated_paragraphs() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = acdc_extensions_lists::registry()?.parse("= Document\n\n.Generated title\n[#generated]\nlist-of::image[]\n\nlist-of::paragraph[]\n\n.Target\nimage::one.svg[]", &options)?; + let observed = links(&result); + assert_eq!(observed.len(), 2); + assert_eq!( + observed.last(), + Some(&vec![("generated".into(), DisplayIntent::Title)]) + ); + assert_eq!(result.finish()?.warnings(), []); + } + Ok(()) +} + +#[test] +fn requests_inside_asciidoc_cells_and_list_continuations_are_replaced() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = acdc_extensions_lists::registry()?.parse("= Document\n\n* Item\n+\nlist-of::image[]\n\n[cols=a]\n|===\n|list-of::image[]\n|===\n\n.Target\nimage::one.svg[]", &options)?; + let observed = links(&result); + assert_eq!(observed.len(), 2); + assert_eq!(observed.first(), observed.last()); + assert_eq!(result.finish()?.warnings(), []); + } + Ok(()) +} + +#[test] +fn unsupported_options_fail_at_the_macro_instead_of_being_ignored() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (arguments, message) in [ + ("enhanced_rendering=true", "title formatting is automatic"), + ("enhanced_rendering=false", "title formatting is automatic"), + ("enhanced_rendering=0", "title formatting is automatic"), + ("enhanced_rendering=nil", "title formatting is automatic"), + ("enhanced_rendering=\"\"", "title formatting is automatic"), + ("enhanced_rendering=", "title formatting is automatic"), + (",true", "one positional argument"), + ("true,false", "one positional argument"), + ] { + let source = format!("= Document\n\nlist-of::image[{arguments}]"); + let error = acdc_extensions_lists::registry()? + .parse(&source, &options) + .err() + .ok_or("expected option error")?; + assert!( + matches!(error, Error::Extension(origin, detail) if origin.location.start.line == 3 && detail.contains(message)), + "{mode:?}: {arguments}" + ); + } + } + Ok(()) +} + +struct Rename; + +impl TreeProcessor for Rename { + fn process(&mut self, editor: &mut DocumentEditor<'_>) -> Result<(), Error> { + let targets: Vec<_> = editor + .query() + .select(BlockContext::Image) + .map(|view| view.target().clone()) + .collect(); + for target in targets { + editor.replace_block( + &target, + BlockBuilder::image("changed.svg") + .with_attributes("id=renamed,title='Later title',caption='Updated '"), + )?; + } + Ok(()) + } +} + +#[test] +fn later_processors_rename_targets_without_refreshing_captured_titles_or_membership() -> TestResult +{ + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let mut builder = Registry::builder(); + builder.extend(&acdc_extensions_lists::registry()?)?; + builder.register_tree_processor(TreeProcessorRegistration::new("rename", || Rename))?; + let result = builder.build().parse("= Document\n:label: Early\n\nlist-of::image[]\n\n.Original *{label}*\nimage::one.svg[]\n\n:label: Late", &options)?; + let parsed = result.finish()?; + let output = parsed.document().blocks().next().ok_or("output")?; + let BlockKind::Paragraph(paragraph) = output.kind() else { + return Err("paragraph".into()); + }; + let InlineKind::CrossReference(xref) = + paragraph.content().inlines().next().ok_or("link")?.kind() + else { + return Err("xref".into()); + }; + let display = xref.generated_display().ok_or("display")?; + assert_eq!(display.target(), "renamed"); + assert_eq!( + display.title_source().ok_or("title")?.raw_source(), + "Original *{label}*" + ); + assert_eq!( + display + .title_source() + .ok_or("context")? + .attributes() + .get("label") + .and_then(acdc_parser::DocumentAttributeValue::as_str), + Some("Early") + ); + assert!( + display + .title() + .ok_or("captured title")? + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + ); + assert_eq!(parsed.warnings(), []); + } + Ok(()) +} diff --git a/extensions/lists/tests/empty_sections.rs b/extensions/lists/tests/empty_sections.rs new file mode 100644 index 000000000..d0b382a9c --- /dev/null +++ b/extensions/lists/tests/empty_sections.rs @@ -0,0 +1,259 @@ +//! Empty-list policy and the checked removal of its containing section. + +use acdc_parser::{ + AttributeValue, CompatibilityMode, ElementAttributes, Options, WarningKind, + ast::{BlockKind, CaptionRef, InlineKind}, + extensions::{ + BlockContext, BlockMacro, BlockMacroOutput, MacroExecutionContext, MacroInvocation, + Registry, + }, +}; + +type TestResult = Result<(), Box>; + +fn modes() -> [CompatibilityMode; 2] { + [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] +} + +#[test] +fn hide_empty_section_follows_reference_string_truthiness_and_first_slot() -> TestResult { + let cases = [ + ("", false), + ("true", true), + ("false", true), + ("0", true), + ("\"\"", true), + ("hide_empty_section", true), + ("hide_empty_section=true", true), + ("hide_empty_section=false", true), + ("hide_empty_section=0", true), + ("hide_empty_section=\"\"", true), + ("hide_empty_section=", true), + ("hide_empty_section=nil", true), + ("hide_empty_section!", true), + (",", false), + ("custom=x,", false), + ("hide_empty_section=false,", true), + ("\"\",hide_empty_section=false", true), + ]; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (arguments, hidden) in cases { + let source = format!( + "= Document\n\n[#lists]\n== Lists\n\nlist-of::image[{arguments}]\n\n[#keep]\n== Keep\n\nBody." + ); + let result = acdc_extensions_lists::registry()?.parse(&source, &options)?; + let sections: Vec<_> = result + .query() + .select(BlockContext::Section) + .filter_map(|view| view.output_id()) + .collect(); + assert_eq!( + sections, + if hidden { + vec!["keep"] + } else { + vec!["lists", "keep"] + }, + "{mode:?}: {arguments}" + ); + assert_eq!(result.finish()?.warnings(), []); + } + } + Ok(()) +} + +#[test] +fn matching_untitled_nodes_keep_the_section_even_when_no_entries_are_generated() -> TestResult { + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = acdc_extensions_lists::registry()?.parse("= Document\n\n[#lists]\n== Lists\n\nlist-of::image[hide_empty_section=true]\n\n== Targets\n\nimage::untitled.svg[]", &options)?; + assert_eq!(result.query().select(BlockContext::Section).count(), 2); + assert_eq!(result.query().select(BlockContext::Paragraph).count(), 0); + assert_eq!(result.finish()?.warnings(), []); + } + Ok(()) +} + +#[test] +fn removal_cancels_pending_descendants_and_later_requests_observe_removed_targets() -> TestResult { + let source = "= Document\n\n[#gone]\n== Gone\n\nlist-of::image[hide_empty_section=true]\n\nlist-of::unknown[]\n\n=== Child\n\n.Title\nKept only until its section disappears.\n\nlist-of::paragraph[]\n\n[#keep]\n== Keep\n\nlist-of::paragraph[]"; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = acdc_extensions_lists::registry()?.parse(source, &options)?; + assert_eq!(result.query().blocks().count(), 1); + assert_eq!( + result + .query() + .blocks() + .next() + .ok_or("surviving section")? + .output_id(), + Some("keep") + ); + assert_eq!(result.finish()?.warnings(), []); + } + Ok(()) +} + +#[test] +fn hiding_inside_nested_containers_removes_the_nearest_section_only() -> TestResult { + let containers = [ + "--\nlist-of::image[true]\n--", + "* Item\n+\nlist-of::image[true]", + "[NOTE]\n====\nlist-of::image[true]\n====", + ]; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for container in containers { + let source = format!( + "= Document\n\n[#parent]\n== Parent\n\nBody.\n\n[#child]\n=== Child\n\n{container}\n\n[#keep]\n== Keep\n\nBody." + ); + let result = acdc_extensions_lists::registry()?.parse(&source, &options)?; + let sections: Vec<_> = result + .query() + .select(BlockContext::Section) + .filter_map(|view| view.output_id()) + .collect(); + assert_eq!(sections, ["parent", "keep"], "{mode:?}: {container}"); + assert_eq!(result.finish()?.warnings(), []); + } + } + Ok(()) +} + +#[test] +fn calls_without_a_section_and_in_cells_preserve_the_surrounding_document() -> TestResult { + let cases = [ + ("list-of::image[true]\n\nKeep.", 0, 1), + ("--\nlist-of::image[true]\n--\n\nKeep.", 0, 1), + ( + "[#outer]\n== Outer\n\n[cols=a]\n|===\n|list-of::image[true]\n|===\n\nKeep.", + 1, + 1, + ), + ]; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + for (body, sections, paragraphs) in cases { + let result = acdc_extensions_lists::registry()? + .parse(&format!("= Document\n\n{body}"), &options)?; + assert_eq!( + result.query().select(BlockContext::Section).count(), + sections, + "{body}" + ); + assert_eq!( + result.query().select(BlockContext::Paragraph).count(), + paragraphs, + "{body}" + ); + assert_eq!(result.finish()?.warnings(), []); + } + } + Ok(()) +} + +#[test] +fn actual_false_and_nil_attribute_defaults_are_disabled() -> TestResult { + for value in [AttributeValue::Bool(false), AttributeValue::None] { + let mut defaults = ElementAttributes::default(); + defaults.set("hide_empty_section".into(), value); + let mut builder = Registry::builder(); + builder.extend(&acdc_extensions_lists::registry()?)?; + builder.replace( + BlockMacro::new("list-of", || { + |_: &MacroInvocation<'_>, _: &mut MacroExecutionContext| { + Ok(BlockMacroOutput::Deferred) + } + }) + .with_defaults(defaults), + )?; + let result = builder.build().parse( + "= Document\n\n== Lists\n\nlist-of::image[]", + &Options::default(), + )?; + assert_eq!(result.query().select(BlockContext::Section).count(), 1); + assert_eq!(result.finish()?.warnings(), []); + } + Ok(()) +} + +#[test] +fn removed_section_repairs_catalogs_footnotes_and_preserves_surviving_ordinals() -> TestResult { + let source = "= Document\n:sectnums:\n\n[#gone]\n== Gone\n\nRemoved footnote:gone[Removed definition].\n\n.Removed figure\n[#gone-figure]\nimage::gone.svg[]\n\nlist-of::video[true]\n\n[#keep]\n== Keep\n\nSurviving footnote:kept[Surviving definition].\n\n.Surviving figure\n[#kept-figure]\nimage::kept.svg[]\n\nlist-of::image[]"; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let result = acdc_extensions_lists::registry()?.parse(source, &options)?; + let image = result + .query() + .select(BlockContext::Image) + .next() + .ok_or("image")?; + assert!( + matches!(image.caption(), Some(CaptionRef::Numbered {number: Some(number), ..}) if number.get() == 2) + ); + let parsed = result.finish()?; + let document = parsed.document(); + assert!(document.references().get("gone").is_none()); + assert!(document.references().get("gone-figure").is_none()); + assert!(document.references().get("kept-figure").is_some()); + let toc: Vec<_> = document + .toc_entries() + .map(|entry| (entry.id(), entry.number())) + .collect(); + assert_eq!(toc, [("keep", Some("2"))]); + assert_eq!(document.footnotes().count(), 1); + assert_eq!(document.footnotes().next().ok_or("footnote")?.number(), 1); + assert_eq!(parsed.warnings(), []); + } + Ok(()) +} + +#[test] +fn earlier_lists_keep_captured_titles_when_a_later_request_removes_the_target() -> TestResult { + let source = "= Document\n:label: Original\n\nlist-of::paragraph[]\n\n== Gone\n\n.Frozen *{label}*\n[#target]\nSelected paragraph.\n\nlist-of::image[true]\n\n== Keep\n\n:label: Later\n"; + for mode in modes() { + let options = Options::builder().with_compatibility_mode(mode).build()?; + let parsed = acdc_extensions_lists::registry()? + .parse(source, &options)? + .finish()?; + assert_eq!(parsed.warnings().len(), 1); + assert!( + matches!(&parsed.warnings().first().ok_or("warning")?.kind, WarningKind::UnresolvedReference {target} if target == "target") + ); + let BlockKind::Paragraph(paragraph) = + parsed.document().blocks().next().ok_or("list")?.kind() + else { + return Err("paragraph".into()); + }; + let InlineKind::CrossReference(xref) = + paragraph.content().inlines().next().ok_or("link")?.kind() + else { + return Err("xref".into()); + }; + let display = xref.generated_display().ok_or("captured display")?; + assert!(display.is_missing()); + assert_eq!( + display.title_source().ok_or("source")?.raw_source(), + "Frozen *{label}*" + ); + assert_eq!( + display + .title_source() + .ok_or("attributes")? + .attributes() + .get("label") + .and_then(acdc_parser::DocumentAttributeValue::as_str), + Some("Original") + ); + assert!( + display + .title() + .ok_or("title")? + .inlines() + .any(|inline| matches!(inline.kind(), InlineKind::Bold(_))) + ); + } + Ok(()) +} diff --git a/extensions/lists/tests/fixtures.rs b/extensions/lists/tests/fixtures.rs new file mode 100644 index 000000000..c3a763368 --- /dev/null +++ b/extensions/lists/tests/fixtures.rs @@ -0,0 +1,26 @@ +//! Ordinary HTML rendering of the native library's generated nodes. + +use std::{fs, path::Path}; + +use acdc_converters_html::HtmlVariant; +use acdc_parser::CompatibilityMode; + +mod support; + +#[test] +fn lists_render_through_the_shared_pipeline_in_both_modes_and_html_variants() +-> Result<(), Box> { + let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures"); + for name in ["default", "nested", "empty_sections"] { + let source = fs::read_to_string(fixtures.join(format!("{name}.adoc")))?; + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + for variant in [HtmlVariant::Standard, HtmlVariant::Semantic] { + let output = support::render(&source, mode, variant)?; + let expected = + fs::read_to_string(fixtures.join(format!("{name}.{}.html", variant.as_str())))?; + assert_eq!(output, expected, "{name}: {mode:?}, {variant:?}"); + } + } + } + Ok(()) +} diff --git a/extensions/lists/tests/fixtures/default.adoc b/extensions/lists/tests/fixtures/default.adoc new file mode 100644 index 000000000..e1c1f7dcc --- /dev/null +++ b/extensions/lists/tests/fixtures/default.adoc @@ -0,0 +1,35 @@ += Native lists +:word: Early + +== Lists + +[.generated] +list-of::image[] + +list-of::quote[] + +list-of::image[] + +== Targets + +.A *bold* {word} & title +[#authored,reftext="Other reference"] +image::example.svg[] + +:word: Late + +[caption=""] +.Title only +image::other.svg[] + +.A _quoted_ title +[quote] +____ +Quoted text. +____ + +image::untitled.svg[] + +== Keep this empty section + +list-of::video[] diff --git a/extensions/lists/tests/fixtures/default.semantic.html b/extensions/lists/tests/fixtures/default.semantic.html new file mode 100644 index 000000000..f15d496cd --- /dev/null +++ b/extensions/lists/tests/fixtures/default.semantic.html @@ -0,0 +1,31 @@ +
+

Lists

+

Figure 1. A bold Early & title
+Title only
+

+

A quoted title
+

+

Figure 1. A bold Early & title
+Title only
+

+
+
+

Targets

+
+example
Figure 1. A bold Early & title
+
+
+other
Title only
+
+
+
A quoted title
+
+

Quoted text.

+
+
+
+untitled
+
+
+

Keep this empty section

+
diff --git a/extensions/lists/tests/fixtures/default.standard.html b/extensions/lists/tests/fixtures/default.standard.html new file mode 100644 index 000000000..0add511c9 --- /dev/null +++ b/extensions/lists/tests/fixtures/default.standard.html @@ -0,0 +1,37 @@ +
+

Lists

+
+
+

Figure 1. A bold Early & title
+Title only
+

+
+ +
+

Figure 1. A bold Early & title
+Title only
+

+
+
+
+
+

Targets

+
+
example
Figure 1. A bold Early & title
other
Title only
+
A quoted title
+
+
+

Quoted text.

+
+
+
+
untitled
+
+
+

Keep this empty section

+
+
+
diff --git a/extensions/lists/tests/fixtures/empty_sections.adoc b/extensions/lists/tests/fixtures/empty_sections.adoc new file mode 100644 index 000000000..757e05e2d --- /dev/null +++ b/extensions/lists/tests/fixtures/empty_sections.adoc @@ -0,0 +1,27 @@ += Empty list sections +:sectnums: + +[#removed] +== Removed section + +list-of::video[hide_empty_section=true] + +[#kept-default] +== Kept by default + +list-of::video[] + +[#kept-untitled] +== Matching untitled image + +list-of::image[hide_empty_section=false] + +[#targets] +== Targets + +image::untitled.svg[] + +[#sections] +== Surviving sections + +list-of::section[] diff --git a/extensions/lists/tests/fixtures/empty_sections.semantic.html b/extensions/lists/tests/fixtures/empty_sections.semantic.html new file mode 100644 index 000000000..c37fbc91c --- /dev/null +++ b/extensions/lists/tests/fixtures/empty_sections.semantic.html @@ -0,0 +1,19 @@ +
+

2. Kept by default

+
+
+

3. Matching untitled image

+
+
+

4. Targets

+
+untitled
+
+
+

5. Surviving sections

+

Kept by default
+Matching untitled image
+Targets
+Surviving sections
+

+
diff --git a/extensions/lists/tests/fixtures/empty_sections.standard.html b/extensions/lists/tests/fixtures/empty_sections.standard.html new file mode 100644 index 000000000..71763df76 --- /dev/null +++ b/extensions/lists/tests/fixtures/empty_sections.standard.html @@ -0,0 +1,27 @@ +
+

2. Kept by default

+
+
+
+
+

3. Matching untitled image

+
+
+
+
+

4. Targets

+
+
untitled
+
+
+

5. Surviving sections

+ +
diff --git a/extensions/lists/tests/fixtures/include_warning.adoc b/extensions/lists/tests/fixtures/include_warning.adoc new file mode 100644 index 000000000..2f1fda1c2 --- /dev/null +++ b/extensions/lists/tests/fixtures/include_warning.adoc @@ -0,0 +1,3 @@ += Included warning + +include::includes/unknown.adoc[] diff --git a/extensions/lists/tests/fixtures/includes/unknown.adoc b/extensions/lists/tests/fixtures/includes/unknown.adoc new file mode 100644 index 000000000..15da0cb86 --- /dev/null +++ b/extensions/lists/tests/fixtures/includes/unknown.adoc @@ -0,0 +1 @@ +list-of::unknown[] diff --git a/extensions/lists/tests/fixtures/nested.adoc b/extensions/lists/tests/fixtures/nested.adoc new file mode 100644 index 000000000..8172d8d36 --- /dev/null +++ b/extensions/lists/tests/fixtures/nested.adoc @@ -0,0 +1,24 @@ += Nested lists + +== Lists + +list-of::image[] + +== Targets + +-- +.Open image +image::open.svg[] +-- + +* List item ++ +.List image +image::list.svg[] + +[cols=a] +|=== +| +.Cell image +image::cell.svg[] +|=== diff --git a/extensions/lists/tests/fixtures/nested.semantic.html b/extensions/lists/tests/fixtures/nested.semantic.html new file mode 100644 index 000000000..d318f45a5 --- /dev/null +++ b/extensions/lists/tests/fixtures/nested.semantic.html @@ -0,0 +1,41 @@ +
+

Lists

+

Figure 1. Open image
+Figure 2. List image
+Figure 3. Cell image
+

+
+
+

Targets

+
+
+
+open
Figure 1. Open image
+
+
+
+
+
    +
  • +List item
    +list
    Figure 2. List image
    +
    +
  • +
+
+
+ +++ + + + + + +
+cell
Figure 3. Cell image
+
+
+
+
diff --git a/extensions/lists/tests/fixtures/nested.standard.html b/extensions/lists/tests/fixtures/nested.standard.html new file mode 100644 index 000000000..28e940dfb --- /dev/null +++ b/extensions/lists/tests/fixtures/nested.standard.html @@ -0,0 +1,39 @@ +
+

Lists

+
+
+

Figure 1. Open image
+Figure 2. List image
+Figure 3. Cell image
+

+
+
+
+
+

Targets

+
+
+
+
open
Figure 1. Open image
+
+
+
    +
  • +

    List item

    +
    list
    Figure 2. List image
  • +
+
+ +++ + + + + + +
+
cell
Figure 3. Cell image
+
+
+
diff --git a/extensions/lists/tests/support/mod.rs b/extensions/lists/tests/support/mod.rs new file mode 100644 index 000000000..a5ec27070 --- /dev/null +++ b/extensions/lists/tests/support/mod.rs @@ -0,0 +1,45 @@ +use acdc_converters_core::{ + Converter as _, Diagnostics, Options, + pipeline::{ExtensionCatalog, Pipeline}, +}; +use acdc_converters_html::{Converter, HtmlVariant}; +use acdc_parser::CompatibilityMode; + +pub(crate) fn render( + source: &str, + mode: CompatibilityMode, + variant: HtmlVariant, +) -> Result> { + let mut available = ExtensionCatalog::default(); + available.register("lists", acdc_extensions_lists::registry()?)?; + let pipeline = Pipeline::new(Converter::new_with_variant( + Options::builder().embedded(true).build(), + acdc_parser::Options::builder().with_compatibility_mode(mode), + variant, + )?) + .with_extensions(available.select(["lists"])?.ok_or("selection")?); + let parsed = pipeline.parse(source)?; + assert!(parsed.warnings().is_empty(), "{:?}", parsed.warnings()); + let before = serde_json::to_value(parsed.document())?; + let mut output = Vec::new(); + let mut warnings = Vec::new(); + let warning_source = pipeline.converter().warning_source(); + for _ in 0..2 { + let mut bytes = Vec::new(); + pipeline.write_to( + parsed.document(), + &mut bytes, + None, + None, + &mut Diagnostics::new(&warning_source, &mut warnings), + )?; + if output.is_empty() { + output = bytes; + } else { + assert_eq!(bytes, output, "repeated conversion"); + } + } + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(serde_json::to_value(parsed.document())?, before); + Ok(String::from_utf8(output)?) +}