lxml 6.0.0__cp312-cp312-macosx_10_13_x86_64.whl

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.
Files changed (174) hide show
  1. lxml/ElementInclude.py +244 -0
  2. lxml/__init__.py +22 -0
  3. lxml/_elementpath.cpython-312-darwin.so +0 -0
  4. lxml/_elementpath.py +343 -0
  5. lxml/apihelpers.pxi +1801 -0
  6. lxml/builder.cpython-312-darwin.so +0 -0
  7. lxml/builder.py +243 -0
  8. lxml/classlookup.pxi +580 -0
  9. lxml/cleanup.pxi +215 -0
  10. lxml/cssselect.py +101 -0
  11. lxml/debug.pxi +36 -0
  12. lxml/docloader.pxi +178 -0
  13. lxml/doctestcompare.py +488 -0
  14. lxml/dtd.pxi +479 -0
  15. lxml/etree.cpython-312-darwin.so +0 -0
  16. lxml/etree.h +244 -0
  17. lxml/etree.pyx +3853 -0
  18. lxml/etree_api.h +204 -0
  19. lxml/extensions.pxi +830 -0
  20. lxml/html/ElementSoup.py +10 -0
  21. lxml/html/__init__.py +1927 -0
  22. lxml/html/_diffcommand.py +86 -0
  23. lxml/html/_difflib.cpython-312-darwin.so +0 -0
  24. lxml/html/_difflib.py +2106 -0
  25. lxml/html/_html5builder.py +100 -0
  26. lxml/html/_setmixin.py +56 -0
  27. lxml/html/builder.py +173 -0
  28. lxml/html/clean.py +21 -0
  29. lxml/html/defs.py +135 -0
  30. lxml/html/diff.cpython-312-darwin.so +0 -0
  31. lxml/html/diff.py +972 -0
  32. lxml/html/formfill.py +299 -0
  33. lxml/html/html5parser.py +260 -0
  34. lxml/html/soupparser.py +314 -0
  35. lxml/html/usedoctest.py +13 -0
  36. lxml/includes/__init__.pxd +0 -0
  37. lxml/includes/__init__.py +0 -0
  38. lxml/includes/c14n.pxd +25 -0
  39. lxml/includes/config.pxd +3 -0
  40. lxml/includes/dtdvalid.pxd +18 -0
  41. lxml/includes/etree_defs.h +379 -0
  42. lxml/includes/etreepublic.pxd +237 -0
  43. lxml/includes/extlibs/__init__.py +0 -0
  44. lxml/includes/extlibs/libcharset.h +45 -0
  45. lxml/includes/extlibs/localcharset.h +137 -0
  46. lxml/includes/extlibs/zconf.h +543 -0
  47. lxml/includes/extlibs/zlib.h +1938 -0
  48. lxml/includes/htmlparser.pxd +56 -0
  49. lxml/includes/libexslt/__init__.py +0 -0
  50. lxml/includes/libexslt/exslt.h +108 -0
  51. lxml/includes/libexslt/exsltconfig.h +70 -0
  52. lxml/includes/libexslt/exsltexports.h +63 -0
  53. lxml/includes/libxml/HTMLparser.h +339 -0
  54. lxml/includes/libxml/HTMLtree.h +148 -0
  55. lxml/includes/libxml/SAX.h +18 -0
  56. lxml/includes/libxml/SAX2.h +170 -0
  57. lxml/includes/libxml/__init__.py +0 -0
  58. lxml/includes/libxml/c14n.h +115 -0
  59. lxml/includes/libxml/catalog.h +183 -0
  60. lxml/includes/libxml/chvalid.h +230 -0
  61. lxml/includes/libxml/debugXML.h +79 -0
  62. lxml/includes/libxml/dict.h +82 -0
  63. lxml/includes/libxml/encoding.h +307 -0
  64. lxml/includes/libxml/entities.h +147 -0
  65. lxml/includes/libxml/globals.h +25 -0
  66. lxml/includes/libxml/hash.h +251 -0
  67. lxml/includes/libxml/list.h +137 -0
  68. lxml/includes/libxml/nanoftp.h +16 -0
  69. lxml/includes/libxml/nanohttp.h +98 -0
  70. lxml/includes/libxml/parser.h +1633 -0
  71. lxml/includes/libxml/parserInternals.h +591 -0
  72. lxml/includes/libxml/relaxng.h +224 -0
  73. lxml/includes/libxml/schemasInternals.h +959 -0
  74. lxml/includes/libxml/schematron.h +143 -0
  75. lxml/includes/libxml/threads.h +81 -0
  76. lxml/includes/libxml/tree.h +1326 -0
  77. lxml/includes/libxml/uri.h +106 -0
  78. lxml/includes/libxml/valid.h +485 -0
  79. lxml/includes/libxml/xinclude.h +141 -0
  80. lxml/includes/libxml/xlink.h +193 -0
  81. lxml/includes/libxml/xmlIO.h +419 -0
  82. lxml/includes/libxml/xmlautomata.h +163 -0
  83. lxml/includes/libxml/xmlerror.h +962 -0
  84. lxml/includes/libxml/xmlexports.h +96 -0
  85. lxml/includes/libxml/xmlmemory.h +188 -0
  86. lxml/includes/libxml/xmlmodule.h +61 -0
  87. lxml/includes/libxml/xmlreader.h +444 -0
  88. lxml/includes/libxml/xmlregexp.h +116 -0
  89. lxml/includes/libxml/xmlsave.h +111 -0
  90. lxml/includes/libxml/xmlschemas.h +254 -0
  91. lxml/includes/libxml/xmlschemastypes.h +152 -0
  92. lxml/includes/libxml/xmlstring.h +140 -0
  93. lxml/includes/libxml/xmlunicode.h +15 -0
  94. lxml/includes/libxml/xmlversion.h +332 -0
  95. lxml/includes/libxml/xmlwriter.h +489 -0
  96. lxml/includes/libxml/xpath.h +569 -0
  97. lxml/includes/libxml/xpathInternals.h +639 -0
  98. lxml/includes/libxml/xpointer.h +48 -0
  99. lxml/includes/libxslt/__init__.py +0 -0
  100. lxml/includes/libxslt/attributes.h +39 -0
  101. lxml/includes/libxslt/documents.h +93 -0
  102. lxml/includes/libxslt/extensions.h +262 -0
  103. lxml/includes/libxslt/extra.h +72 -0
  104. lxml/includes/libxslt/functions.h +78 -0
  105. lxml/includes/libxslt/imports.h +75 -0
  106. lxml/includes/libxslt/keys.h +53 -0
  107. lxml/includes/libxslt/namespaces.h +68 -0
  108. lxml/includes/libxslt/numbersInternals.h +73 -0
  109. lxml/includes/libxslt/pattern.h +84 -0
  110. lxml/includes/libxslt/preproc.h +43 -0
  111. lxml/includes/libxslt/security.h +104 -0
  112. lxml/includes/libxslt/templates.h +77 -0
  113. lxml/includes/libxslt/transform.h +207 -0
  114. lxml/includes/libxslt/variables.h +118 -0
  115. lxml/includes/libxslt/xslt.h +110 -0
  116. lxml/includes/libxslt/xsltInternals.h +1995 -0
  117. lxml/includes/libxslt/xsltconfig.h +146 -0
  118. lxml/includes/libxslt/xsltexports.h +64 -0
  119. lxml/includes/libxslt/xsltlocale.h +44 -0
  120. lxml/includes/libxslt/xsltutils.h +343 -0
  121. lxml/includes/lxml-version.h +3 -0
  122. lxml/includes/relaxng.pxd +64 -0
  123. lxml/includes/schematron.pxd +34 -0
  124. lxml/includes/tree.pxd +492 -0
  125. lxml/includes/uri.pxd +5 -0
  126. lxml/includes/xinclude.pxd +22 -0
  127. lxml/includes/xmlerror.pxd +852 -0
  128. lxml/includes/xmlparser.pxd +303 -0
  129. lxml/includes/xmlschema.pxd +35 -0
  130. lxml/includes/xpath.pxd +136 -0
  131. lxml/includes/xslt.pxd +190 -0
  132. lxml/isoschematron/__init__.py +348 -0
  133. lxml/isoschematron/resources/rng/iso-schematron.rng +709 -0
  134. lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl +75 -0
  135. lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl +77 -0
  136. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl +313 -0
  137. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl +1160 -0
  138. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl +55 -0
  139. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl +1796 -0
  140. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl +588 -0
  141. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt +84 -0
  142. lxml/iterparse.pxi +438 -0
  143. lxml/lxml.etree.h +244 -0
  144. lxml/lxml.etree_api.h +204 -0
  145. lxml/nsclasses.pxi +281 -0
  146. lxml/objectify.cpython-312-darwin.so +0 -0
  147. lxml/objectify.pyx +2149 -0
  148. lxml/objectpath.pxi +332 -0
  149. lxml/parser.pxi +2059 -0
  150. lxml/parsertarget.pxi +180 -0
  151. lxml/proxy.pxi +619 -0
  152. lxml/public-api.pxi +178 -0
  153. lxml/pyclasslookup.py +3 -0
  154. lxml/readonlytree.pxi +565 -0
  155. lxml/relaxng.pxi +165 -0
  156. lxml/sax.cpython-312-darwin.so +0 -0
  157. lxml/sax.py +286 -0
  158. lxml/saxparser.pxi +875 -0
  159. lxml/schematron.pxi +173 -0
  160. lxml/serializer.pxi +1849 -0
  161. lxml/usedoctest.py +13 -0
  162. lxml/xinclude.pxi +67 -0
  163. lxml/xmlerror.pxi +1654 -0
  164. lxml/xmlid.pxi +179 -0
  165. lxml/xmlschema.pxi +215 -0
  166. lxml/xpath.pxi +487 -0
  167. lxml/xslt.pxi +957 -0
  168. lxml/xsltext.pxi +242 -0
  169. lxml-6.0.0.dist-info/METADATA +163 -0
  170. lxml-6.0.0.dist-info/RECORD +174 -0
  171. lxml-6.0.0.dist-info/WHEEL +6 -0
  172. lxml-6.0.0.dist-info/licenses/LICENSE.txt +31 -0
  173. lxml-6.0.0.dist-info/licenses/LICENSES.txt +29 -0
  174. lxml-6.0.0.dist-info/top_level.txt +1 -0
