Debian Codegraph @

docutils/parsers/docutils_xml.py

raw symbols SCIP
1 #! /usr/bin/env python3
2 # :Copyright: © 2024 Günter Milde.
3 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
4 #
5 # Copying and distribution of this file, with or without modification,
6 # are permitted in any medium without royalty provided the copyright
7 # notice and this notice are preserved.
8 # This file is offered as-is, without any warranty.
9 #
10 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
11 #
12 # Revision: $Revision: 10136 $
13 # Date: $Date: 2025-05-20 17:48:27 +0200 (Di, 20. Mai 2025) $
14
15 """A Docutils-XML parser.
16
17 Provisional:
18 The API is not fixed yet.
19 Defined objects may be renamed or changed
20 in any Docutils release without prior notice.
21 """
22
23 from __future__ import annotations
24
25 __docformat__ = 'reStructuredText'
26
27 import re
28 import xml.etree.ElementTree as ET
29
30 from docutils import frontend, nodes, parsers, utils
31
32
33 class Parser(parsers.Parser):
34
35 """A Docutils-XML parser."""
36
37 supported = ('xml', 'docutils-xml')
38 """Aliases this parser supports."""
39
40 config_section = 'xml parser'
41 config_section_dependencies = ('parsers',)
42 settings_default_overrides = {'doctitle_xform': False,
43 'validate': True,
44 }
45
46 def parse(self, inputstring, document) -> None:
47 """
48 Parse `inputstring` and populate `document`, a "document tree".
49
50 Provisional.
51 """
52 self.setup_parse(inputstring, document)
53
54 node = parse_element(inputstring, document)
55 if not isinstance(node, nodes.document):
56 document.append(node)
57
58 self.finish_parse()
59
60
61 class Unknown(nodes.Special, nodes.Inline, nodes.Element):
62 """An unknown element found by the XML parser."""
63 content_model = (((nodes.Element, nodes.Text), '*'),) # no restrictions
64
65
66 def parse_element(inputstring, document=None):
67 """
68 Parse `inputstring` as "Docutils XML", return `nodes.Element` instance.
69
70 :inputstring: XML source.
71 :document: `nodes.document` instance (default: a new dummy instance).
72 Provides settings and reporter.
73 Populated and returned, if the inputstring's root element
74 is <document>.
75
76 Caution:
77 The function does not detect invalid XML.
78
79 To check the validity of the returned node,
80 you may use its `validate()` method::
81
82 node = parse_element('<tip><hint>text</hint></tip>')
83 node.validate()
84
85 Provisional.
86 """
87 root = None
88 parser = ET.XMLPullParser(events=('start',))
89 for i, line in enumerate(inputstring.splitlines(keepends=True)):
90 try:
91 parser.feed(line)
92 for event, element in parser.read_events():
93 if root is None:
94 root = element
95 element.attrib['source line'] = str(i+1)
96 except ET.ParseError as e:
97 if document is None:
98 raise
99 document.reporter.error(f'XML parse error: {e}.',
100 source=document.settings._source,
101 line=e.position[0])
102 break
103 return element2node(root, document)
104
105
106 def element2node(element, document=None, unindent=True):
107 """
108 Convert an `etree` element and its children to Docutils doctree nodes.
109
110 :element: `xml.etree` element
111 :document: see `parse_element()`
112 :unindent: Remove formatting indentation of follow-up text lines?
113 Cf. `append_text()`.
114 TODO: do we need an "unindent" configuration setting?
115
116 Return a `docutils.nodes.Element` instance.
117
118 Internal.
119 """
120 if document is None:
121 document = utils.new_document('xml input',
122 frontend.get_default_settings(Parser))
123 document.source == 'xml input'
124 if element is None:
125 problem = nodes.problematic('', 'No XML element found.')
126 return nodes.paragraph('', '', problem)
127 # Get the corresponding `nodes.Element` instance:
128 try:
129 nodeclass = getattr(nodes, element.tag)
130 if not issubclass(nodeclass, nodes.Element):
131 nodeclass = Unknown
132 except AttributeError:
133 nodeclass = Unknown
134 if nodeclass == nodes.document:
135 node = document
136 document.source = document.source or document.settings._source
137 else:
138 node = nodeclass()
139
140 node.line = int(element.get('source line'))
141 if isinstance(node, Unknown):
142 node.tagname = element.tag
143 document.reporter.warning(
144 f'Unknown element type <{element.tag}>.',
145 base_node=node)
146
147 # Attributes: convert and add to `node.attributes`.
148 for key, value in element.items():
149 if key.startswith('{') or key == 'source line':
150 continue # skip duplicate attributes with namespace URL
151 try:
152 node.attributes[key] = nodes.ATTRIBUTE_VALIDATORS[key](value)
153 except (ValueError, KeyError):
154 if key in node.list_attributes:
155 value = value.split()
156 node.attributes[key] = value # node becomes invalid!
157
158 # Bookkeeping (register some elements/attributes in document-wide lists)
159 if isinstance(node, nodes.decoration):
160 document.decoration = node
161 elif isinstance(node, nodes.substitution_definition):
162 document.note_substitution_def(node, ' '.join(node['names']), document)
163 if node['ids']: # register, check for duplicates
164 document.set_id(node)
165 # TODO: anything missing?
166
167 # Append content:
168 # update "unindent" flag: change line indentation?
169 unindent = unindent and not isinstance(
170 node, (nodes.FixedTextElement, nodes.literal, Unknown))
171 # (leading) text
172 append_text(node, element.text, unindent)
173 # children and their tailing text
174 for child in element:
175 node.append(element2node(child, document, unindent))
176 # Text after a child node
177 append_text(node, child.tail, unindent)
178
179 return node
180
181
182 def append_text(node, text, unindent) -> None:
183 # Format `text`, wrap in a TextElement and append to `node`.
184 # Skip if `text` is empty or just formatting whitespace.
185 if not text:
186 return
187 if unindent:
188 text = re.sub('\n +', '\n', text)
189 if isinstance(node, nodes.TextElement):
190 node.append(nodes.Text(text))
191 elif text.strip():
192 # no TextElement: ignore formatting whitespace
193 # but append other text (node becomes invalid!)
194 node.append(nodes.Text(text.strip()))