asciidocstring 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ # Agent Rules & Repository Guide: `asciidocstring`
2
+
3
+ Welcome, fellow agent! This file contains critical context, guidelines, and rules for working with this repository.
4
+
5
+ ---
6
+
7
+ ## 1. Development Rules
8
+
9
+ ### Rule 1: Strict Red / Green TDD
10
+ Always write focused, failing tests first in the `tests/` directory before writing or editing production code.
11
+ * Verify the **RED** stage by running `PYTHONPATH=src venv/bin/pytest tests/`.
12
+ * Write the minimum code required to go **GREEN**.
13
+ * Keep the test suite passing throughout.
14
+
15
+ ### Rule 2: Pure Python and Portability
16
+ We target **Python 3.14+** and **Pyodide (WASM) 314.0+**.
17
+ * Do **NOT** add any dependencies with native C/C++ compiled extensions.
18
+ * Ensure all code runs flawlessly in WASM environments.
19
+
20
+ ### Rule 3: Linting & Typing Standards
21
+ Keep the codebase strictly clean and typed:
22
+ * Run Ruff: `venv/bin/ruff check src/ tests/`
23
+ * Run MyPy: `venv/bin/mypy src/`
24
+
25
+ ---
26
+
27
+ ## 2. Core Architecture
28
+
29
+ The library processes Python docstrings written in AsciiDoc using a decoupled, two-stage architecture:
30
+
31
+ 1. **Parser & Cleaning Layer (`src/asciidocstring/document.py`):**
32
+ * Uses `inspect.cleandoc` to calculate and strip common leading whitespace from docstrings.
33
+ * Dynamically appends a trailing `\n` to inputs to avoid `lark.exceptions.UnexpectedEOF` (required by `asciidoctrine`).
34
+ * Parses the cleaned text into an Abstract Semantic Graph (ASG) using `asciidoctrine.lark_parser.parse_to_ast()`.
35
+
36
+ 2. **AST Processing & Visitors Layer (`src/asciidocstring/visitors.py`):**
37
+ * Subclasses `asciidoctrine.nodes.NodeVisitor`.
38
+ * For docstring rendering, serializes the AST to reStructuredText (`ReSTSerializerVisitor`).
39
+ * For doctests, queries and extracts executable code blocks (`TestBlockExtractorVisitor`).
40
+
41
+ ---
42
+
43
+ ## 3. Reference Commands
44
+
45
+ ```bash
46
+ # Set up environment
47
+ python3 -m venv venv
48
+ venv/bin/pip install -e .
49
+
50
+ # Run test suite
51
+ PYTHONPATH=src venv/bin/pytest
52
+
53
+ # Run static quality checks
54
+ venv/bin/ruff check src/ tests/
55
+ mypy src/
56
+ ```
57
+
58
+ ---
59
+
60
+ ## 4. Known Upstream Limitations & Parser Details
61
+
62
+ * **Bare-URL Autolinks (Issue [#76](https://github.com/webmaven/asciidoctrine/issues/76)):** `asciidoctrine` does not yet parse bare URLs (such as `https://google.com` without bracketed labels) as `Ref` nodes; they are currently parsed as plain `Text` nodes. Use bracketed links `https://google.com[Google]` where explicit translation is required.
63
+
@@ -0,0 +1,47 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ bin/
8
+ build/
9
+ develop-eggs/
10
+ dist/
11
+ downloads/
12
+ eggs/
13
+ .eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ wheels/
20
+ share/python-wheels/
21
+ *.egg-info/
22
+ .installed.cfg
23
+ *.egg
24
+ MANIFEST
25
+
26
+ # Virtual environments
27
+ venv/
28
+ .venv/
29
+ env/
30
+ ENV/
31
+ env.bak/
32
+ venv.bak/
33
+
34
+ # Testing / coverage
35
+ .cache/
36
+ .pytest_cache/
37
+ .mypy_cache/
38
+ .ruff_cache/
39
+
40
+ # OS-specific files
41
+ .DS_Store
42
+ .DS_Store?
43
+ ._*
44
+ .Spotlight-V100
45
+ .Trashes
46
+ ehthumbs.db
47
+ Thumbs.db
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if distributed along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: asciidocstring
3
+ Version: 0.1.0
4
+ Summary: A semantic parser and converter for Python docstrings written in AsciiDoc
5
+ Project-URL: Homepage, https://github.com/webmaven/asciidocstring
6
+ Author: webmaven
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.14
12
+ Requires-Python: >=3.14
13
+ Requires-Dist: asciidoctrine>=0.1.0a3
14
+ Requires-Dist: lark==1.3.1
15
+ Description-Content-Type: text/plain
16
+
17
+ = AsciiDocString
18
+ :toc: left
19
+ :sectnums:
20
+
21
+ A semantic parser, extractor, and translator for Python docstrings written in AsciiDoc.
22
+
23
+ == Introduction
24
+
25
+ `asciidocstring` is a Python library built on top of the pure-Python `asciidoctrine` parser. It is designed to clean raw docstrings (stripping common indentation) and compile them into a structured Abstract Semantic Graph (ASG).
26
+
27
+ This parsed semantic graph can be used by downstream libraries to:
28
+ 1. Render high-fidelity reStructuredText for Sphinx (`sphinx-asciidoc`).
29
+ 2. Query and run interactive doctests (`asciidoctest`).
30
+
31
+ == Installation
32
+
33
+ [source,bash]
34
+ ----
35
+ pip install asciidocstring
36
+ ----
37
+
38
+ == Usage
39
+
40
+ === Parsing a Docstring
41
+
42
+ [source,python]
43
+ ----
44
+ import asciidocstring
45
+
46
+ docstring = """
47
+ = Parse Coordinates
48
+
49
+ This function processes dynamic coordinate objects.
50
+
51
+ [source,python,test]
52
+ ----
53
+ assert parse_coords(10, 20) == (10, 20)
54
+ ----
55
+
56
+ x (int):: The horizontal component
57
+ y (int):: The vertical component
58
+ """
59
+
60
+ doc = asciidocstring.parse(docstring)
61
+
62
+ # Convert to reStructuredText (reST) for Sphinx
63
+ rest_output = doc.to_rest()
64
+
65
+ # Extract code blocks for doctesting
66
+ tests = doc.extract_tests()
67
+ ----
68
+
69
+ == License
70
+
71
+ This project is licensed under the Apache License, Version 2.0.
@@ -0,0 +1,55 @@
1
+ = AsciiDocString
2
+ :toc: left
3
+ :sectnums:
4
+
5
+ A semantic parser, extractor, and translator for Python docstrings written in AsciiDoc.
6
+
7
+ == Introduction
8
+
9
+ `asciidocstring` is a Python library built on top of the pure-Python `asciidoctrine` parser. It is designed to clean raw docstrings (stripping common indentation) and compile them into a structured Abstract Semantic Graph (ASG).
10
+
11
+ This parsed semantic graph can be used by downstream libraries to:
12
+ 1. Render high-fidelity reStructuredText for Sphinx (`sphinx-asciidoc`).
13
+ 2. Query and run interactive doctests (`asciidoctest`).
14
+
15
+ == Installation
16
+
17
+ [source,bash]
18
+ ----
19
+ pip install asciidocstring
20
+ ----
21
+
22
+ == Usage
23
+
24
+ === Parsing a Docstring
25
+
26
+ [source,python]
27
+ ----
28
+ import asciidocstring
29
+
30
+ docstring = """
31
+ = Parse Coordinates
32
+
33
+ This function processes dynamic coordinate objects.
34
+
35
+ [source,python,test]
36
+ ----
37
+ assert parse_coords(10, 20) == (10, 20)
38
+ ----
39
+
40
+ x (int):: The horizontal component
41
+ y (int):: The vertical component
42
+ """
43
+
44
+ doc = asciidocstring.parse(docstring)
45
+
46
+ # Convert to reStructuredText (reST) for Sphinx
47
+ rest_output = doc.to_rest()
48
+
49
+ # Extract code blocks for doctesting
50
+ tests = doc.extract_tests()
51
+ ----
52
+
53
+ == License
54
+
55
+ This project is licensed under the Apache License, Version 2.0.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "asciidocstring"
7
+ dynamic = ["version"]
8
+ description = "A semantic parser and converter for Python docstrings written in AsciiDoc"
9
+ readme = { file = "README.adoc", content-type = "text/plain" }
10
+ requires-python = ">=3.14"
11
+ license = "Apache-2.0"
12
+ authors = [
13
+ { name = "webmaven" }
14
+ ]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.14",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ dependencies = [
21
+ "asciidoctrine>=0.1.0a3",
22
+ "lark==1.3.1",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/webmaven/asciidocstring"
27
+
28
+ [tool.hatch.version]
29
+ path = "src/asciidocstring/__init__.py"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/asciidocstring"]
33
+
34
+ [tool.ruff]
35
+ line-length = 88
36
+ target-version = "py313" # Ruff supports target version up to current stable
37
+ src = ["src"]
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I"]
41
+ ignore = []
42
+
43
+ [tool.mypy]
44
+ python_version = "3.14"
45
+ strict = true
46
+ warn_unreachable = true
47
+ pretty = true
@@ -0,0 +1,5 @@
1
+ from .document import AsciiDocStringDocument, parse
2
+ from .visitors import TestBlock
3
+
4
+ __version__ = "0.1.0"
5
+ __all__ = ["parse", "AsciiDocStringDocument", "TestBlock"]
@@ -0,0 +1,47 @@
1
+ import inspect
2
+ from typing import Any, List
3
+
4
+ from asciidoctrine.lark_parser import parse_to_ast
5
+
6
+ from .visitors import ReSTSerializerVisitor, TestBlock, TestBlockExtractorVisitor
7
+
8
+
9
+ class AsciiDocStringDocument:
10
+ """The main interface representing a parsed AsciiDoc docstring."""
11
+
12
+ def __init__(self, raw_source: str):
13
+ self.raw_source = raw_source
14
+ self.clean_source = self._clean(raw_source)
15
+ self.ast = self._parse(self.clean_source)
16
+
17
+ def _clean(self, source: str) -> str:
18
+ """Strip common leading indentation and ensure a trailing newline."""
19
+ cleaned = inspect.cleandoc(source)
20
+ # Ensure a trailing newline to avoid lark EOF errors
21
+ if not cleaned.endswith("\n"):
22
+ cleaned += "\n"
23
+ return cleaned
24
+
25
+ def _parse(self, source: str) -> Any:
26
+ """Parse cleaned AsciiDoc using asciidoctrine's Lark parser."""
27
+ try:
28
+ return parse_to_ast(source)
29
+ except Exception as e:
30
+ # Re-raise standard parser errors transparently or wrap them if needed
31
+ raise ValueError(f"AsciiDoc Parse Error: {e}") from e
32
+
33
+ def to_rest(self) -> str:
34
+ """Render parsed ASG into standard reStructuredText."""
35
+ visitor = ReSTSerializerVisitor()
36
+ return visitor.serialize(self.ast)
37
+
38
+ def extract_tests(
39
+ self, language: str = "python", requires_test_marker: bool = False
40
+ ) -> List[TestBlock]:
41
+ """Extract executable code blocks from the parsed AST."""
42
+ visitor = TestBlockExtractorVisitor(language, requires_test_marker)
43
+ return visitor.extract(self.ast)
44
+
45
+ def parse(docstring: str) -> AsciiDocStringDocument:
46
+ """Convenience function to parse a raw python docstring."""
47
+ return AsciiDocStringDocument(docstring)
@@ -0,0 +1,235 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Dict, List
3
+
4
+ from asciidoctrine.nodes import Listing, NodeVisitor
5
+
6
+
7
+ @dataclass
8
+ class TestBlock:
9
+ """Represents an executable code block extracted from a docstring."""
10
+ content: str
11
+ language: str
12
+ line_number: int
13
+ is_interactive: bool # True if it contains ">>> " style prompts
14
+ attributes: Dict[str, Any]
15
+
16
+ class TestBlockExtractorVisitor(NodeVisitor):
17
+ """AST visitor to locate and extract Python test blocks from a docstring."""
18
+
19
+ def __init__(self, target_language: str, requires_test_marker: bool):
20
+ self.target_language = target_language.lower()
21
+ self.requires_test_marker = requires_test_marker
22
+ self.extracted_tests: List[TestBlock] = []
23
+
24
+ def extract(self, node: Any) -> List[TestBlock]:
25
+ """Reset state, traverse the node tree, and return extracted test blocks."""
26
+ self.extracted_tests = []
27
+ self.visit(node)
28
+ return self.extracted_tests
29
+
30
+ def visit_listing(self, node: Listing) -> None:
31
+ """Process code listing blocks."""
32
+ attrs = node.attributes or {}
33
+ style = attrs.get("style", "")
34
+ lang = attrs.get("language", "").lower()
35
+
36
+ # A Listing node with style='source' represents a source code block
37
+ is_source = (style == "source" or node.name == "listing")
38
+ is_target_lang = (lang == self.target_language) or (
39
+ not lang and self.target_language == "python"
40
+ )
41
+
42
+ # Sgthand [.test] parsed as 'role': 'test', or positional [source,python,test]
43
+ has_test_marker = (
44
+ "test" in attrs
45
+ or attrs.get("role") == "test"
46
+ or attrs.get("3") == "test"
47
+ or "test" in attrs.get("positional", [])
48
+ )
49
+
50
+ if is_source and is_target_lang:
51
+ if self.requires_test_marker and not has_test_marker:
52
+ return # Skip since test marker is required but not present
53
+
54
+ # Extract content from Text inline nodes
55
+ content_parts = [
56
+ inline.value
57
+ for inline in node.inlines
58
+ if hasattr(inline, "value")
59
+ ]
60
+ content = "".join(content_parts)
61
+
62
+ # Identify interactive session
63
+ is_interactive = ">>> " in content
64
+
65
+ # Fetch line numbers from node locations if available
66
+ line_number = 1
67
+ if hasattr(node, "location") and node.location:
68
+ line_number = node.location[0].get("line", 1)
69
+
70
+ self.extracted_tests.append(TestBlock(
71
+ content=content,
72
+ language=lang or self.target_language,
73
+ line_number=line_number,
74
+ is_interactive=is_interactive,
75
+ attributes=attrs
76
+ ))
77
+
78
+ class ReSTSerializerVisitor(NodeVisitor):
79
+ """AST visitor to serialize parsed AsciiDoc to reStructuredText."""
80
+
81
+ def __init__(self) -> None:
82
+ self.output: List[str] = []
83
+ self._indent_level = 0
84
+ self._current_list_depth = 0
85
+
86
+ def serialize(self, node: Any) -> str:
87
+ """Reset state, walk AST, and return reST representation."""
88
+ self.output = []
89
+ self._indent_level = 0
90
+ self._current_list_depth = 0
91
+ self.visit(node)
92
+ # Strip excess trailing newlines from end of document
93
+ return "".join(self.output).rstrip() + "\n"
94
+
95
+ def render_inline(self, node: Any) -> str:
96
+ """Recursively render inline nodes and format their styles."""
97
+ if node.name == "text":
98
+ return str(node.value)
99
+ elif node.name == "span":
100
+ content = "".join(self.render_inline(sub) for sub in node.inlines)
101
+ if node.variant == "strong":
102
+ return f"**{content}**"
103
+ elif node.variant == "emphasis":
104
+ return f"*{content}*"
105
+ elif node.variant == "code":
106
+ return f"``{content}``"
107
+ return content
108
+ elif node.name == "ref":
109
+ content = "".join(self.render_inline(sub) for sub in node.inlines)
110
+ target = getattr(node, "target", "")
111
+ return f"`{content} <{target}>`_"
112
+ return ""
113
+
114
+ def visit_document(self, node: Any) -> None:
115
+ """Render Document header title and traverse block content."""
116
+ if hasattr(node, "header") and node.header and node.header.title:
117
+ title_text = "".join(
118
+ self.render_inline(inline)
119
+ for inline in node.header.title.inlines
120
+ )
121
+ underline = "=" * len(title_text)
122
+ self.output.append(f"{title_text}\n{underline}\n\n")
123
+
124
+ for block in node.blocks:
125
+ self.visit(block)
126
+
127
+ def visit_section(self, node: Any) -> None:
128
+ """Render Section title with standard depth-based underline indicators."""
129
+ level = getattr(node, "level", 1)
130
+ # Underline character mapping: depth 0 is Document (=), depth 1 is Section (-)
131
+ char_map = {0: "=", 1: "-", 2: "~", 3: "^"}
132
+ underline_char = char_map.get(level, "-")
133
+
134
+ if node.title:
135
+ title_text = "".join(
136
+ self.render_inline(inline) for inline in node.title.inlines
137
+ )
138
+ underline = underline_char * len(title_text)
139
+ self.output.append(f"{title_text}\n{underline}\n\n")
140
+
141
+ for block in node.blocks:
142
+ self.visit(block)
143
+
144
+ def visit_paragraph(self, node: Any) -> None:
145
+ """Render a plain paragraph with the current block level indentation."""
146
+ content = "".join(self.render_inline(inline) for inline in node.inlines)
147
+ indent = " " * self._indent_level
148
+ self.output.append(f"{indent}{content}\n\n")
149
+
150
+ def visit_listing(self, node: Any) -> None:
151
+ """Render code block listing using Sphinx-standard code-block directives."""
152
+ attrs = node.attributes or {}
153
+ lang = attrs.get("language", "python")
154
+
155
+ content_parts = [
156
+ inline.value for inline in node.inlines if hasattr(inline, "value")
157
+ ]
158
+ content = "".join(content_parts)
159
+
160
+ indent = " " * self._indent_level
161
+ self.output.append(f"{indent}.. code-block:: {lang}\n\n")
162
+
163
+ body_indent = " " * (self._indent_level + 3)
164
+ indented_lines = []
165
+ for line in content.splitlines():
166
+ if line.strip():
167
+ indented_lines.append(f"{body_indent}{line}")
168
+ else:
169
+ indented_lines.append("")
170
+ body = "\n".join(indented_lines)
171
+ self.output.append(f"{body}\n\n")
172
+
173
+ def visit_list(self, node: Any) -> None:
174
+ """Render bullets and handle list level nesting contexts."""
175
+ old_depth = self._current_list_depth
176
+ self._current_list_depth += 1
177
+
178
+ for item in node.items:
179
+ self.visit(item)
180
+
181
+ self._current_list_depth = old_depth
182
+
183
+ def visit_listitem(self, node: Any) -> None:
184
+ """Render standard bullet item formatting."""
185
+ indent_size = (self._current_list_depth - 1) * 2
186
+ indent = " " * indent_size
187
+
188
+ content = ""
189
+ if hasattr(node, "principal") and node.principal:
190
+ content = "".join(self.render_inline(inline) for inline in node.principal)
191
+
192
+ self.output.append(f"{indent}* {content}\n")
193
+
194
+ # Render nested block children under this item
195
+ old_indent = self._indent_level
196
+ self._indent_level += indent_size + 2
197
+ for block in node.blocks:
198
+ self.visit(block)
199
+ self._indent_level = old_indent
200
+
201
+ def visit_descriptionlist(self, node: Any) -> None:
202
+ """Render description lists."""
203
+ for item in node.items:
204
+ self.visit(item)
205
+
206
+ def visit_descriptionlistitem(self, node: Any) -> None:
207
+ """Render a single description list item (definition)."""
208
+ for term in node.terms:
209
+ term_text = "".join(self.render_inline(inline) for inline in term.inlines)
210
+ self.output.append(f"{term_text}\n")
211
+
212
+ old_indent = self._indent_level
213
+ # reST standard definition block is indented by 3 spaces
214
+ self._indent_level += 3
215
+ for block in node.blocks:
216
+ self.visit(block)
217
+ self._indent_level = old_indent
218
+
219
+ def visit_admonition(self, node: Any) -> None:
220
+ """Render standard admonition blocks (e.g. note, warning, tip)."""
221
+ variant = getattr(node, "variant", "note").lower()
222
+
223
+ indent = " " * self._indent_level
224
+ self.output.append(f"{indent}.. {variant}::\n\n")
225
+
226
+ old_indent = self._indent_level
227
+ self._indent_level += 3
228
+ for block in node.blocks:
229
+ self.visit(block)
230
+ self._indent_level = old_indent
231
+
232
+ def visit_thematicbreak(self, node: Any) -> None:
233
+ """Render thematic breaks (horizontal lines)."""
234
+ indent = " " * self._indent_level
235
+ self.output.append(f"{indent}----\n\n")
@@ -0,0 +1,82 @@
1
+ import asciidocstring
2
+
3
+
4
+ def test_extract_python_source_blocks() -> None:
5
+ # Docstring with python source block and other language
6
+ docstring = """
7
+ Some introduction text.
8
+
9
+ [source,python]
10
+ ----
11
+ assert foo() == 42
12
+ ----
13
+
14
+ And some Ruby code that should be ignored by default:
15
+ [source,ruby]
16
+ ----
17
+ foo = 42
18
+ ----
19
+ """
20
+ doc = asciidocstring.parse(docstring)
21
+ tests = doc.extract_tests(language="python")
22
+
23
+ assert len(tests) == 1
24
+ test_block = tests[0]
25
+
26
+ # Assert fields are extracted correctly
27
+ assert test_block.content.strip() == "assert foo() == 42"
28
+ assert test_block.language == "python"
29
+ assert test_block.is_interactive is False
30
+ assert test_block.line_number > 1 # Should find starting line number of block
31
+
32
+ def test_extract_interactive_prompts() -> None:
33
+ # Docstring with standard python interactive prompts
34
+ docstring = """
35
+ [source,python]
36
+ ----
37
+ >>> foo()
38
+ 42
39
+ ----
40
+ """
41
+ doc = asciidocstring.parse(docstring)
42
+ tests = doc.extract_tests(language="python")
43
+
44
+ assert len(tests) == 1
45
+ assert tests[0].is_interactive is True
46
+
47
+ def test_requires_test_marker_filter() -> None:
48
+ # Docstring containing both a normal source block and different
49
+ # test-marked source blocks
50
+ docstring = """
51
+ A non-test block:
52
+ [source,python]
53
+ ----
54
+ x = 1
55
+ ----
56
+
57
+ A test block with consecutive independent attribute lines:
58
+ # (merged role + source)
59
+ [.test]
60
+ [source,python]
61
+ ----
62
+ y = 2
63
+ ----
64
+
65
+ A test block with positional third attribute [source,python,test]:
66
+ [source,python,test]
67
+ ----
68
+ z = 3
69
+ ----
70
+ """
71
+ doc = asciidocstring.parse(docstring)
72
+
73
+ # By default, extracting tests should not require explicit marker
74
+ all_tests = doc.extract_tests(requires_test_marker=False)
75
+ assert len(all_tests) == 3
76
+
77
+ # When requires_test_marker is True, only return blocks with "test" marker
78
+ explicit_tests = doc.extract_tests(requires_test_marker=True)
79
+ assert len(explicit_tests) == 2
80
+
81
+ contents = {b.content.strip() for b in explicit_tests}
82
+ assert contents == {"y = 2", "z = 3"}
@@ -0,0 +1,40 @@
1
+ import pytest
2
+
3
+ import asciidocstring
4
+ from asciidocstring.document import AsciiDocStringDocument
5
+
6
+
7
+ def test_indentation_stripping() -> None:
8
+ # A standard raw indented docstring
9
+ raw_docstring = """
10
+ = Sample Docstring
11
+
12
+ This is a paragraph under the docstring.
13
+ It should have common indentation stripped.
14
+ """
15
+ doc = asciidocstring.parse(raw_docstring)
16
+ assert isinstance(doc, AsciiDocStringDocument)
17
+ # The clean source should be normalized without common leading whitespace
18
+ expected = (
19
+ "= Sample Docstring\n\n"
20
+ "This is a paragraph under the docstring.\n"
21
+ "It should have common indentation stripped.\n"
22
+ )
23
+ assert doc.clean_source == expected
24
+
25
+ def test_unexpected_eof_prevention() -> None:
26
+ # Under the hood, lark will fail on string ends without a trailing newline
27
+ # asciidocstring should ensure a trailing newline is appended
28
+ no_newline = "== Section Header"
29
+ doc = asciidocstring.parse(no_newline)
30
+ assert doc.clean_source == "== Section Header\n"
31
+ assert doc.ast is not None
32
+
33
+ def test_strict_parsing_errors() -> None:
34
+ # Testing that syntactically invalid input raises descriptive errors
35
+ invalid_syntax = ":: invalid\n"
36
+ with pytest.raises(Exception) as exc_info:
37
+ asciidocstring.parse(invalid_syntax)
38
+ # Check that it raised our custom parse exception with context details
39
+ assert "Parse Error" in str(exc_info.value)
40
+
@@ -0,0 +1,98 @@
1
+ import asciidocstring
2
+
3
+
4
+ def test_basic_blocks_serialization() -> None:
5
+ docstring = """
6
+ = Document Title
7
+
8
+ This is a plain paragraph.
9
+
10
+ == Section Subtitle
11
+
12
+ Another paragraph.
13
+ """
14
+ doc = asciidocstring.parse(docstring)
15
+ rest = doc.to_rest()
16
+
17
+ # Assert titles are translated to proper reST underlines
18
+ assert "Document Title\n==============" in rest
19
+ assert "Section Subtitle\n----------------" in rest
20
+ assert "This is a plain paragraph." in rest
21
+
22
+ def test_source_listing_serialization() -> None:
23
+ docstring = """
24
+ Here is some code:
25
+
26
+ [source,python]
27
+ ----
28
+ x = 42
29
+ print(x)
30
+ ----
31
+ """
32
+ doc = asciidocstring.parse(docstring)
33
+ rest = doc.to_rest()
34
+
35
+ expected_block = ".. code-block:: python\n\n x = 42\n print(x)"
36
+ assert expected_block in rest
37
+
38
+ def test_inline_formatting_serialization() -> None:
39
+ docstring = """
40
+ This text contains *bold word*, _italic word_, and `monospace code`.
41
+ """
42
+ doc = asciidocstring.parse(docstring)
43
+ rest = doc.to_rest()
44
+
45
+ # Bold *x* in AsciiDoc -> **x** in reST
46
+ # Italic _x* in AsciiDoc -> *x* in reST
47
+ # Monospace `x` in AsciiDoc -> ``x`` in reST
48
+ assert "contains **bold word**," in rest
49
+ assert "*italic word*," in rest
50
+ assert "``monospace code``." in rest
51
+
52
+ def test_lists_serialization() -> None:
53
+ docstring = """
54
+ * First bullet
55
+ * Second bullet
56
+ ** Nested bullet
57
+ """
58
+ doc = asciidocstring.parse(docstring)
59
+ rest = doc.to_rest()
60
+
61
+ # Assert standard bullet formatting and indentation
62
+ assert "* First bullet" in rest
63
+ assert " * Nested bullet" in rest
64
+
65
+ def test_description_lists_serialization() -> None:
66
+ docstring = """
67
+ param1 (int):: The first parameter
68
+ param2 (str):: The second parameter
69
+ """
70
+ doc = asciidocstring.parse(docstring)
71
+ rest = doc.to_rest()
72
+
73
+ expected_param1 = "param1 (int)\n The first parameter"
74
+ expected_param2 = "param2 (str)\n The second parameter"
75
+ assert expected_param1 in rest
76
+ assert expected_param2 in rest
77
+
78
+ def test_admonitions_serialization() -> None:
79
+ docstring = """
80
+ WARNING: This is a warning message.
81
+ """
82
+ doc = asciidocstring.parse(docstring)
83
+ rest = doc.to_rest()
84
+
85
+ expected_admonition = ".. warning::\n\n This is a warning message."
86
+ assert expected_admonition in rest
87
+
88
+ def test_links_serialization() -> None:
89
+ docstring = """
90
+ Check out http://example.com[Example Site] for more details.
91
+ """
92
+ doc = asciidocstring.parse(docstring)
93
+ rest = doc.to_rest()
94
+
95
+ expected_link = "Check out `Example Site <http://example.com>`_ for more details."
96
+ assert expected_link in rest
97
+
98
+