lxml/apihelpers.pxi ADDED
@@ -0,0 +1,1801 @@
1
+ # Private/public helper functions for API functions
2
+
3
+ from lxml.includes cimport uri
4
+
5
+
6
+ cdef void displayNode(xmlNode* c_node, indent) noexcept:
7
+ # to help with debugging
8
+ cdef xmlNode* c_child
9
+ try:
10
+ print(indent * ' ', <long>c_node)
11
+ c_child = c_node.children
12
+ while c_child is not NULL:
13
+ displayNode(c_child, indent + 1)
14
+ c_child = c_child.next
15
+ finally:
16
+ return # swallow any exceptions
17
+
18
+ cdef inline bint _isHtmlDocument(_Element element) except -1:
19
+ cdef xmlNode* c_node = element._c_node
20
+ return (
21
+ c_node is not NULL and c_node.doc is not NULL and
22
+ c_node.doc.properties & tree.XML_DOC_HTML != 0
23
+ )
24
+
25
+ cdef inline int _assertValidNode(_Element element) except -1:
26
+ assert element._c_node is not NULL, "invalid Element proxy at %s" % id(element)
27
+
28
+ cdef inline int _assertValidDoc(_Document doc) except -1:
29
+ assert doc._c_doc is not NULL, "invalid Document proxy at %s" % id(doc)
30
+
31
+ cdef _Document _documentOrRaise(object input):
32
+ """Call this to get the document of a _Document, _ElementTree or _Element
33
+ object, or to raise an exception if it can't be determined.
34
+
35
+ Should be used in all API functions for consistency.
36
+ """
37
+ cdef _Document doc
38
+ if isinstance(input, _ElementTree):
39
+ if (<_ElementTree>input)._context_node is not None:
40
+ doc = (<_ElementTree>input)._context_node._doc
41
+ else:
42
+ doc = None
43
+ elif isinstance(input, _Element):
44
+ doc = (<_Element>input)._doc
45
+ elif isinstance(input, _Document):
46
+ doc = <_Document>input
47
+ else:
48
+ raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}"
49
+ if doc is None:
50
+ raise ValueError, f"Input object has no document: {python._fqtypename(input).decode('utf8')}"
51
+ _assertValidDoc(doc)
52
+ return doc
53
+
54
+ cdef _Element _rootNodeOrRaise(object input):
55
+ """Call this to get the root node of a _Document, _ElementTree or
56
+ _Element object, or to raise an exception if it can't be determined.
57
+
58
+ Should be used in all API functions for consistency.
59
+ """
60
+ cdef _Element node
61
+ if isinstance(input, _ElementTree):
62
+ node = (<_ElementTree>input)._context_node
63
+ elif isinstance(input, _Element):
64
+ node = <_Element>input
65
+ elif isinstance(input, _Document):
66
+ node = (<_Document>input).getroot()
67
+ else:
68
+ raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}"
69
+ if (node is None or not node._c_node or
70
+ node._c_node.type != tree.XML_ELEMENT_NODE):
71
+ raise ValueError, f"Input object is not an XML element: {python._fqtypename(input).decode('utf8')}"
72
+ _assertValidNode(node)
73
+ return node
74
+
75
+ cdef bint _isAncestorOrSame(xmlNode* c_ancestor, xmlNode* c_node) noexcept:
76
+ while c_node:
77
+ if c_node is c_ancestor:
78
+ return True
79
+ c_node = c_node.parent
80
+ return False
81
+
82
+ cdef _Element _makeElement(tag, xmlDoc* c_doc, _Document doc,
83
+ _BaseParser parser, text, tail, attrib, nsmap,
84
+ dict extra_attrs):
85
+ """Create a new element and initialize text content, namespaces and
86
+ attributes.
87
+
88
+ This helper function will reuse as much of the existing document as
89
+ possible:
90
+
91
+ If 'parser' is None, the parser will be inherited from 'doc' or the
92
+ default parser will be used.
93
+
94
+ If 'doc' is None, 'c_doc' is used to create a new _Document and the new
95
+ element is made its root node.
96
+
97
+ If 'c_doc' is also NULL, a new xmlDoc will be created.
98
+ """
99
+ cdef xmlNode* c_node
100
+ if doc is not None:
101
+ c_doc = doc._c_doc
102
+ ns_utf, name_utf = _getNsTag(tag)
103
+ if parser is not None and parser._for_html:
104
+ _htmlTagValidOrRaise(name_utf)
105
+ if c_doc is NULL:
106
+ c_doc = _newHTMLDoc()
107
+ else:
108
+ _tagValidOrRaise(name_utf)
109
+ if c_doc is NULL:
110
+ c_doc = _newXMLDoc()
111
+ c_node = _createElement(c_doc, name_utf)
112
+ if c_node is NULL:
113
+ if doc is None and c_doc is not NULL:
114
+ tree.xmlFreeDoc(c_doc)
115
+ raise MemoryError()
116
+ try:
117
+ if doc is None:
118
+ tree.xmlDocSetRootElement(c_doc, c_node)
119
+ doc = _documentFactory(c_doc, parser)
120
+ if text is not None:
121
+ _setNodeText(c_node, text)
122
+ if tail is not None:
123
+ _setTailText(c_node, tail)
124
+ # add namespaces to node if necessary
125
+ _setNodeNamespaces(c_node, doc, ns_utf, nsmap)
126
+ _initNodeAttributes(c_node, doc, attrib, extra_attrs)
127
+ return _elementFactory(doc, c_node)
128
+ except:
129
+ # free allocated c_node/c_doc unless Python does it for us
130
+ if c_node.doc is not c_doc:
131
+ # node not yet in document => will not be freed by document
132
+ if tail is not None:
133
+ _removeText(c_node.next) # tail
134
+ tree.xmlFreeNode(c_node)
135
+ if doc is None:
136
+ # c_doc will not be freed by doc
137
+ tree.xmlFreeDoc(c_doc)
138
+ raise
139
+
140
+ cdef int _initNewElement(_Element element, bint is_html, name_utf, ns_utf,
141
+ _BaseParser parser, attrib, nsmap, dict extra_attrs) except -1:
142
+ """Initialise a new Element object.
143
+
144
+ This is used when users instantiate a Python Element subclass
145
+ directly, without it being mapped to an existing XML node.
146
+ """
147
+ cdef xmlDoc* c_doc
148
+ cdef xmlNode* c_node
149
+ cdef _Document doc
150
+ if is_html:
151
+ _htmlTagValidOrRaise(name_utf)
152
+ c_doc = _newHTMLDoc()
153
+ else:
154
+ _tagValidOrRaise(name_utf)
155
+ c_doc = _newXMLDoc()
156
+ c_node = _createElement(c_doc, name_utf)
157
+ if c_node is NULL:
158
+ if c_doc is not NULL:
159
+ tree.xmlFreeDoc(c_doc)
160
+ raise MemoryError()
161
+ tree.xmlDocSetRootElement(c_doc, c_node)
162
+ doc = _documentFactory(c_doc, parser)
163
+ # add namespaces to node if necessary
164
+ _setNodeNamespaces(c_node, doc, ns_utf, nsmap)
165
+ _initNodeAttributes(c_node, doc, attrib, extra_attrs)
166
+ _registerProxy(element, doc, c_node)
167
+ element._init()
168
+ return 0
169
+
170
+ cdef _Element _makeSubElement(_Element parent, tag, text, tail,
171
+ attrib, nsmap, dict extra_attrs):
172
+ """Create a new child element and initialize text content, namespaces and
173
+ attributes.
174
+ """
175
+ cdef xmlNode* c_node
176
+ cdef xmlDoc* c_doc
177
+ if parent is None or parent._doc is None:
178
+ return None
179
+ _assertValidNode(parent)
180
+ ns_utf, name_utf = _getNsTag(tag)
181
+ c_doc = parent._doc._c_doc
182
+
183
+ if parent._doc._parser is not None and parent._doc._parser._for_html:
184
+ _htmlTagValidOrRaise(name_utf)
185
+ else:
186
+ _tagValidOrRaise(name_utf)
187
+
188
+ c_node = _createElement(c_doc, name_utf)
189
+ if c_node is NULL:
190
+ raise MemoryError()
191
+ tree.xmlAddChild(parent._c_node, c_node)
192
+
193
+ try:
194
+ if text is not None:
195
+ _setNodeText(c_node, text)
196
+ if tail is not None:
197
+ _setTailText(c_node, tail)
198
+
199
+ # add namespaces to node if necessary
200
+ _setNodeNamespaces(c_node, parent._doc, ns_utf, nsmap)
201
+ _initNodeAttributes(c_node, parent._doc, attrib, extra_attrs)
202
+ return _elementFactory(parent._doc, c_node)
203
+ except:
204
+ # make sure we clean up in case of an error
205
+ _removeNode(parent._doc, c_node)
206
+ raise
207
+
208
+
209
+ cdef int _setNodeNamespaces(xmlNode* c_node, _Document doc,
210
+ object node_ns_utf, object nsmap) except -1:
211
+ """Lookup current namespace prefixes, then set namespace structure for
212
+ node (if 'node_ns_utf' was provided) and register new ns-prefix mappings.
213
+
214
+ 'node_ns_utf' should only be passed for a newly created node.
215
+ """
216
+ cdef xmlNs* c_ns
217
+ cdef list nsdefs
218
+
219
+ if nsmap:
220
+ for prefix, href in _iter_nsmap(nsmap):
221
+ href_utf = _utf8(href)
222
+ _uriValidOrRaise(href_utf)
223
+ c_href = _xcstr(href_utf)
224
+ if prefix is not None:
225
+ prefix_utf = _utf8(prefix)
226
+ _prefixValidOrRaise(prefix_utf)
227
+ c_prefix = _xcstr(prefix_utf)
228
+ else:
229
+ c_prefix = <const_xmlChar*>NULL
230
+ # add namespace with prefix if it is not already known
231
+ c_ns = tree.xmlSearchNs(doc._c_doc, c_node, c_prefix)
232
+ if c_ns is NULL or \
233
+ c_ns.href is NULL or \
234
+ tree.xmlStrcmp(c_ns.href, c_href) != 0:
235
+ c_ns = tree.xmlNewNs(c_node, c_href, c_prefix)
236
+ if href_utf == node_ns_utf:
237
+ tree.xmlSetNs(c_node, c_ns)
238
+ node_ns_utf = None
239
+
240
+ if node_ns_utf is not None:
241
+ _uriValidOrRaise(node_ns_utf)
242
+ doc._setNodeNs(c_node, _xcstr(node_ns_utf))
243
+ return 0
244
+
245
+
246
+ cdef dict _build_nsmap(xmlNode* c_node):
247
+ """
248
+ Namespace prefix->URI mapping known in the context of this Element.
249
+ This includes all namespace declarations of the parents.
250
+ """
251
+ cdef xmlNs* c_ns
252
+ nsmap = {}
253
+ while c_node is not NULL and c_node.type == tree.XML_ELEMENT_NODE:
254
+ c_ns = c_node.nsDef
255
+ while c_ns is not NULL:
256
+ if c_ns.prefix or c_ns.href:
257
+ prefix = funicodeOrNone(c_ns.prefix)
258
+ if prefix not in nsmap:
259
+ nsmap[prefix] = funicodeOrNone(c_ns.href)
260
+ c_ns = c_ns.next
261
+ c_node = c_node.parent
262
+ return nsmap
263
+
264
+
265
+ cdef _iter_nsmap(nsmap):
266
+ """
267
+ Create a reproducibly ordered iterable from an nsmap mapping.
268
+ Tries to preserve an existing order and sorts if it assumes no order.
269
+
270
+ The difference to _iter_attrib() is that None doesn't sort with strings
271
+ in Py3.x.
272
+ """
273
+ if isinstance(nsmap, dict):
274
+ # dicts are insertion-ordered in Py3.6+ => keep the user provided order.
275
+ return nsmap.items()
276
+ if len(nsmap) <= 1:
277
+ return nsmap.items()
278
+ # nsmap will usually be a plain unordered dict => avoid type checking overhead
279
+ if type(nsmap) is not dict and isinstance(nsmap, OrderedDict):
280
+ return nsmap.items() # keep existing order
281
+ if None not in nsmap:
282
+ return sorted(nsmap.items())
283
+
284
+ # Move the default namespace to the end. This makes sure libxml2
285
+ # prefers a prefix if the ns is defined redundantly on the same
286
+ # element. That way, users can work around a problem themselves
287
+ # where default namespace attributes on non-default namespaced
288
+ # elements serialise without prefix (i.e. into the non-default
289
+ # namespace).
290
+ default_ns = nsmap[None]
291
+ nsdefs = [(k, v) for k, v in nsmap.items() if k is not None]
292
+ nsdefs.sort()
293
+ nsdefs.append((None, default_ns))
294
+ return nsdefs
295
+
296
+
297
+ cdef _iter_attrib(attrib):
298
+ """
299
+ Create a reproducibly ordered iterable from an attrib mapping.
300
+ Tries to preserve an existing order and sorts if it assumes no order.
301
+ """
302
+ # dicts are insertion-ordered in Py3.6+ => keep the user provided order.
303
+ if isinstance(attrib, (dict, _Attrib, OrderedDict)):
304
+ return attrib.items()
305
+ # assume it's an unordered mapping of some kind
306
+ return sorted(attrib.items())
307
+
308
+
309
+ cdef _initNodeAttributes(xmlNode* c_node, _Document doc, attrib, dict extra):
310
+ """Initialise the attributes of an element node.
311
+ """
312
+ cdef bint is_html
313
+ cdef xmlNs* c_ns
314
+ if attrib is not None and not hasattr(attrib, 'items'):
315
+ raise TypeError, f"Invalid attribute dictionary: {python._fqtypename(attrib).decode('utf8')}"
316
+ if not attrib and not extra:
317
+ return # nothing to do
318
+ is_html = doc._parser._for_html
319
+ seen = set()
320
+ if extra:
321
+ for name, value in extra.items():
322
+ _addAttributeToNode(c_node, doc, is_html, name, value, seen)
323
+ if attrib:
324
+ for name, value in _iter_attrib(attrib):
325
+ _addAttributeToNode(c_node, doc, is_html, name, value, seen)
326
+
327
+
328
+ cdef int _addAttributeToNode(xmlNode* c_node, _Document doc, bint is_html,
329
+ name, value, set seen_tags) except -1:
330
+ ns_utf, name_utf = tag = _getNsTag(name)
331
+ if tag in seen_tags:
332
+ return 0
333
+ seen_tags.add(tag)
334
+ if not is_html:
335
+ _attributeValidOrRaise(name_utf)
336
+ value_utf = _utf8(value)
337
+ if ns_utf is None:
338
+ tree.xmlNewProp(c_node, _xcstr(name_utf), _xcstr(value_utf))
339
+ else:
340
+ _uriValidOrRaise(ns_utf)
341
+ c_ns = doc._findOrBuildNodeNs(c_node, _xcstr(ns_utf), NULL, 1)
342
+ tree.xmlNewNsProp(c_node, c_ns,
343
+ _xcstr(name_utf), _xcstr(value_utf))
344
+ return 0
345
+
346
+
347
+ ctypedef struct _ns_node_ref:
348
+ xmlNs* ns
349
+ xmlNode* node
350
+
351
+
352
+ cdef int _collectNsDefs(xmlNode* c_element, _ns_node_ref **_c_ns_list,
353
+ size_t *_c_ns_list_len, size_t *_c_ns_list_size) except -1:
354
+ c_ns_list = _c_ns_list[0]
355
+ cdef size_t c_ns_list_len = _c_ns_list_len[0]
356
+ cdef size_t c_ns_list_size = _c_ns_list_size[0]
357
+
358
+ c_nsdef = c_element.nsDef
359
+ while c_nsdef is not NULL:
360
+ if c_ns_list_len >= c_ns_list_size:
361
+ if c_ns_list is NULL:
362
+ c_ns_list_size = 20
363
+ else:
364
+ c_ns_list_size *= 2
365
+ c_nsref_ptr = <_ns_node_ref*> python.lxml_realloc(
366
+ c_ns_list, c_ns_list_size, sizeof(_ns_node_ref))
367
+ if c_nsref_ptr is NULL:
368
+ if c_ns_list is not NULL:
369
+ python.lxml_free(c_ns_list)
370
+ _c_ns_list[0] = NULL
371
+ raise MemoryError()
372
+ c_ns_list = c_nsref_ptr
373
+
374
+ c_ns_list[c_ns_list_len] = _ns_node_ref(c_nsdef, c_element)
375
+ c_ns_list_len += 1
376
+ c_nsdef = c_nsdef.next
377
+
378
+ _c_ns_list_size[0] = c_ns_list_size
379
+ _c_ns_list_len[0] = c_ns_list_len
380
+ _c_ns_list[0] = c_ns_list
381
+
382
+
383
+ cdef int _removeUnusedNamespaceDeclarations(xmlNode* c_element, set prefixes_to_keep) except -1:
384
+ """Remove any namespace declarations from a subtree that are not used by
385
+ any of its elements (or attributes).
386
+
387
+ If a 'prefixes_to_keep' is provided, it must be a set of prefixes.
388
+ Any corresponding namespace mappings will not be removed as part of the cleanup.
389
+ """
390
+ cdef xmlNode* c_node
391
+ cdef _ns_node_ref* c_ns_list = NULL
392
+ cdef size_t c_ns_list_size = 0
393
+ cdef size_t c_ns_list_len = 0
394
+ cdef size_t i
395
+
396
+ if c_element.parent and c_element.parent.type == tree.XML_DOCUMENT_NODE:
397
+ # include declarations on the document node
398
+ _collectNsDefs(c_element.parent, &c_ns_list, &c_ns_list_len, &c_ns_list_size)
399
+
400
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_element, c_element, 1)
401
+ # collect all new namespace declarations into the ns list
402
+ if c_element.nsDef:
403
+ _collectNsDefs(c_element, &c_ns_list, &c_ns_list_len, &c_ns_list_size)
404
+
405
+ # remove all namespace declarations from the list that are referenced
406
+ if c_ns_list_len and c_element.type == tree.XML_ELEMENT_NODE:
407
+ c_node = c_element
408
+ while c_node and c_ns_list_len:
409
+ if c_node.ns:
410
+ for i in range(c_ns_list_len):
411
+ if c_node.ns is c_ns_list[i].ns:
412
+ c_ns_list_len -= 1
413
+ c_ns_list[i] = c_ns_list[c_ns_list_len]
414
+ #c_ns_list[c_ns_list_len] = _ns_node_ref(NULL, NULL)
415
+ break
416
+ if c_node is c_element:
417
+ # continue with attributes
418
+ c_node = <xmlNode*>c_element.properties
419
+ else:
420
+ c_node = c_node.next
421
+ tree.END_FOR_EACH_ELEMENT_FROM(c_element)
422
+
423
+ if c_ns_list is NULL:
424
+ return 0
425
+
426
+ # free all namespace declarations that remained in the list,
427
+ # except for those we should keep explicitly
428
+ cdef xmlNs* c_nsdef
429
+ for i in range(c_ns_list_len):
430
+ if prefixes_to_keep is not None:
431
+ if c_ns_list[i].ns.prefix and c_ns_list[i].ns.prefix in prefixes_to_keep:
432
+ continue
433
+ c_node = c_ns_list[i].node
434
+ c_nsdef = c_node.nsDef
435
+ if c_nsdef is c_ns_list[i].ns:
436
+ c_node.nsDef = c_node.nsDef.next
437
+ else:
438
+ while c_nsdef.next is not c_ns_list[i].ns:
439
+ c_nsdef = c_nsdef.next
440
+ c_nsdef.next = c_nsdef.next.next
441
+ tree.xmlFreeNs(c_ns_list[i].ns)
442
+
443
+ if c_ns_list is not NULL:
444
+ python.lxml_free(c_ns_list)
445
+ return 0
446
+
447
+ cdef xmlNs* _searchNsByHref(xmlNode* c_node, const_xmlChar* c_href, bint is_attribute) noexcept:
448
+ """Search a namespace declaration that covers a node (element or
449
+ attribute).
450
+
451
+ For attributes, try to find a prefixed namespace declaration
452
+ instead of the default namespaces. This helps in supporting
453
+ round-trips for attributes on elements with a different namespace.
454
+ """
455
+ cdef xmlNs* c_ns
456
+ cdef xmlNs* c_default_ns = NULL
457
+ cdef xmlNode* c_element
458
+ if c_href is NULL or c_node is NULL or c_node.type == tree.XML_ENTITY_REF_NODE:
459
+ return NULL
460
+ if tree.xmlStrcmp(c_href, tree.XML_XML_NAMESPACE) == 0:
461
+ # no special cases here, let libxml2 handle this
462
+ return tree.xmlSearchNsByHref(c_node.doc, c_node, c_href)
463
+ if c_node.type == tree.XML_ATTRIBUTE_NODE:
464
+ is_attribute = 1
465
+ while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE:
466
+ c_node = c_node.parent
467
+ c_element = c_node
468
+ while c_node is not NULL:
469
+ if c_node.type == tree.XML_ELEMENT_NODE:
470
+ c_ns = c_node.nsDef
471
+ while c_ns is not NULL:
472
+ if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0:
473
+ if c_ns.prefix is NULL and is_attribute:
474
+ # for attributes, continue searching a named
475
+ # prefix, but keep the first default namespace
476
+ # declaration that we found
477
+ if c_default_ns is NULL:
478
+ c_default_ns = c_ns
479
+ elif tree.xmlSearchNs(
480
+ c_element.doc, c_element, c_ns.prefix) is c_ns:
481
+ # start node is in namespace scope => found!
482
+ return c_ns
483
+ c_ns = c_ns.next
484
+ if c_node is not c_element and c_node.ns is not NULL:
485
+ # optimise: the node may have the namespace itself
486
+ c_ns = c_node.ns
487
+ if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0:
488
+ if c_ns.prefix is NULL and is_attribute:
489
+ # for attributes, continue searching a named
490
+ # prefix, but keep the first default namespace
491
+ # declaration that we found
492
+ if c_default_ns is NULL:
493
+ c_default_ns = c_ns
494
+ elif tree.xmlSearchNs(
495
+ c_element.doc, c_element, c_ns.prefix) is c_ns:
496
+ # start node is in namespace scope => found!
497
+ return c_ns
498
+ c_node = c_node.parent
499
+ # nothing found => use a matching default namespace or fail
500
+ if c_default_ns is not NULL:
501
+ if tree.xmlSearchNs(c_element.doc, c_element, NULL) is c_default_ns:
502
+ return c_default_ns
503
+ return NULL
504
+
505
+ cdef int _replaceNodeByChildren(_Document doc, xmlNode* c_node) except -1:
506
+ # NOTE: this does not deallocate the node, just unlink it!
507
+ cdef xmlNode* c_parent
508
+ cdef xmlNode* c_child
509
+ if c_node.children is NULL:
510
+ tree.xmlUnlinkNode(c_node)
511
+ return 0
512
+
513
+ c_parent = c_node.parent
514
+ # fix parent links of children
515
+ c_child = c_node.children
516
+ while c_child is not NULL:
517
+ c_child.parent = c_parent
518
+ c_child = c_child.next
519
+
520
+ # fix namespace references of children if their parent's namespace
521
+ # declarations get lost
522
+ if c_node.nsDef is not NULL:
523
+ c_child = c_node.children
524
+ while c_child is not NULL:
525
+ moveNodeToDocument(doc, doc._c_doc, c_child)
526
+ c_child = c_child.next
527
+
528
+ # fix sibling links to/from child slice
529
+ if c_node.prev is NULL:
530
+ c_parent.children = c_node.children
531
+ else:
532
+ c_node.prev.next = c_node.children
533
+ c_node.children.prev = c_node.prev
534
+ if c_node.next is NULL:
535
+ c_parent.last = c_node.last
536
+ else:
537
+ c_node.next.prev = c_node.last
538
+ c_node.last.next = c_node.next
539
+
540
+ # unlink c_node
541
+ c_node.children = c_node.last = NULL
542
+ c_node.parent = c_node.next = c_node.prev = NULL
543
+ return 0
544
+
545
+ cdef unicode _attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node):
546
+ c_href = _getNs(<xmlNode*>c_attrib_node)
547
+ value = tree.xmlGetNsProp(c_element, c_attrib_node.name, c_href)
548
+ try:
549
+ result = funicode(value)
550
+ finally:
551
+ tree.xmlFree(value)
552
+ return result
553
+
554
+ cdef unicode _attributeValueFromNsName(xmlNode* c_element,
555
+ const_xmlChar* c_href, const_xmlChar* c_name):
556
+ c_result = tree.xmlGetNsProp(c_element, c_name, c_href)
557
+ if c_result is NULL:
558
+ return None
559
+ try:
560
+ result = funicode(c_result)
561
+ finally:
562
+ tree.xmlFree(c_result)
563
+ return result
564
+
565
+ cdef object _getNodeAttributeValue(xmlNode* c_node, key, default):
566
+ ns, tag = _getNsTag(key)
567
+ c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
568
+ c_result = tree.xmlGetNsProp(c_node, _xcstr(tag), c_href)
569
+ if c_result is NULL:
570
+ # XXX free namespace that is not in use..?
571
+ return default
572
+ try:
573
+ result = funicode(c_result)
574
+ finally:
575
+ tree.xmlFree(c_result)
576
+ return result
577
+
578
+ cdef inline object _getAttributeValue(_Element element, key, default):
579
+ return _getNodeAttributeValue(element._c_node, key, default)
580
+
581
+ cdef int _setAttributeValue(_Element element, key, value) except -1:
582
+ cdef const_xmlChar* c_value
583
+ cdef xmlNs* c_ns
584
+ ns, tag = _getNsTag(key)
585
+ is_html = element._doc._parser._for_html
586
+ if not is_html:
587
+ _attributeValidOrRaise(tag)
588
+ c_tag = _xcstr(tag)
589
+ if value is None and is_html:
590
+ c_value = NULL
591
+ else:
592
+ if isinstance(value, QName):
593
+ value = _resolveQNameText(element, value)
594
+ else:
595
+ value = _utf8(value)
596
+ c_value = _xcstr(value)
597
+ if ns is None:
598
+ c_ns = NULL
599
+ else:
600
+ c_ns = element._doc._findOrBuildNodeNs(element._c_node, _xcstr(ns), NULL, 1)
601
+ tree.xmlSetNsProp(element._c_node, c_ns, c_tag, c_value)
602
+ return 0
603
+
604
+ cdef int _delAttribute(_Element element, key) except -1:
605
+ ns, tag = _getNsTag(key)
606
+ c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
607
+ if _delAttributeFromNsName(element._c_node, c_href, _xcstr(tag)):
608
+ raise KeyError, key
609
+ return 0
610
+
611
+ cdef int _delAttributeFromNsName(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
612
+ c_attr = tree.xmlHasNsProp(c_node, c_name, c_href)
613
+ if c_attr is NULL:
614
+ # XXX free namespace that is not in use..?
615
+ return -1
616
+ tree.xmlRemoveProp(c_attr)
617
+ return 0
618
+
619
+ cdef list _collectAttributes(xmlNode* c_node, int collecttype):
620
+ """Collect all attributes of a node in a list. Depending on collecttype,
621
+ it collects either the name (1), the value (2) or the name-value tuples.
622
+ """
623
+ cdef Py_ssize_t count
624
+ c_attr = c_node.properties
625
+ count = 0
626
+ while c_attr is not NULL:
627
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
628
+ count += 1
629
+ c_attr = c_attr.next
630
+
631
+ if not count:
632
+ return []
633
+
634
+ attributes = [None] * count
635
+ c_attr = c_node.properties
636
+ count = 0
637
+ while c_attr is not NULL:
638
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
639
+ if collecttype == 1:
640
+ item = _namespacedName(<xmlNode*>c_attr)
641
+ elif collecttype == 2:
642
+ item = _attributeValue(c_node, c_attr)
643
+ else:
644
+ item = (_namespacedName(<xmlNode*>c_attr),
645
+ _attributeValue(c_node, c_attr))
646
+ attributes[count] = item
647
+ count += 1
648
+ c_attr = c_attr.next
649
+ return attributes
650
+
651
+ cdef object __RE_XML_ENCODING = re.compile(
652
+ r'^(<\?xml[^>]+)\s+encoding\s*=\s*["\'][^"\']*["\'](\s*\?>|)', re.U)
653
+
654
+ cdef object __REPLACE_XML_ENCODING = __RE_XML_ENCODING.sub
655
+ cdef object __HAS_XML_ENCODING = __RE_XML_ENCODING.match
656
+
657
+ cdef object _stripEncodingDeclaration(object xml_string):
658
+ # this is a hack to remove the XML encoding declaration from unicode
659
+ return __REPLACE_XML_ENCODING(r'\g<1>\g<2>', xml_string)
660
+
661
+ cdef bint _hasEncodingDeclaration(object xml_string) except -1:
662
+ # check if a (unicode) string has an XML encoding declaration
663
+ return __HAS_XML_ENCODING(xml_string) is not None
664
+
665
+ cdef inline bint _hasText(xmlNode* c_node) noexcept:
666
+ return c_node is not NULL and _textNodeOrSkip(c_node.children) is not NULL
667
+
668
+ cdef inline bint _hasTail(xmlNode* c_node) noexcept:
669
+ return c_node is not NULL and _textNodeOrSkip(c_node.next) is not NULL
670
+
671
+ cdef inline bint _hasNonWhitespaceTail(xmlNode* c_node) except -1:
672
+ return _hasNonWhitespaceText(c_node, tail=True)
673
+
674
+ cdef bint _hasNonWhitespaceText(xmlNode* c_node, bint tail=False) except -1:
675
+ c_text_node = c_node and _textNodeOrSkip(c_node.next if tail else c_node.children)
676
+ if c_text_node is NULL:
677
+ return False
678
+ while c_text_node is not NULL:
679
+ if c_text_node.content[0] != c'\0' and not _collectText(c_text_node).isspace():
680
+ return True
681
+ c_text_node = _textNodeOrSkip(c_text_node.next)
682
+ return False
683
+
684
+ cdef unicode _collectText(xmlNode* c_node):
685
+ """Collect all text nodes and return them as a unicode string.
686
+
687
+ Start collecting at c_node.
688
+
689
+ If there was no text to collect, return None
690
+ """
691
+ cdef Py_ssize_t scount
692
+ cdef xmlChar* c_text
693
+ cdef xmlNode* c_node_cur
694
+ # check for multiple text nodes
695
+ scount = 0
696
+ c_text = NULL
697
+ c_node_cur = c_node = _textNodeOrSkip(c_node)
698
+ while c_node_cur is not NULL:
699
+ if c_node_cur.content[0] != c'\0':
700
+ c_text = c_node_cur.content
701
+ scount += 1
702
+ c_node_cur = _textNodeOrSkip(c_node_cur.next)
703
+
704
+ # handle two most common cases first
705
+ if c_text is NULL:
706
+ return '' if scount > 0 else None
707
+ if scount == 1:
708
+ return funicode(c_text)
709
+
710
+ # the rest is not performance critical anymore
711
+ result = b''
712
+ while c_node is not NULL:
713
+ result += <unsigned char*>c_node.content
714
+ c_node = _textNodeOrSkip(c_node.next)
715
+ return funicode(<const_xmlChar*><unsigned char*>result)
716
+
717
+ cdef void _removeText(xmlNode* c_node) noexcept:
718
+ """Remove all text nodes.
719
+
720
+ Start removing at c_node.
721
+ """
722
+ cdef xmlNode* c_next
723
+ c_node = _textNodeOrSkip(c_node)
724
+ while c_node is not NULL:
725
+ c_next = _textNodeOrSkip(c_node.next)
726
+ tree.xmlUnlinkNode(c_node)
727
+ tree.xmlFreeNode(c_node)
728
+ c_node = c_next
729
+
730
+ cdef xmlNode* _createTextNode(xmlDoc* doc, value) except NULL:
731
+ cdef xmlNode* c_text_node
732
+ if isinstance(value, CDATA):
733
+ c_text_node = tree.xmlNewCDataBlock(
734
+ doc, _xcstr((<CDATA>value)._utf8_data),
735
+ python.PyBytes_GET_SIZE((<CDATA>value)._utf8_data))
736
+ else:
737
+ text = _utf8(value)
738
+ c_text_node = tree.xmlNewDocText(doc, _xcstr(text))
739
+ if not c_text_node:
740
+ raise MemoryError()
741
+ return c_text_node
742
+
743
+ cdef int _setNodeText(xmlNode* c_node, value) except -1:
744
+ # remove all text nodes at the start first
745
+ _removeText(c_node.children)
746
+ if value is None:
747
+ return 0
748
+ # now add new text node with value at start
749
+ c_text_node = _createTextNode(c_node.doc, value)
750
+ if c_node.children is NULL:
751
+ tree.xmlAddChild(c_node, c_text_node)
752
+ else:
753
+ tree.xmlAddPrevSibling(c_node.children, c_text_node)
754
+ return 0
755
+
756
+ cdef int _setTailText(xmlNode* c_node, value) except -1:
757
+ # remove all text nodes at the start first
758
+ _removeText(c_node.next)
759
+ if value is None:
760
+ return 0
761
+ # now append new text node with value
762
+ c_text_node = _createTextNode(c_node.doc, value)
763
+ tree.xmlAddNextSibling(c_node, c_text_node)
764
+ return 0
765
+
766
+ cdef bytes _resolveQNameText(_Element element, value):
767
+ cdef xmlNs* c_ns
768
+ ns, tag = _getNsTag(value)
769
+ if ns is None:
770
+ return tag
771
+ else:
772
+ c_ns = element._doc._findOrBuildNodeNs(
773
+ element._c_node, _xcstr(ns), NULL, 0)
774
+ return python.PyBytes_FromFormat('%s:%s', c_ns.prefix, _cstr(tag))
775
+
776
+ cdef inline bint _hasChild(xmlNode* c_node) noexcept:
777
+ return c_node is not NULL and _findChildForwards(c_node, 0) is not NULL
778
+
779
+ cdef inline Py_ssize_t _countElements(xmlNode* c_node) noexcept:
780
+ "Counts the elements within the following siblings and the node itself."
781
+ cdef Py_ssize_t count
782
+ count = 0
783
+ while c_node is not NULL:
784
+ if _isElement(c_node):
785
+ count += 1
786
+ c_node = c_node.next
787
+ return count
788
+
789
+ cdef int _findChildSlice(
790
+ slice sliceobject, xmlNode* c_parent,
791
+ xmlNode** c_start_node, Py_ssize_t* c_step, Py_ssize_t* c_length) except -1:
792
+ """Resolve a children slice.
793
+
794
+ Returns the start node, step size and the slice length in the
795
+ pointer arguments.
796
+ """
797
+ cdef Py_ssize_t start = 0, stop = 0, childcount
798
+ childcount = _countElements(c_parent.children)
799
+ if childcount == 0:
800
+ c_start_node[0] = NULL
801
+ c_length[0] = 0
802
+ if sliceobject.step is None:
803
+ c_step[0] = 1
804
+ else:
805
+ python._PyEval_SliceIndex(sliceobject.step, c_step)
806
+ return 0
807
+ python.PySlice_GetIndicesEx(
808
+ sliceobject, childcount, &start, &stop, c_step, c_length)
809
+ if start > childcount // 2:
810
+ c_start_node[0] = _findChildBackwards(c_parent, childcount - start - 1)
811
+ else:
812
+ c_start_node[0] = _findChild(c_parent, start)
813
+ return 0
814
+
815
+ cdef bint _isFullSlice(slice sliceobject) except -1:
816
+ """Conservative guess if this slice is a full slice as in ``s[:]``.
817
+ """
818
+ cdef Py_ssize_t step = 0
819
+ if sliceobject is None:
820
+ return 0
821
+ if sliceobject.start is None and \
822
+ sliceobject.stop is None:
823
+ if sliceobject.step is None:
824
+ return 1
825
+ python._PyEval_SliceIndex(sliceobject.step, &step)
826
+ if step == 1:
827
+ return 1
828
+ return 0
829
+ return 0
830
+
831
+ cdef _collectChildren(_Element element):
832
+ cdef xmlNode* c_node
833
+ cdef list result = []
834
+ c_node = element._c_node.children
835
+ if c_node is not NULL:
836
+ if not _isElement(c_node):
837
+ c_node = _nextElement(c_node)
838
+ while c_node is not NULL:
839
+ result.append(_elementFactory(element._doc, c_node))
840
+ c_node = _nextElement(c_node)
841
+ return result
842
+
843
+ cdef inline xmlNode* _findChild(xmlNode* c_node, Py_ssize_t index) noexcept:
844
+ if index < 0:
845
+ return _findChildBackwards(c_node, -index - 1)
846
+ else:
847
+ return _findChildForwards(c_node, index)
848
+
849
+ cdef inline xmlNode* _findChildForwards(xmlNode* c_node, Py_ssize_t index) noexcept:
850
+ """Return child element of c_node with index, or return NULL if not found.
851
+ """
852
+ cdef xmlNode* c_child
853
+ cdef Py_ssize_t c
854
+ c_child = c_node.children
855
+ c = 0
856
+ while c_child is not NULL:
857
+ if _isElement(c_child):
858
+ if c == index:
859
+ return c_child
860
+ c += 1
861
+ c_child = c_child.next
862
+ return NULL
863
+
864
+ cdef inline xmlNode* _findChildBackwards(xmlNode* c_node, Py_ssize_t index) noexcept:
865
+ """Return child element of c_node with index, or return NULL if not found.
866
+ Search from the end.
867
+ """
868
+ cdef xmlNode* c_child
869
+ cdef Py_ssize_t c
870
+ c_child = c_node.last
871
+ c = 0
872
+ while c_child is not NULL:
873
+ if _isElement(c_child):
874
+ if c == index:
875
+ return c_child
876
+ c += 1
877
+ c_child = c_child.prev
878
+ return NULL
879
+
880
+ cdef inline xmlNode* _textNodeOrSkip(xmlNode* c_node) noexcept nogil:
881
+ """Return the node if it's a text node. Skip over ignorable nodes in a
882
+ series of text nodes. Return NULL if a non-ignorable node is found.
883
+
884
+ This is used to skip over XInclude nodes when collecting adjacent text
885
+ nodes.
886
+ """
887
+ while c_node is not NULL:
888
+ if c_node.type == tree.XML_TEXT_NODE or \
889
+ c_node.type == tree.XML_CDATA_SECTION_NODE:
890
+ return c_node
891
+ elif c_node.type == tree.XML_XINCLUDE_START or \
892
+ c_node.type == tree.XML_XINCLUDE_END:
893
+ c_node = c_node.next
894
+ else:
895
+ return NULL
896
+ return NULL
897
+
898
+ cdef inline xmlNode* _nextElement(xmlNode* c_node) noexcept:
899
+ """Given a node, find the next sibling that is an element.
900
+ """
901
+ if c_node is NULL:
902
+ return NULL
903
+ c_node = c_node.next
904
+ while c_node is not NULL:
905
+ if _isElement(c_node):
906
+ return c_node
907
+ c_node = c_node.next
908
+ return NULL
909
+
910
+ cdef inline xmlNode* _previousElement(xmlNode* c_node) noexcept:
911
+ """Given a node, find the next sibling that is an element.
912
+ """
913
+ if c_node is NULL:
914
+ return NULL
915
+ c_node = c_node.prev
916
+ while c_node is not NULL:
917
+ if _isElement(c_node):
918
+ return c_node
919
+ c_node = c_node.prev
920
+ return NULL
921
+
922
+ cdef inline xmlNode* _parentElement(xmlNode* c_node) noexcept:
923
+ "Given a node, find the parent element."
924
+ if c_node is NULL or not _isElement(c_node):
925
+ return NULL
926
+ c_node = c_node.parent
927
+ if c_node is NULL or not _isElement(c_node):
928
+ return NULL
929
+ return c_node
930
+
931
+ cdef inline bint _tagMatches(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
932
+ """Tests if the node matches namespace URI and tag name.
933
+
934
+ A node matches if it matches both c_href and c_name.
935
+
936
+ A node matches c_href if any of the following is true:
937
+ * c_href is NULL
938
+ * its namespace is NULL and c_href is the empty string
939
+ * its namespace string equals the c_href string
940
+
941
+ A node matches c_name if any of the following is true:
942
+ * c_name is NULL
943
+ * its name string equals the c_name string
944
+ """
945
+ if c_node is NULL:
946
+ return 0
947
+ if c_node.type != tree.XML_ELEMENT_NODE:
948
+ # not an element, only succeed if we match everything
949
+ return c_name is NULL and c_href is NULL
950
+ if c_name is NULL:
951
+ if c_href is NULL:
952
+ # always match
953
+ return 1
954
+ else:
955
+ c_node_href = _getNs(c_node)
956
+ if c_node_href is NULL:
957
+ return c_href[0] == c'\0'
958
+ else:
959
+ return tree.xmlStrcmp(c_node_href, c_href) == 0
960
+ elif c_href is NULL:
961
+ if _getNs(c_node) is not NULL:
962
+ return 0
963
+ return c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0
964
+ elif c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0:
965
+ c_node_href = _getNs(c_node)
966
+ if c_node_href is NULL:
967
+ return c_href[0] == c'\0'
968
+ else:
969
+ return tree.xmlStrcmp(c_node_href, c_href) == 0
970
+ else:
971
+ return 0
972
+
973
+ cdef inline bint _tagMatchesExactly(xmlNode* c_node, qname* c_qname) noexcept:
974
+ """Tests if the node matches namespace URI and tag name.
975
+
976
+ This differs from _tagMatches() in that it does not consider a
977
+ NULL value in qname.href a wildcard, and that it expects the c_name
978
+ to be taken from the doc dict, i.e. it only compares the names by
979
+ address.
980
+
981
+ A node matches if it matches both href and c_name of the qname.
982
+
983
+ A node matches c_href if any of the following is true:
984
+ * its namespace is NULL and c_href is the empty string
985
+ * its namespace string equals the c_href string
986
+
987
+ A node matches c_name if any of the following is true:
988
+ * c_name is NULL
989
+ * its name string points to the same address (!) as c_name
990
+ """
991
+ return _nsTagMatchesExactly(_getNs(c_node), c_node.name, c_qname)
992
+
993
+ cdef inline bint _nsTagMatchesExactly(const_xmlChar* c_node_href,
994
+ const_xmlChar* c_node_name,
995
+ qname* c_qname) noexcept:
996
+ """Tests if name and namespace URI match those of c_qname.
997
+
998
+ This differs from _tagMatches() in that it does not consider a
999
+ NULL value in qname.href a wildcard, and that it expects the c_name
1000
+ to be taken from the doc dict, i.e. it only compares the names by
1001
+ address.
1002
+
1003
+ A node matches if it matches both href and c_name of the qname.
1004
+
1005
+ A node matches c_href if any of the following is true:
1006
+ * its namespace is NULL and c_href is the empty string
1007
+ * its namespace string equals the c_href string
1008
+
1009
+ A node matches c_name if any of the following is true:
1010
+ * c_name is NULL
1011
+ * its name string points to the same address (!) as c_name
1012
+ """
1013
+ cdef char* c_href
1014
+ if c_qname.c_name is not NULL and c_qname.c_name is not c_node_name:
1015
+ return 0
1016
+ if c_qname.href is NULL:
1017
+ return 1
1018
+ c_href = python.__cstr(c_qname.href)
1019
+ if c_href[0] == b'\0':
1020
+ return c_node_href is NULL or c_node_href[0] == b'\0'
1021
+ elif c_node_href is NULL:
1022
+ return 0
1023
+ else:
1024
+ return tree.xmlStrcmp(<const_xmlChar*>c_href, c_node_href) == 0
1025
+
1026
+ cdef Py_ssize_t _mapTagsToQnameMatchArray(xmlDoc* c_doc, list ns_tags,
1027
+ qname* c_ns_tags, bint force_into_dict) except -1:
1028
+ """Map a sequence of (name, namespace) pairs to a qname array for efficient
1029
+ matching with _tagMatchesExactly() above.
1030
+
1031
+ Note that each qname struct in the array owns its href byte string object
1032
+ if it is not NULL.
1033
+ """
1034
+ cdef Py_ssize_t count = 0, i, c_tag_len
1035
+ cdef bytes ns, tag
1036
+ cdef const_xmlChar* c_tag
1037
+
1038
+ for ns, tag in ns_tags:
1039
+ if tag is None:
1040
+ c_tag = <const_xmlChar*> NULL
1041
+ else:
1042
+ c_tag_len = len(tag)
1043
+ if c_tag_len > limits.INT_MAX:
1044
+ # too long, not in the dict => not in the document
1045
+ continue
1046
+ elif force_into_dict:
1047
+ c_tag = tree.xmlDictLookup(c_doc.dict, _xcstr(tag), <int> c_tag_len)
1048
+ if c_tag is NULL:
1049
+ # clean up before raising the error
1050
+ for i in xrange(count):
1051
+ cpython.ref.Py_XDECREF(c_ns_tags[i].href)
1052
+ raise MemoryError()
1053
+ else:
1054
+ c_tag = tree.xmlDictExists(c_doc.dict, _xcstr(tag), <int> c_tag_len)
1055
+ if c_tag is NULL:
1056
+ # not in the dict => not in the document
1057
+ continue
1058
+
1059
+ c_ns_tags[count].c_name = c_tag
1060
+ if ns is None:
1061
+ c_ns_tags[count].href = NULL
1062
+ else:
1063
+ cpython.ref.Py_INCREF(ns) # keep an owned reference!
1064
+ c_ns_tags[count].href = <python.PyObject*>ns
1065
+ count += 1
1066
+ return count
1067
+
1068
+ cdef int _removeNode(_Document doc, xmlNode* c_node) except -1:
1069
+ """Unlink and free a node and subnodes if possible. Otherwise, make sure
1070
+ it's self-contained.
1071
+ """
1072
+ cdef xmlNode* c_next
1073
+ c_next = c_node.next
1074
+ tree.xmlUnlinkNode(c_node)
1075
+ _moveTail(c_next, c_node)
1076
+ if not attemptDeallocation(c_node):
1077
+ # make namespaces absolute
1078
+ moveNodeToDocument(doc, c_node.doc, c_node)
1079
+ return 0
1080
+
1081
+ cdef int _removeSiblings(xmlNode* c_element, tree.xmlElementType node_type, bint with_tail) except -1:
1082
+ cdef xmlNode* c_node
1083
+ cdef xmlNode* c_next
1084
+ c_node = c_element.next
1085
+ while c_node is not NULL:
1086
+ c_next = _nextElement(c_node)
1087
+ if c_node.type == node_type:
1088
+ if with_tail:
1089
+ _removeText(c_node.next)
1090
+ tree.xmlUnlinkNode(c_node)
1091
+ attemptDeallocation(c_node)
1092
+ c_node = c_next
1093
+ c_node = c_element.prev
1094
+ while c_node is not NULL:
1095
+ c_next = _previousElement(c_node)
1096
+ if c_node.type == node_type:
1097
+ if with_tail:
1098
+ _removeText(c_node.next)
1099
+ tree.xmlUnlinkNode(c_node)
1100
+ attemptDeallocation(c_node)
1101
+ c_node = c_next
1102
+ return 0
1103
+
1104
+ cdef void _moveTail(xmlNode* c_tail, xmlNode* c_target) noexcept:
1105
+ cdef xmlNode* c_next
1106
+ # tail support: look for any text nodes trailing this node and
1107
+ # move them too
1108
+ c_tail = _textNodeOrSkip(c_tail)
1109
+ while c_tail is not NULL:
1110
+ c_next = _textNodeOrSkip(c_tail.next)
1111
+ c_target = tree.xmlAddNextSibling(c_target, c_tail)
1112
+ c_tail = c_next
1113
+
1114
+ cdef int _copyTail(xmlNode* c_tail, xmlNode* c_target) except -1:
1115
+ cdef xmlNode* c_new_tail
1116
+ # tail copying support: look for any text nodes trailing this node and
1117
+ # copy it to the target node
1118
+ c_tail = _textNodeOrSkip(c_tail)
1119
+ while c_tail is not NULL:
1120
+ if c_target.doc is not c_tail.doc:
1121
+ c_new_tail = tree.xmlDocCopyNode(c_tail, c_target.doc, 0)
1122
+ else:
1123
+ c_new_tail = tree.xmlCopyNode(c_tail, 0)
1124
+ if c_new_tail is NULL:
1125
+ raise MemoryError()
1126
+ c_target = tree.xmlAddNextSibling(c_target, c_new_tail)
1127
+ c_tail = _textNodeOrSkip(c_tail.next)
1128
+ return 0
1129
+
1130
+ cdef int _copyNonElementSiblings(xmlNode* c_node, xmlNode* c_target) except -1:
1131
+ cdef xmlNode* c_copy
1132
+ cdef xmlNode* c_sibling = c_node
1133
+ while c_sibling.prev != NULL and \
1134
+ (c_sibling.prev.type == tree.XML_PI_NODE or
1135
+ c_sibling.prev.type == tree.XML_COMMENT_NODE or
1136
+ c_sibling.prev.type == tree.XML_DTD_NODE):
1137
+ c_sibling = c_sibling.prev
1138
+ while c_sibling != c_node:
1139
+ if c_sibling.type == tree.XML_DTD_NODE:
1140
+ c_copy = <xmlNode*>_copyDtd(<tree.xmlDtd*>c_sibling)
1141
+ if c_sibling == <xmlNode*>c_node.doc.intSubset:
1142
+ c_target.doc.intSubset = <tree.xmlDtd*>c_copy
1143
+ else: # c_sibling == c_node.doc.extSubset
1144
+ c_target.doc.extSubset = <tree.xmlDtd*>c_copy
1145
+ else:
1146
+ c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1)
1147
+ if c_copy is NULL:
1148
+ raise MemoryError()
1149
+ tree.xmlAddPrevSibling(c_target, c_copy)
1150
+ c_sibling = c_sibling.next
1151
+ while c_sibling.next != NULL and \
1152
+ (c_sibling.next.type == tree.XML_PI_NODE or
1153
+ c_sibling.next.type == tree.XML_COMMENT_NODE):
1154
+ c_sibling = c_sibling.next
1155
+ c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1)
1156
+ if c_copy is NULL:
1157
+ raise MemoryError()
1158
+ tree.xmlAddNextSibling(c_target, c_copy)
1159
+
1160
+ cdef int _deleteSlice(_Document doc, xmlNode* c_node,
1161
+ Py_ssize_t count, Py_ssize_t step) except -1:
1162
+ """Delete slice, ``count`` items starting with ``c_node`` with a step
1163
+ width of ``step``.
1164
+ """
1165
+ cdef xmlNode* c_next
1166
+ cdef Py_ssize_t c, i
1167
+ cdef _node_to_node_function next_element
1168
+ if c_node is NULL:
1169
+ return 0
1170
+ if step > 0:
1171
+ next_element = _nextElement
1172
+ else:
1173
+ step = -step
1174
+ next_element = _previousElement
1175
+ # now start deleting nodes
1176
+ c = 0
1177
+ c_next = c_node
1178
+ while c_node is not NULL and c < count:
1179
+ for i in range(step):
1180
+ c_next = next_element(c_next)
1181
+ if c_next is NULL:
1182
+ break
1183
+ _removeNode(doc, c_node)
1184
+ c += 1
1185
+ c_node = c_next
1186
+ return 0
1187
+
1188
+ cdef int _replaceSlice(_Element parent, xmlNode* c_node,
1189
+ Py_ssize_t slicelength, Py_ssize_t step,
1190
+ bint left_to_right, elements) except -1:
1191
+ """Replace the slice of ``count`` elements starting at ``c_node`` with
1192
+ positive step width ``step`` by the Elements in ``elements``. The
1193
+ direction is given by the boolean argument ``left_to_right``.
1194
+
1195
+ ``c_node`` may be NULL to indicate the end of the children list.
1196
+ """
1197
+ cdef xmlNode* c_orig_neighbour
1198
+ cdef xmlNode* c_next
1199
+ cdef xmlDoc* c_source_doc
1200
+ cdef _Element element
1201
+ cdef Py_ssize_t seqlength, i, c
1202
+ cdef _node_to_node_function next_element
1203
+ assert step > 0
1204
+ if left_to_right:
1205
+ next_element = _nextElement
1206
+ else:
1207
+ next_element = _previousElement
1208
+
1209
+ if not isinstance(elements, (list, tuple)):
1210
+ elements = list(elements)
1211
+
1212
+ if step != 1 or not left_to_right:
1213
+ # *replacing* children stepwise with list => check size!
1214
+ seqlength = len(elements)
1215
+ if seqlength != slicelength:
1216
+ raise ValueError, f"attempt to assign sequence of size {seqlength} " \
1217
+ f"to extended slice of size {slicelength}"
1218
+
1219
+ if c_node is NULL:
1220
+ # no children yet => add all elements straight away
1221
+ if left_to_right:
1222
+ for element in elements:
1223
+ assert element is not None, "Node must not be None"
1224
+ _appendChild(parent, element)
1225
+ else:
1226
+ for element in elements:
1227
+ assert element is not None, "Node must not be None"
1228
+ _prependChild(parent, element)
1229
+ return 0
1230
+
1231
+ # remove the elements first as some might be re-added
1232
+ if left_to_right:
1233
+ # L->R, remember left neighbour
1234
+ c_orig_neighbour = _previousElement(c_node)
1235
+ else:
1236
+ # R->L, remember right neighbour
1237
+ c_orig_neighbour = _nextElement(c_node)
1238
+
1239
+ # We remove the original slice elements one by one. Since we hold
1240
+ # a Python reference to all elements that we will insert, it is
1241
+ # safe to let _removeNode() try (and fail) to free them even if
1242
+ # the element itself or one of its descendents will be reinserted.
1243
+ c = 0
1244
+ c_next = c_node
1245
+ while c_node is not NULL and c < slicelength:
1246
+ for i in range(step):
1247
+ c_next = next_element(c_next)
1248
+ if c_next is NULL:
1249
+ break
1250
+ _removeNode(parent._doc, c_node)
1251
+ c += 1
1252
+ c_node = c_next
1253
+
1254
+ # make sure each element is inserted only once
1255
+ elements = iter(elements)
1256
+
1257
+ # find the first node right of the new insertion point
1258
+ if left_to_right:
1259
+ if c_orig_neighbour is not NULL:
1260
+ c_node = next_element(c_orig_neighbour)
1261
+ else:
1262
+ # before the first element
1263
+ c_node = _findChildForwards(parent._c_node, 0)
1264
+ elif c_orig_neighbour is NULL:
1265
+ # at the end, but reversed stepping
1266
+ # append one element and go to the next insertion point
1267
+ for element in elements:
1268
+ assert element is not None, "Node must not be None"
1269
+ _appendChild(parent, element)
1270
+ c_node = element._c_node
1271
+ if slicelength > 0:
1272
+ slicelength -= 1
1273
+ for i in range(1, step):
1274
+ c_node = next_element(c_node)
1275
+ if c_node is NULL:
1276
+ break
1277
+ break
1278
+ else:
1279
+ c_node = c_orig_neighbour
1280
+
1281
+ if left_to_right:
1282
+ # adjust step size after removing slice as we are not stepping
1283
+ # over the newly inserted elements
1284
+ step -= 1
1285
+
1286
+ # now insert elements where we removed them
1287
+ if c_node is not NULL:
1288
+ for element in elements:
1289
+ assert element is not None, "Node must not be None"
1290
+ _assertValidNode(element)
1291
+ # move element and tail over
1292
+ c_source_doc = element._c_node.doc
1293
+ c_next = element._c_node.next
1294
+ tree.xmlAddPrevSibling(c_node, element._c_node)
1295
+ _moveTail(c_next, element._c_node)
1296
+
1297
+ # integrate element into new document
1298
+ moveNodeToDocument(parent._doc, c_source_doc, element._c_node)
1299
+
1300
+ # stop at the end of the slice
1301
+ if slicelength > 0:
1302
+ slicelength -= 1
1303
+ for i in range(step):
1304
+ c_node = next_element(c_node)
1305
+ if c_node is NULL:
1306
+ break
1307
+ if c_node is NULL:
1308
+ break
1309
+ else:
1310
+ # everything inserted
1311
+ return 0
1312
+
1313
+ # append the remaining elements at the respective end
1314
+ if left_to_right:
1315
+ for element in elements:
1316
+ assert element is not None, "Node must not be None"
1317
+ _assertValidNode(element)
1318
+ _appendChild(parent, element)
1319
+ else:
1320
+ for element in elements:
1321
+ assert element is not None, "Node must not be None"
1322
+ _assertValidNode(element)
1323
+ _prependChild(parent, element)
1324
+
1325
+ return 0
1326
+
1327
+
1328
+ cdef int _linkChild(xmlNode* c_parent, xmlNode* c_node) except -1:
1329
+ """Adaptation of 'xmlAddChild()' that deep-fix the document links iteratively.
1330
+ """
1331
+ assert _isElement(c_node)
1332
+ c_node.parent = c_parent
1333
+ if c_parent.children is NULL:
1334
+ c_parent.children = c_parent.last = c_node
1335
+ else:
1336
+ c_node.prev = c_parent.last
1337
+ c_parent.last.next = c_node
1338
+ c_parent.last = c_node
1339
+
1340
+ _setTreeDoc(c_node, c_parent.doc)
1341
+ return 0
1342
+
1343
+
1344
+ cdef int _appendChild(_Element parent, _Element child) except -1:
1345
+ """Append a new child to a parent element.
1346
+ """
1347
+ c_node = child._c_node
1348
+ c_source_doc = c_node.doc
1349
+ # prevent cycles
1350
+ if _isAncestorOrSame(c_node, parent._c_node):
1351
+ raise ValueError("cannot append parent to itself")
1352
+ # store possible text node
1353
+ c_next = c_node.next
1354
+ # move node itself
1355
+ tree.xmlUnlinkNode(c_node)
1356
+ # do not call xmlAddChild() here since it would deep-traverse the tree
1357
+ _linkChild(parent._c_node, c_node)
1358
+ _moveTail(c_next, c_node)
1359
+ # uh oh, elements may be pointing to different doc when
1360
+ # parent element has moved; change them too..
1361
+ moveNodeToDocument(parent._doc, c_source_doc, c_node)
1362
+ return 0
1363
+
1364
+ cdef int _prependChild(_Element parent, _Element child) except -1:
1365
+ """Prepend a new child to a parent element.
1366
+ """
1367
+ c_node = child._c_node
1368
+ c_source_doc = c_node.doc
1369
+ # prevent cycles
1370
+ if _isAncestorOrSame(c_node, parent._c_node):
1371
+ raise ValueError("cannot append parent to itself")
1372
+ # store possible text node
1373
+ c_next = c_node.next
1374
+ # move node itself
1375
+ c_child = _findChildForwards(parent._c_node, 0)
1376
+ if c_child is NULL:
1377
+ tree.xmlUnlinkNode(c_node)
1378
+ # do not call xmlAddChild() here since it would deep-traverse the tree
1379
+ _linkChild(parent._c_node, c_node)
1380
+ else:
1381
+ tree.xmlAddPrevSibling(c_child, c_node)
1382
+ _moveTail(c_next, c_node)
1383
+ # uh oh, elements may be pointing to different doc when
1384
+ # parent element has moved; change them too..
1385
+ moveNodeToDocument(parent._doc, c_source_doc, c_node)
1386
+ return 0
1387
+
1388
+ cdef int _appendSibling(_Element element, _Element sibling) except -1:
1389
+ """Add a new sibling behind an element.
1390
+ """
1391
+ return _addSibling(element, sibling, as_next=True)
1392
+
1393
+ cdef int _prependSibling(_Element element, _Element sibling) except -1:
1394
+ """Add a new sibling before an element.
1395
+ """
1396
+ return _addSibling(element, sibling, as_next=False)
1397
+
1398
+ cdef int _addSibling(_Element element, _Element sibling, bint as_next) except -1:
1399
+ c_node = sibling._c_node
1400
+ c_source_doc = c_node.doc
1401
+ # prevent cycles
1402
+ if _isAncestorOrSame(c_node, element._c_node):
1403
+ if element._c_node is c_node:
1404
+ return 0 # nothing to do
1405
+ raise ValueError("cannot add ancestor as sibling, please break cycle first")
1406
+ # store possible text node
1407
+ c_next = c_node.next
1408
+ # move node itself
1409
+ if as_next:
1410
+ # must insert after any tail text
1411
+ c_next_node = _nextElement(element._c_node)
1412
+ if c_next_node is NULL:
1413
+ c_next_node = element._c_node
1414
+ while c_next_node.next:
1415
+ c_next_node = c_next_node.next
1416
+ tree.xmlAddNextSibling(c_next_node, c_node)
1417
+ else:
1418
+ tree.xmlAddPrevSibling(c_next_node, c_node)
1419
+ else:
1420
+ tree.xmlAddPrevSibling(element._c_node, c_node)
1421
+ _moveTail(c_next, c_node)
1422
+ # uh oh, elements may be pointing to different doc when
1423
+ # parent element has moved; change them too..
1424
+ moveNodeToDocument(element._doc, c_source_doc, c_node)
1425
+ return 0
1426
+
1427
+ cdef inline bint isutf8(const_xmlChar* s) noexcept:
1428
+ cdef xmlChar c = s[0]
1429
+ while c != c'\0':
1430
+ if c & 0x80:
1431
+ return True
1432
+ s += 1
1433
+ c = s[0]
1434
+ return False
1435
+
1436
+ cdef bint isutf8l(const_xmlChar* s, size_t length) noexcept:
1437
+ """
1438
+ Search for non-ASCII characters in the string, knowing its length in advance.
1439
+ """
1440
+ cdef unsigned int i
1441
+ cdef unsigned long non_ascii_mask
1442
+ cdef const unsigned long *lptr = <const unsigned long*> s
1443
+
1444
+ cdef const unsigned long *end = lptr + length // sizeof(unsigned long)
1445
+ if length >= sizeof(non_ascii_mask):
1446
+ # Build constant 0x80808080... mask (and let the C compiler fold it).
1447
+ non_ascii_mask = 0
1448
+ for i in range(sizeof(non_ascii_mask) // 2):
1449
+ non_ascii_mask = (non_ascii_mask << 16) | 0x8080
1450
+
1451
+ # Advance to long-aligned character before we start reading longs.
1452
+ while (<size_t>s) % sizeof(unsigned long) and s < <const_xmlChar *>end:
1453
+ if s[0] & 0x80:
1454
+ return True
1455
+ s += 1
1456
+
1457
+ # Read one long at a time
1458
+ lptr = <const unsigned long*> s
1459
+ while lptr < end:
1460
+ if lptr[0] & non_ascii_mask:
1461
+ return True
1462
+ lptr += 1
1463
+ s = <const_xmlChar *>lptr
1464
+
1465
+ while s < (<const_xmlChar *>end + length % sizeof(unsigned long)):
1466
+ if s[0] & 0x80:
1467
+ return True
1468
+ s += 1
1469
+
1470
+ return False
1471
+
1472
+ cdef int _is_valid_xml_ascii(bytes pystring) except -1:
1473
+ """Check if a string is XML ascii content."""
1474
+ cdef signed char ch
1475
+ # When ch is a *signed* char, non-ascii characters are negative integers
1476
+ # and xmlIsChar_ch does not accept them.
1477
+ for ch in pystring:
1478
+ if not tree.xmlIsChar_ch(ch):
1479
+ return 0
1480
+ return 1
1481
+
1482
+ cdef bint _is_valid_xml_utf8(bytes pystring) except -1:
1483
+ """Check if a string is like valid UTF-8 XML content."""
1484
+ cdef const_xmlChar* s = _xcstr(pystring)
1485
+ cdef const_xmlChar* c_end = s + len(pystring)
1486
+ cdef unsigned long next3 = 0
1487
+ if s < c_end - 2:
1488
+ next3 = (s[0] << 8) | (s[1])
1489
+
1490
+ while s < c_end - 2:
1491
+ next3 = 0x00ffffff & ((next3 << 8) | s[2])
1492
+ if s[0] & 0x80:
1493
+ # 0xefbfbe and 0xefbfbf are utf-8 encodings of
1494
+ # forbidden characters \ufffe and \uffff
1495
+ if next3 == 0x00efbfbe or next3 == 0x00efbfbf:
1496
+ return 0
1497
+ # 0xeda080 and 0xedbfbf are utf-8 encodings of
1498
+ # \ud800 and \udfff. Anything between them (inclusive)
1499
+ # is forbidden, because they are surrogate blocks in utf-16.
1500
+ if 0x00eda080 <= next3 <= 0x00edbfbf:
1501
+ return 0
1502
+ elif not tree.xmlIsChar_ch(s[0]):
1503
+ return 0 # invalid ascii char
1504
+ s += 1
1505
+
1506
+ while s < c_end:
1507
+ if not s[0] & 0x80 and not tree.xmlIsChar_ch(s[0]):
1508
+ return 0 # invalid ascii char
1509
+ s += 1
1510
+
1511
+ return 1
1512
+
1513
+ cdef inline unicode funicodeOrNone(const_xmlChar* s):
1514
+ return funicode(s) if s is not NULL else None
1515
+
1516
+ cdef inline unicode funicodeOrEmpty(const_xmlChar* s):
1517
+ return funicode(s) if s is not NULL else ''
1518
+
1519
+ cdef unicode funicode(const_xmlChar* s):
1520
+ return s.decode('UTF-8')
1521
+
1522
+ cdef bytes _utf8(object s):
1523
+ """Test if a string is valid user input and encode it to UTF-8.
1524
+ Reject all bytes/unicode input that contains non-XML characters.
1525
+ Reject all bytes input that contains non-ASCII characters.
1526
+ """
1527
+ cdef int valid
1528
+ cdef bytes utf8_string
1529
+ if isinstance(s, unicode):
1530
+ utf8_string = (<unicode>s).encode('utf8')
1531
+ valid = _is_valid_xml_utf8(utf8_string)
1532
+ elif isinstance(s, (bytes, bytearray)):
1533
+ utf8_string = s if type(s) is bytes else bytes(s)
1534
+ valid = _is_valid_xml_ascii(utf8_string)
1535
+ else:
1536
+ raise TypeError("Argument must be bytes or unicode, got '%.200s'" % type(s).__name__)
1537
+ if not valid:
1538
+ raise ValueError(
1539
+ "All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters")
1540
+ return utf8_string
1541
+
1542
+
1543
+ cdef bytes _utf8orNone(object s):
1544
+ return _utf8(s) if s is not None else None
1545
+
1546
+
1547
+ cdef enum:
1548
+ NO_FILE_PATH = 0
1549
+ ABS_UNIX_FILE_PATH = 1
1550
+ ABS_WIN_FILE_PATH = 2
1551
+ REL_FILE_PATH = 3
1552
+
1553
+
1554
+ cdef bint _isFilePath(const_xmlChar* c_path) noexcept:
1555
+ "simple heuristic to see if a path is a filename"
1556
+ cdef xmlChar c
1557
+ # test if it looks like an absolute Unix path or a Windows network path
1558
+ if c_path[0] == c'/':
1559
+ return ABS_UNIX_FILE_PATH
1560
+
1561
+ # test if it looks like an absolute Windows path or URL
1562
+ if c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z':
1563
+ c_path += 1
1564
+ if c_path[0] == c':' and c_path[1] in b'\0\\':
1565
+ return ABS_WIN_FILE_PATH # C: or C:\...
1566
+
1567
+ # test if it looks like a URL with scheme://
1568
+ while c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z':
1569
+ c_path += 1
1570
+ if c_path[0] == c':' and c_path[1] == c'/' and c_path[2] == c'/':
1571
+ return NO_FILE_PATH
1572
+
1573
+ # assume it's a relative path
1574
+ return REL_FILE_PATH
1575
+
1576
+
1577
+ cdef object _getFSPathOrObject(object obj):
1578
+ """
1579
+ Get the __fspath__ attribute of an object if it exists.
1580
+ Otherwise, the original object is returned.
1581
+ """
1582
+ if _isString(obj):
1583
+ return obj
1584
+ try:
1585
+ return python.PyOS_FSPath(obj)
1586
+ except TypeError:
1587
+ return obj
1588
+
1589
+
1590
+ cdef object _encodeFilename(object filename):
1591
+ """Make sure a filename is 8-bit encoded (or None).
1592
+ """
1593
+ if filename is None:
1594
+ return None
1595
+ elif isinstance(filename, bytes):
1596
+ return filename
1597
+ elif isinstance(filename, unicode):
1598
+ filename8 = (<unicode>filename).encode('utf8')
1599
+ if _isFilePath(<unsigned char*>filename8):
1600
+ try:
1601
+ return python.PyUnicode_AsEncodedString(
1602
+ filename, _C_FILENAME_ENCODING, NULL)
1603
+ except UnicodeEncodeError:
1604
+ pass
1605
+ return filename8
1606
+ else:
1607
+ raise TypeError("Argument must be string or unicode.")
1608
+
1609
+ cdef object _decodeFilename(const_xmlChar* c_path):
1610
+ """Make the filename a unicode string if we are in Py3.
1611
+ """
1612
+ return _decodeFilenameWithLength(c_path, tree.xmlStrlen(c_path))
1613
+
1614
+ cdef object _decodeFilenameWithLength(const_xmlChar* c_path, size_t c_len):
1615
+ """Make the filename a unicode string if we are in Py3.
1616
+ """
1617
+ if _isFilePath(c_path):
1618
+ try:
1619
+ return python.PyUnicode_Decode(
1620
+ <const_char*>c_path, c_len, _C_FILENAME_ENCODING, NULL)
1621
+ except UnicodeDecodeError:
1622
+ pass
1623
+ try:
1624
+ return (<unsigned char*>c_path)[:c_len].decode('UTF-8')
1625
+ except UnicodeDecodeError:
1626
+ # this is a stupid fallback, but it might still work...
1627
+ return (<unsigned char*>c_path)[:c_len].decode('latin-1', 'replace')
1628
+
1629
+ cdef object _encodeFilenameUTF8(object filename):
1630
+ """Recode filename as UTF-8. Tries ASCII, local filesystem encoding and
1631
+ UTF-8 as source encoding.
1632
+ """
1633
+ cdef char* c_filename
1634
+ if filename is None:
1635
+ return None
1636
+ elif isinstance(filename, bytes):
1637
+ if not isutf8l(<bytes>filename, len(<bytes>filename)):
1638
+ # plain ASCII!
1639
+ return filename
1640
+ c_filename = _cstr(<bytes>filename)
1641
+ try:
1642
+ # try to decode with default encoding
1643
+ filename = python.PyUnicode_Decode(
1644
+ c_filename, len(<bytes>filename),
1645
+ _C_FILENAME_ENCODING, NULL)
1646
+ except UnicodeDecodeError as decode_exc:
1647
+ try:
1648
+ # try if it's proper UTF-8
1649
+ (<bytes>filename).decode('utf8')
1650
+ return filename
1651
+ except UnicodeDecodeError:
1652
+ raise decode_exc # otherwise re-raise original exception
1653
+ if isinstance(filename, unicode):
1654
+ return (<unicode>filename).encode('utf8')
1655
+ else:
1656
+ raise TypeError("Argument must be string or unicode.")
1657
+
1658
+ cdef tuple _getNsTag(tag):
1659
+ """Given a tag, find namespace URI and tag name.
1660
+ Return None for NS uri if no namespace URI provided.
1661
+ """
1662
+ return __getNsTag(tag, 0)
1663
+
1664
+ cdef tuple _getNsTagWithEmptyNs(tag):
1665
+ """Given a tag, find namespace URI and tag name. Return None for NS uri
1666
+ if no namespace URI provided, or the empty string if namespace
1667
+ part is '{}'.
1668
+ """
1669
+ return __getNsTag(tag, 1)
1670
+
1671
+ cdef tuple __getNsTag(tag, bint empty_ns):
1672
+ cdef char* c_tag
1673
+ cdef char* c_ns_end
1674
+ cdef Py_ssize_t taglen
1675
+ cdef Py_ssize_t nslen
1676
+ cdef bytes ns = None
1677
+ # _isString() is much faster than isinstance()
1678
+ if not _isString(tag) and isinstance(tag, QName):
1679
+ tag = (<QName>tag).text
1680
+ tag = _utf8(tag)
1681
+ c_tag = _cstr(tag)
1682
+ if c_tag[0] == c'{':
1683
+ c_tag += 1
1684
+ c_ns_end = cstring_h.strchr(c_tag, c'}')
1685
+ if c_ns_end is NULL:
1686
+ raise ValueError, "Invalid tag name"
1687
+ nslen = c_ns_end - c_tag
1688
+ taglen = python.PyBytes_GET_SIZE(tag) - nslen - 2
1689
+ if taglen == 0:
1690
+ raise ValueError, "Empty tag name"
1691
+ if nslen > 0:
1692
+ ns = <bytes>c_tag[:nslen]
1693
+ elif empty_ns:
1694
+ ns = b''
1695
+ tag = <bytes>c_ns_end[1:taglen+1]
1696
+ elif python.PyBytes_GET_SIZE(tag) == 0:
1697
+ raise ValueError, "Empty tag name"
1698
+ return ns, tag
1699
+
1700
+ cdef inline int _pyXmlNameIsValid(name_utf8):
1701
+ return _xmlNameIsValid(_xcstr(name_utf8)) and b':' not in name_utf8
1702
+
1703
+ cdef inline int _pyHtmlNameIsValid(name_utf8):
1704
+ return _htmlNameIsValid(_xcstr(name_utf8))
1705
+
1706
+ cdef inline int _xmlNameIsValid(const_xmlChar* c_name) noexcept:
1707
+ return tree.xmlValidateNameValue(c_name)
1708
+
1709
+ cdef int _htmlNameIsValid(const_xmlChar* c_name) noexcept:
1710
+ if c_name is NULL or c_name[0] == c'\0':
1711
+ return 0
1712
+ while c_name[0] != c'\0':
1713
+ if c_name[0] in b'&<>/"\'\t\n\x0B\x0C\r ':
1714
+ return 0
1715
+ c_name += 1
1716
+ return 1
1717
+
1718
+ cdef bint _characterReferenceIsValid(const_xmlChar* c_name) noexcept:
1719
+ cdef bint is_hex
1720
+ if c_name[0] == c'x':
1721
+ c_name += 1
1722
+ is_hex = 1
1723
+ else:
1724
+ is_hex = 0
1725
+ if c_name[0] == c'\0':
1726
+ return 0
1727
+ while c_name[0] != c'\0':
1728
+ if c_name[0] < c'0' or c_name[0] > c'9':
1729
+ if not is_hex:
1730
+ return 0
1731
+ if not (c'a' <= c_name[0] <= c'f'):
1732
+ if not (c'A' <= c_name[0] <= c'F'):
1733
+ return 0
1734
+ c_name += 1
1735
+ return 1
1736
+
1737
+ cdef int _tagValidOrRaise(tag_utf) except -1:
1738
+ if not _pyXmlNameIsValid(tag_utf):
1739
+ raise ValueError(f"Invalid tag name {(<bytes>tag_utf).decode('utf8')!r}")
1740
+ return 0
1741
+
1742
+ cdef int _htmlTagValidOrRaise(tag_utf) except -1:
1743
+ if not _pyHtmlNameIsValid(tag_utf):
1744
+ raise ValueError(f"Invalid HTML tag name {(<bytes>tag_utf).decode('utf8')!r}")
1745
+ return 0
1746
+
1747
+ cdef int _attributeValidOrRaise(name_utf) except -1:
1748
+ if not _pyXmlNameIsValid(name_utf):
1749
+ raise ValueError(f"Invalid attribute name {(<bytes>name_utf).decode('utf8')!r}")
1750
+ return 0
1751
+
1752
+ cdef int _prefixValidOrRaise(tag_utf) except -1:
1753
+ if not _pyXmlNameIsValid(tag_utf):
1754
+ raise ValueError(f"Invalid namespace prefix {(<bytes>tag_utf).decode('utf8')!r}")
1755
+ return 0
1756
+
1757
+ cdef int _uriValidOrRaise(uri_utf) except -1:
1758
+ cdef uri.xmlURI* c_uri = uri.xmlParseURI(_cstr(uri_utf))
1759
+ if c_uri is NULL:
1760
+ raise ValueError(f"Invalid namespace URI {(<bytes>uri_utf).decode('utf8')!r}")
1761
+ uri.xmlFreeURI(c_uri)
1762
+ return 0
1763
+
1764
+ cdef inline unicode _namespacedName(xmlNode* c_node):
1765
+ return _namespacedNameFromNsName(_getNs(c_node), c_node.name)
1766
+
1767
+
1768
+ cdef unicode _namespacedNameFromNsName(const_xmlChar* c_href, const_xmlChar* c_name):
1769
+ name = funicode(c_name)
1770
+ if c_href is NULL:
1771
+ return name
1772
+ href = funicode(c_href)
1773
+ return f"{{{href}}}{name}"
1774
+
1775
+
1776
+ cdef _getFilenameForFile(source):
1777
+ """Given a Python File or Gzip object, give filename back.
1778
+
1779
+ Returns None if not a file object.
1780
+ """
1781
+ # urllib2 provides a geturl() method
1782
+ try:
1783
+ return source.geturl()
1784
+ except:
1785
+ pass
1786
+ # file instances have a name attribute
1787
+ try:
1788
+ filename = source.name
1789
+ if _isString(filename):
1790
+ return os_path_abspath(filename)
1791
+ except:
1792
+ pass
1793
+ # gzip file instances have a filename attribute (before Py3k)
1794
+ try:
1795
+ filename = source.filename
1796
+ if _isString(filename):
1797
+ return os_path_abspath(filename)
1798
+ except:
1799
+ pass
1800
+ # can't determine filename
1801
+ return None