SF.net SVN: docutils:[10200 ] trunk/docutils/docutils/ parsers/rst/states.py

milde--- via Docutils-checkins <[email protected]> Mon, 11 Aug 2025 12:07:22 +0000
Newsgroups gmane.text.docutils.cvs
Message-ID <[email protected]>
Revision: 10200
          http://sourceforge.net/p/docutils/code/10200
Author:   milde
Date:     2025-08-11 12:07:22 +0000 (Mon, 11 Aug 2025)
Log Message:
-----------
Fix error/crash whith Sphinx "autoprogram" [bugs:#509].

Sphinx's "autoprogram" fails to parse docstrings containing a section header.

"autoprogram" starts nested parsing with empty `memo.title_styles` and a
`<section>` as root node.  In this context, the "root section" should be
considered a "level 0" section.
Remove the unattached "root section" from the list of `parent_sections` so that
appending a new top-level section to `parent_sections[0].parent` works.

Modified Paths:
--------------
    trunk/docutils/docutils/parsers/rst/states.py

Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py	2025-08-11 12:07:14 UTC (rev 10199)
+++ trunk/docutils/docutils/parsers/rst/states.py	2025-08-11 12:07:22 UTC (rev 10200)
@@ -169,7 +169,6 @@
 
 
 class NestedStateMachine(StateMachineWS):
-
     """
     StateMachine run from within other StateMachine runs, to parse nested
     document structures.
@@ -177,7 +176,7 @@
 
     def run(self, input_lines, input_offset, memo, node, match_titles=True):
         """
-        Parse `input_lines` and populate a `docutils.nodes.document` instance.
+        Parse `input_lines` and populate `node`.
 
         Extend `StateMachineWS.run()`: set up document-wide data.
         """
@@ -326,11 +325,17 @@
 
         When a new section is reached that isn't a subsection of the current
         section, set `self.parent` to the new section's parent section
-        (or the document if the new section is a top-level section).
+        (or the root node if the new section is a top-level section).
         """
         title_styles = self.memo.title_styles
         parent_sections = self.parent.section_hierarchy()
-        # current section level: (0 document, 1 section, 2 subsection, ...)
+        # Adding a new <section> at level "i" is done by appending to
+        # ``parent_sections[i-1].parent``.
+        # However, in nested parsing the root `node` may be a <section>.
+        # Then ``parent_sections[0]`` has no parent and must be discarded:
+        if parent_sections and parent_sections[0].parent is None:
+            parent_sections.pop(0)
+        # current section level: (0 root, 1 section, 2 subsection, ...)
         oldlevel = len(parent_sections)
         # new section level:
         try:  # check for existing title style

This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.