From 37890a831b539e2706cf4bdf7442a5caccc21673 Mon Sep 17 00:00:00 2001 From: rctruta <17259677+rctruta@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:38:55 -0500 Subject: [PATCH 1/2] fix(docs): parse CommonMark code fences in rustdoc_trim.py --- docs/build.sh | 2 + docs/rustdoc_trim.py | 130 +++++++++++++++++++++++++++++--------- docs/test_rustdoc_trim.py | 73 +++++++++++++++++++++ 3 files changed, 174 insertions(+), 31 deletions(-) create mode 100644 docs/test_rustdoc_trim.py diff --git a/docs/build.sh b/docs/build.sh index 44236cf727d39..493e03e417e83 100755 --- a/docs/build.sh +++ b/docs/build.sh @@ -10,6 +10,8 @@ cd "${SCRIPT_DIR}" rm -rf build 2> /dev/null +python3 -m unittest test_rustdoc_trim.py + # Keep the workspace dependency graph in sync with the codebase. scripts/generate_dependency_graph.sh diff --git a/docs/rustdoc_trim.py b/docs/rustdoc_trim.py index 77d481c8a8f09..46e6b40a73d88 100644 --- a/docs/rustdoc_trim.py +++ b/docs/rustdoc_trim.py @@ -2,46 +2,114 @@ # SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership # SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements -import re -from sphinx.application import Sphinx +from __future__ import annotations -# Regex pattern to match Rust code blocks in Markdown -RUST_CODE_BLOCK_PATTERN = re.compile(r"```rust(?:,ignore)?\s*(.*?)```", re.DOTALL) +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from sphinx.application import Sphinx -def remove_hashtag_lines_in_rust_blocks(markdown_content): - """ - Removes lines starting with '# ' in Rust code blocks within a Markdown string. - """ - def _process_code_block(match): - # Extract the code block content - code_block_content = match.group(1).strip() +def _split_line_ending(line: str) -> tuple[str, str]: + if line.endswith("\r\n"): + return line[:-2], "\r\n" + if line.endswith("\n"): + return line[:-1], "\n" + return line, "" - # Remove lines starting with '#' - modified_code_block = "\n".join( - line - for line in code_block_content.splitlines() - if (not line.lstrip().startswith("# ")) and line.strip() != "#" - ) - # Return the modified code block wrapped in triple backticks - return f"```rust\n{modified_code_block}\n```" +def _parse_fence(body: str) -> tuple[str, str, int, str] | None: + stripped = body.lstrip(" \t") + if len(stripped) < 3 or stripped[0] not in ("`", "~"): + return None + fence_char = stripped[0] + fence_len = len(stripped) - len(stripped.lstrip(fence_char)) + if fence_len < 3: + return None + rest = stripped[fence_len:] + indent = body[: len(body) - len(stripped)] + return indent, fence_char, fence_len, rest - # Replace all Rust code blocks using the _process_code_block function - return RUST_CODE_BLOCK_PATTERN.sub(_process_code_block, markdown_content) +def _is_rust_info_string(info: str) -> bool: + if not info: + return False + lang = info.split(None, 1)[0] + return lang == "rust" or lang.startswith("rust,") -def process_source_file(app: Sphinx, docname: str, source: list[str]): - original_content = source[0] - # Remove lines starting with '#' in Rust code blocks - modified_content = remove_hashtag_lines_in_rust_blocks(original_content) - source[0] = modified_content +def _is_hidden_rustdoc_line(body: str) -> bool: + return body.lstrip().startswith("# ") or body.strip() == "#" -def setup(app: Sphinx): + +def remove_hashtag_lines_in_rust_blocks(markdown_content: str) -> str: + """Remove hidden rustdoc `# ` lines from fenced Rust code blocks.""" + out: list[str] = [] + open_fence: tuple[str, str, int, str, str, bool] | None = None + block_lines: list[tuple[str, str]] = [] + + for raw_line in markdown_content.splitlines(keepends=True): + body, ending = _split_line_ending(raw_line) + parsed = _parse_fence(body) + + if open_fence is None: + # CommonMark §4.5: backtick info strings cannot contain backticks + if parsed is not None and not (parsed[1] == "`" and "`" in parsed[3]): + indent, fence_char, fence_len, rest = parsed + is_rust = _is_rust_info_string(rest.strip(" \t")) + open_fence = (indent, fence_char, fence_len, raw_line, ending, is_rust) + block_lines = [] + else: + out.append(raw_line) + continue + + open_indent, open_char, open_len, open_raw, open_ending, is_rust = open_fence + if ( + parsed is not None + and parsed[1] == open_char + and parsed[2] >= open_len + and parsed[3].strip(" \t") == "" + ): + if is_rust: + kept = [ + line_body + for line_body, _ in block_lines + if not _is_hidden_rustdoc_line(line_body) + ] + while kept and kept[0].strip() == "": + kept.pop(0) + while kept and kept[-1].strip() == "": + kept.pop() + nl = open_ending or "\n" + out.append(f"{open_indent}{open_char * open_len}rust{nl}") + for line_body in kept: + out.append(f"{line_body}{nl}") + out.append(raw_line) + else: + out.append(open_raw) + for line_body, line_ending in block_lines: + out.append(f"{line_body}{line_ending}") + out.append(raw_line) + open_fence = None + block_lines = [] + else: + block_lines.append((body, ending)) + + if open_fence is not None: + out.append(open_fence[3]) + for line_body, line_ending in block_lines: + out.append(f"{line_body}{line_ending}") + + return "".join(out) + + +def process_source_file(app: Sphinx, docname: str, source: list[str]) -> None: + source[0] = remove_hashtag_lines_in_rust_blocks(source[0]) + + +def setup(app: Sphinx) -> dict[str, bool]: app.connect("source-read", process_source_file) - return dict( - parallel_read_safe=True, - parallel_write_safe=True, - ) + return { + "parallel_read_safe": True, + "parallel_write_safe": True, + } diff --git a/docs/test_rustdoc_trim.py b/docs/test_rustdoc_trim.py new file mode 100644 index 0000000000000..fc1ee8db94f99 --- /dev/null +++ b/docs/test_rustdoc_trim.py @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +# SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +import time +import unittest + +from rustdoc_trim import remove_hashtag_lines_in_rust_blocks + + +class RustdocTrimTest(unittest.TestCase): + def test_strips_hidden_lines_and_normalizes_rust_attributes(self): + for header in ("```rust", "```rust,ignore", "```rust,no_run"): + src = ( + f"{header}\n" + "# use std::sync::Arc;\n" + "#\n" + "#[derive(Debug)]\n" + "struct Foo;\n" + " # let hidden = 1;\n" + "let visible = 2;\n" + "```\n" + ) + expected = "```rust\n#[derive(Debug)]\nstruct Foo;\nlet visible = 2;\n```\n" + self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), expected) + + def test_preserves_leading_indentation_on_first_kept_line(self): + src = "```rust\n# fn wrapper() {\n let indented = 42;\n# }\n```\n" + expected = "```rust\n let indented = 42;\n```\n" + self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), expected) + + def test_four_backtick_rust_fence_does_not_close_on_inner_three_backticks(self): + # Regression test for docs/source/contributor-guide/testing_infrastructure.md + src = ( + "````rust\n" + "/// ```\n" + "/// # use std::sync::Arc;\n" + "/// let value = Arc::new(42);\n" + "/// ```\n" + "````\n" + ) + self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), src) + + def test_outer_markdown_fence_leaves_nested_rust_example_untouched(self): + src = "````markdown\n```rust\n# use std::sync::Arc;\nlet x = 1;\n```\n````\n" + self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), src) + + def test_leaves_non_rust_prefix_languages_and_inline_fences_untouched(self): + src = ( + "Use ```rust in prose without closing.\n\n" + "```rustfmt\n" + "# keep comment\n" + "max_width = 100\n" + "```\n" + ) + self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), src) + + def test_backticks_inside_rust_code_do_not_close_block_early(self): + src = '```rust\n# let hidden = true;\nlet fence = "```";\n```\n' + expected = '```rust\nlet fence = "```";\n```\n' + self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), expected) + + def test_unclosed_fence_is_preserved_in_linear_time(self): + src = "```rust" + (" " * 50_000) + "\n" + ("# hidden\nlet x = 1;\n" * 5_000) + start = time.perf_counter() + result = remove_hashtag_lines_in_rust_blocks(src) + elapsed_ms = (time.perf_counter() - start) * 1000 + self.assertEqual(result, src) + self.assertLess(elapsed_ms, 200.0) + + +if __name__ == "__main__": + unittest.main() From c7c4646f28c9acc483385f583e7983c3c39511e4 Mon Sep 17 00:00:00 2001 From: rctruta <17259677+rctruta@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:25:31 -0500 Subject: [PATCH 2/2] refactor(docs): move rustdoc_trim to Sphinx doctree-read --- docs/rustdoc_trim.py | 119 ++++++++---------------------- docs/test_rustdoc_trim.py | 150 ++++++++++++++++++++++++-------------- 2 files changed, 127 insertions(+), 142 deletions(-) diff --git a/docs/rustdoc_trim.py b/docs/rustdoc_trim.py index 46e6b40a73d88..ee991bb7c7414 100644 --- a/docs/rustdoc_trim.py +++ b/docs/rustdoc_trim.py @@ -6,109 +6,50 @@ from typing import TYPE_CHECKING +from docutils import nodes + if TYPE_CHECKING: from sphinx.application import Sphinx -def _split_line_ending(line: str) -> tuple[str, str]: - if line.endswith("\r\n"): - return line[:-2], "\r\n" - if line.endswith("\n"): - return line[:-1], "\n" - return line, "" - - -def _parse_fence(body: str) -> tuple[str, str, int, str] | None: - stripped = body.lstrip(" \t") - if len(stripped) < 3 or stripped[0] not in ("`", "~"): - return None - fence_char = stripped[0] - fence_len = len(stripped) - len(stripped.lstrip(fence_char)) - if fence_len < 3: - return None - rest = stripped[fence_len:] - indent = body[: len(body) - len(stripped)] - return indent, fence_char, fence_len, rest - - -def _is_rust_info_string(info: str) -> bool: - if not info: - return False - lang = info.split(None, 1)[0] - return lang == "rust" or lang.startswith("rust,") - +def _is_rust_language(language: str) -> bool: + return language == "rust" or language.startswith("rust,") -def _is_hidden_rustdoc_line(body: str) -> bool: - return body.lstrip().startswith("# ") or body.strip() == "#" - -def remove_hashtag_lines_in_rust_blocks(markdown_content: str) -> str: - """Remove hidden rustdoc `# ` lines from fenced Rust code blocks.""" - out: list[str] = [] - open_fence: tuple[str, str, int, str, str, bool] | None = None - block_lines: list[tuple[str, str]] = [] - - for raw_line in markdown_content.splitlines(keepends=True): - body, ending = _split_line_ending(raw_line) - parsed = _parse_fence(body) - - if open_fence is None: - # CommonMark §4.5: backtick info strings cannot contain backticks - if parsed is not None and not (parsed[1] == "`" and "`" in parsed[3]): - indent, fence_char, fence_len, rest = parsed - is_rust = _is_rust_info_string(rest.strip(" \t")) - open_fence = (indent, fence_char, fence_len, raw_line, ending, is_rust) - block_lines = [] - else: - out.append(raw_line) +def trim_rustdoc_code(code: str) -> str: + """Strip hidden `#` lines and unescape `##` lines following rustdoc rules.""" + kept: list[str] = [] + for line in code.split("\n"): + stripped = line.lstrip(" \t") + if stripped == "#" or stripped.startswith("# "): continue - - open_indent, open_char, open_len, open_raw, open_ending, is_rust = open_fence - if ( - parsed is not None - and parsed[1] == open_char - and parsed[2] >= open_len - and parsed[3].strip(" \t") == "" - ): - if is_rust: - kept = [ - line_body - for line_body, _ in block_lines - if not _is_hidden_rustdoc_line(line_body) - ] - while kept and kept[0].strip() == "": - kept.pop(0) - while kept and kept[-1].strip() == "": - kept.pop() - nl = open_ending or "\n" - out.append(f"{open_indent}{open_char * open_len}rust{nl}") - for line_body in kept: - out.append(f"{line_body}{nl}") - out.append(raw_line) - else: - out.append(open_raw) - for line_body, line_ending in block_lines: - out.append(f"{line_body}{line_ending}") - out.append(raw_line) - open_fence = None - block_lines = [] + if stripped.startswith("##"): + indent_len = len(line) - len(stripped) + kept.append(f"{line[:indent_len]}{stripped[1:]}") else: - block_lines.append((body, ending)) - - if open_fence is not None: - out.append(open_fence[3]) - for line_body, line_ending in block_lines: - out.append(f"{line_body}{line_ending}") + kept.append(line) - return "".join(out) + start = 0 + while start < len(kept) and not kept[start].strip(): + start += 1 + end = len(kept) + while end > start and not kept[end - 1].strip(): + end -= 1 + return "\n".join(kept[start:end]) -def process_source_file(app: Sphinx, docname: str, source: list[str]) -> None: - source[0] = remove_hashtag_lines_in_rust_blocks(source[0]) +def process_doctree(app: Sphinx, doctree: nodes.document) -> None: + for node in doctree.findall(nodes.literal_block): + if _is_rust_language(node.get("language", "")): + trimmed = trim_rustdoc_code(node.astext()) + node["language"] = "rust" + # Sphinx skips Pygments highlighting when rawsource != astext(). + node.rawsource = trimmed + node[:] = [nodes.Text(trimmed)] def setup(app: Sphinx) -> dict[str, bool]: - app.connect("source-read", process_source_file) + app.connect("doctree-read", process_doctree) return { "parallel_read_safe": True, "parallel_write_safe": True, diff --git a/docs/test_rustdoc_trim.py b/docs/test_rustdoc_trim.py index fc1ee8db94f99..02ce72fc45f59 100644 --- a/docs/test_rustdoc_trim.py +++ b/docs/test_rustdoc_trim.py @@ -2,71 +2,115 @@ # SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership # SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements -import time +import html as html_lib +import re +import tempfile import unittest +from pathlib import Path -from rustdoc_trim import remove_hashtag_lines_in_rust_blocks +from docutils import nodes +from rustdoc_trim import process_doctree, trim_rustdoc_code +from sphinx.cmd.build import build_main +DOCS_DIR = Path(__file__).resolve().parent -class RustdocTrimTest(unittest.TestCase): - def test_strips_hidden_lines_and_normalizes_rust_attributes(self): - for header in ("```rust", "```rust,ignore", "```rust,no_run"): - src = ( - f"{header}\n" - "# use std::sync::Arc;\n" - "#\n" - "#[derive(Debug)]\n" - "struct Foo;\n" - " # let hidden = 1;\n" - "let visible = 2;\n" - "```\n" - ) - expected = "```rust\n#[derive(Debug)]\nstruct Foo;\nlet visible = 2;\n```\n" - self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), expected) - def test_preserves_leading_indentation_on_first_kept_line(self): - src = "```rust\n# fn wrapper() {\n let indented = 42;\n# }\n```\n" - expected = "```rust\n let indented = 42;\n```\n" - self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), expected) - - def test_four_backtick_rust_fence_does_not_close_on_inner_three_backticks(self): - # Regression test for docs/source/contributor-guide/testing_infrastructure.md +class RustdocTrimTest(unittest.TestCase): + def test_strips_hidden_lines_and_unescapes_double_hashes(self): src = ( - "````rust\n" - "/// ```\n" - "/// # use std::sync::Arc;\n" - "/// let value = Arc::new(42);\n" - "/// ```\n" - "````\n" + "# use std::sync::Arc;\n" + "#\n" + "\n" + "#[derive(Debug)]\n" + "## shown_comment\n" + " ## indented_escaped\n" + "##\n" + " # let hidden = 1;\n" + "let visible = 2;\n" + "\n" ) - self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), src) + expected = ( + "#[derive(Debug)]\n" + "# shown_comment\n" + " # indented_escaped\n" + "#\n" + "let visible = 2;" + ) + self.assertEqual(trim_rustdoc_code(src), expected) - def test_outer_markdown_fence_leaves_nested_rust_example_untouched(self): - src = "````markdown\n```rust\n# use std::sync::Arc;\nlet x = 1;\n```\n````\n" - self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), src) + def test_preserves_leading_indentation_on_first_kept_line(self): + src = "# fn wrapper() {\n let indented = 42;\n# }\n" + self.assertEqual(trim_rustdoc_code(src), " let indented = 42;") - def test_leaves_non_rust_prefix_languages_and_inline_fences_untouched(self): - src = ( - "Use ```rust in prose without closing.\n\n" - "```rustfmt\n" - "# keep comment\n" - "max_width = 100\n" - "```\n" + def test_process_doctree_normalizes_rust_blocks_and_skips_other_languages(self): + doc = nodes.document("", nodes.Element()) + rust_ignore = nodes.literal_block( + "# hidden\nlet x = 1;\n", + "# hidden\nlet x = 1;\n", + language="rust,ignore", + ) + rustfmt = nodes.literal_block( + "# keep\nmax_width = 100\n", + "# keep\nmax_width = 100\n", + language="rustfmt", ) - self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), src) + doc += rust_ignore + doc += rustfmt - def test_backticks_inside_rust_code_do_not_close_block_early(self): - src = '```rust\n# let hidden = true;\nlet fence = "```";\n```\n' - expected = '```rust\nlet fence = "```";\n```\n' - self.assertEqual(remove_hashtag_lines_in_rust_blocks(src), expected) + process_doctree(None, doc) - def test_unclosed_fence_is_preserved_in_linear_time(self): - src = "```rust" + (" " * 50_000) + "\n" + ("# hidden\nlet x = 1;\n" * 5_000) - start = time.perf_counter() - result = remove_hashtag_lines_in_rust_blocks(src) - elapsed_ms = (time.perf_counter() - start) * 1000 - self.assertEqual(result, src) - self.assertLess(elapsed_ms, 200.0) + self.assertEqual(rust_ignore["language"], "rust") + self.assertEqual(rust_ignore.astext(), "let x = 1;") + self.assertEqual(rust_ignore.rawsource, "let x = 1;") + self.assertEqual(rustfmt["language"], "rustfmt") + self.assertEqual(rustfmt.astext(), "# keep\nmax_width = 100\n") + + def test_sphinx_myst_end_to_end_fences_and_directives(self): + with tempfile.TemporaryDirectory() as tmp: + src_dir = Path(tmp) / "source" + out_dir = Path(tmp) / "build" + src_dir.mkdir() + (src_dir / "conf.py").write_text( + f"import sys\nsys.path.insert(0, {str(DOCS_DIR)!r})\n" + "extensions = ['myst_parser', 'rustdoc_trim']\n", + encoding="utf-8", + ) + (src_dir / "index.md").write_text( + "# Test\n\n" + "````rust\n" + "/// ```\n" + "# let hidden_after_inner_fence = 1;\n" + "/// let value = 42;\n" + "/// ```\n" + "````\n\n" + "````{note}\n" + "```rust,no_run\n" + "# use std::sync::Arc;\n" + "let in_note = 1;\n" + "```\n" + "````\n\n" + "````markdown\n" + "```rust\n" + "# keep_inside_markdown_example\n" + "```\n" + "````\n\n" + "```rust\n" + "# hidden_in_unclosed_eof_fence\n" + "let unclosed = 3;\n", + encoding="utf-8", + ) + rc = build_main(["-W", "-q", "-b", "html", str(src_dir), str(out_dir)]) + self.assertEqual(rc, 0) + raw_html = (out_dir / "index.html").read_text(encoding="utf-8") + plain = html_lib.unescape(re.sub(r"<[^>]+>", "", raw_html)) + self.assertIn("highlight-rust", raw_html) + self.assertIn("/// ```\n/// let value = 42;\n/// ```", plain) + self.assertNotIn("hidden_after_inner_fence", plain) + self.assertNotIn("use std::sync::Arc", plain) + self.assertIn("let in_note = 1;", plain) + self.assertIn("```rust\n# keep_inside_markdown_example\n```", plain) + self.assertNotIn("hidden_in_unclosed_eof_fence", plain) + self.assertIn("let unclosed = 3;", plain) if __name__ == "__main__":