kumarUjjawal commented on code in PR #28008:
URL: https://github.com/apache/datafusion/pull/28008#discussion_r4795615715
##########
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)
Review Comment:
A test now gates the docs build on a wall-clock limit
(`assertLess(elapsed_ms, 200.0)`), and build.sh runs it under `set -e` before
Sphinx, so a slow machine fails the whole docs build.
##########
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)
Review Comment:
Any backtick fence that isn't Rust is now treated as an opaque code block,
so Rust fences nested inside MyST backtick directives no longer have their
hidden lines removed. The old regex did remove them.
##########
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 (
Review Comment:
Fences are accepted at any indentation (including 4+ spaces and tabs).
CommonMark §4.5, which the PR says it implements, only allows 0-3 spaces before
a fence. So an indented bare ``` line inside Rust code closes the block early.
##########
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):
Review Comment:
`str.splitlines(keepends=True)` also splits on `\r`, `\v`, `\f`,
`\x1c`-`\x1e`, `\x85`, `\u2028` and `\u2029`, but `_split_line_ending` only
recognises `\r\n`/`\n`. The scanner's lines therefore don't match Markdown
lines, and Rust blocks get newlines inserted.
##########
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)
Review Comment:
The open-fence state is an unnamed 6-tuple read by position
(`open_fence[3]`, `parsed[1]`, `parsed[2]`, `parsed[3]`), and `nl = open_ending
or "\n"` has a fallback that can never be used.
##########
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() == "#"
Review Comment:
The function was rewritten to copy rustdoc's hidden-line rules but still
ignores rustdoc's `##` escape, where `## x` is shown as `# x`.
##########
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() == "":
Review Comment:
Leading blank lines are removed with `kept.pop(0)` in a loop, which shifts
the whole list on every pop.
##########
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)
Review Comment:
Trim leading blank lines without shifting the list
##########
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)
Review Comment:
Not every non-Rust fence is literal code in this Sphinx project. For
example, MyST parses the body of a four-backtick `{note}` directive as
Markdown. Copying that whole body unchanged leaves hidden imports and the
`rust,ignore` header in a nested Rust example that the previous filter
processed. Distinguish directives with parsed Markdown content from literal
examples such as the outer `markdown` fence covered by the test.
##########
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:
Review Comment:
An unclosed ```rust fence is copied through without removing hidden lines.
CommonMark closes an unclosed fence at the end of the document, so MyST still
renders it as a Rust block and the `# ` lines appear.
##########
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]
Review Comment:
A fence followed only by a nonbreaking space aborts the Sphinx build.
`rest.strip(" \t")` leaves that character intact, but `info.split(None, 1)`
treats it as whitespace and returns an empty list. Check that a token exists
before indexing it, and treat a missing language as non-Rust.
##########
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)
Review Comment:
Split source lines using Markdown line endings
##########
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)
Review Comment:
Pass non-Rust fence contents through without rebuilding each line. Every
SQL, shell, and text example is now buffered as `(body, ending)` tuples and
copied back into new strings, although its output is always identical to its
input, even for an unclosed fence. This adds per-line allocations on pages such
as `user-guide/sql/scalar_functions.md`. Emit the raw lines as they arrive and
keep only the delimiter state for non-Rust blocks.
##########
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)
Review Comment:
Remove the wall-clock deadline from the docs build test
##########
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)
Review Comment:
Make the fence-width regression test require a transformation. An
implementation that ignores four-backtick Rust fences entirely passes this test
because the expected output is identical to the input. Add a plain `# ` setup
line after a standalone three-backtick line inside the wider block and assert
that only the setup line disappears.
##########
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:
Review Comment:
This fix is at the wrong level: it is a hand-written Markdown fence parser
running on raw source text, even though myst-parser (already a docs dependency)
brings markdown-it-py, and Sphinx gives you parsed `literal_block` nodes with
`language='rust'`.
##########
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
Review Comment:
Respect the indentation limit on opening and closing fences
##########
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]):
Review Comment:
Recognize fences that start on a list-item marker line
##########
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])
Review Comment:
Keep Markdown fence processing out of reStructuredText sources
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]