lxml 5.3.2__cp310-cp310-win32.win32.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 (175) hide show
  1. lxml/ElementInclude.py +244 -0
  2. lxml/__init__.py +22 -0
  3. lxml/_elementpath.cp310-win32.pyd +0 -0
  4. lxml/_elementpath.py +341 -0
  5. lxml/apihelpers.pxi +1793 -0
  6. lxml/builder.cp310-win32.pyd +0 -0
  7. lxml/builder.py +232 -0
  8. lxml/classlookup.pxi +580 -0
  9. lxml/cleanup.pxi +215 -0
  10. lxml/cssselect.py +101 -0
  11. lxml/debug.pxi +90 -0
  12. lxml/docloader.pxi +178 -0
  13. lxml/doctestcompare.py +488 -0
  14. lxml/dtd.pxi +479 -0
  15. lxml/etree.cp310-win32.pyd +0 -0
  16. lxml/etree.h +248 -0
  17. lxml/etree.pyx +3732 -0
  18. lxml/etree_api.h +195 -0
  19. lxml/extensions.pxi +833 -0
  20. lxml/html/ElementSoup.py +10 -0
  21. lxml/html/__init__.py +1923 -0
  22. lxml/html/_diffcommand.py +86 -0
  23. lxml/html/_html5builder.py +100 -0
  24. lxml/html/_setmixin.py +56 -0
  25. lxml/html/builder.py +133 -0
  26. lxml/html/clean.py +21 -0
  27. lxml/html/defs.py +135 -0
  28. lxml/html/diff.cp310-win32.pyd +0 -0
  29. lxml/html/diff.py +878 -0
  30. lxml/html/formfill.py +299 -0
  31. lxml/html/html5parser.py +260 -0
  32. lxml/html/soupparser.py +314 -0
  33. lxml/html/usedoctest.py +13 -0
  34. lxml/includes/__init__.pxd +0 -0
  35. lxml/includes/__init__.py +0 -0
  36. lxml/includes/c14n.pxd +25 -0
  37. lxml/includes/config.pxd +3 -0
  38. lxml/includes/dtdvalid.pxd +18 -0
  39. lxml/includes/etree_defs.h +379 -0
  40. lxml/includes/etreepublic.pxd +237 -0
  41. lxml/includes/extlibs/__init__.py +0 -0
  42. lxml/includes/extlibs/zconf.h +543 -0
  43. lxml/includes/extlibs/zlib.h +1938 -0
  44. lxml/includes/htmlparser.pxd +56 -0
  45. lxml/includes/libexslt/__init__.py +0 -0
  46. lxml/includes/libexslt/exslt.h +108 -0
  47. lxml/includes/libexslt/exsltconfig.h +70 -0
  48. lxml/includes/libexslt/exsltexports.h +63 -0
  49. lxml/includes/libexslt/libexslt.h +29 -0
  50. lxml/includes/libxml/HTMLparser.h +320 -0
  51. lxml/includes/libxml/HTMLtree.h +147 -0
  52. lxml/includes/libxml/SAX.h +204 -0
  53. lxml/includes/libxml/SAX2.h +173 -0
  54. lxml/includes/libxml/__init__.py +0 -0
  55. lxml/includes/libxml/c14n.h +128 -0
  56. lxml/includes/libxml/catalog.h +182 -0
  57. lxml/includes/libxml/chvalid.h +230 -0
  58. lxml/includes/libxml/debugXML.h +217 -0
  59. lxml/includes/libxml/dict.h +81 -0
  60. lxml/includes/libxml/encoding.h +233 -0
  61. lxml/includes/libxml/entities.h +151 -0
  62. lxml/includes/libxml/globals.h +529 -0
  63. lxml/includes/libxml/hash.h +236 -0
  64. lxml/includes/libxml/list.h +137 -0
  65. lxml/includes/libxml/nanoftp.h +186 -0
  66. lxml/includes/libxml/nanohttp.h +81 -0
  67. lxml/includes/libxml/parser.h +1265 -0
  68. lxml/includes/libxml/parserInternals.h +662 -0
  69. lxml/includes/libxml/pattern.h +100 -0
  70. lxml/includes/libxml/relaxng.h +218 -0
  71. lxml/includes/libxml/schemasInternals.h +958 -0
  72. lxml/includes/libxml/schematron.h +142 -0
  73. lxml/includes/libxml/threads.h +94 -0
  74. lxml/includes/libxml/tree.h +1314 -0
  75. lxml/includes/libxml/uri.h +94 -0
  76. lxml/includes/libxml/valid.h +448 -0
  77. lxml/includes/libxml/xinclude.h +129 -0
  78. lxml/includes/libxml/xlink.h +189 -0
  79. lxml/includes/libxml/xmlIO.h +369 -0
  80. lxml/includes/libxml/xmlautomata.h +146 -0
  81. lxml/includes/libxml/xmlerror.h +919 -0
  82. lxml/includes/libxml/xmlexports.h +50 -0
  83. lxml/includes/libxml/xmlmemory.h +228 -0
  84. lxml/includes/libxml/xmlmodule.h +57 -0
  85. lxml/includes/libxml/xmlreader.h +428 -0
  86. lxml/includes/libxml/xmlregexp.h +222 -0
  87. lxml/includes/libxml/xmlsave.h +88 -0
  88. lxml/includes/libxml/xmlschemas.h +246 -0
  89. lxml/includes/libxml/xmlschemastypes.h +152 -0
  90. lxml/includes/libxml/xmlstring.h +140 -0
  91. lxml/includes/libxml/xmlunicode.h +202 -0
  92. lxml/includes/libxml/xmlversion.h +526 -0
  93. lxml/includes/libxml/xmlwriter.h +488 -0
  94. lxml/includes/libxml/xpath.h +575 -0
  95. lxml/includes/libxml/xpathInternals.h +632 -0
  96. lxml/includes/libxml/xpointer.h +137 -0
  97. lxml/includes/libxslt/__init__.py +0 -0
  98. lxml/includes/libxslt/attributes.h +39 -0
  99. lxml/includes/libxslt/documents.h +93 -0
  100. lxml/includes/libxslt/extensions.h +262 -0
  101. lxml/includes/libxslt/extra.h +72 -0
  102. lxml/includes/libxslt/functions.h +78 -0
  103. lxml/includes/libxslt/imports.h +75 -0
  104. lxml/includes/libxslt/keys.h +53 -0
  105. lxml/includes/libxslt/libxslt.h +36 -0
  106. lxml/includes/libxslt/namespaces.h +68 -0
  107. lxml/includes/libxslt/numbersInternals.h +73 -0
  108. lxml/includes/libxslt/preproc.h +43 -0
  109. lxml/includes/libxslt/security.h +104 -0
  110. lxml/includes/libxslt/templates.h +77 -0
  111. lxml/includes/libxslt/transform.h +207 -0
  112. lxml/includes/libxslt/trio.h +216 -0
  113. lxml/includes/libxslt/triodef.h +220 -0
  114. lxml/includes/libxslt/variables.h +118 -0
  115. lxml/includes/libxslt/win32config.h +51 -0
  116. lxml/includes/libxslt/xslt.h +110 -0
  117. lxml/includes/libxslt/xsltInternals.h +1992 -0
  118. lxml/includes/libxslt/xsltconfig.h +179 -0
  119. lxml/includes/libxslt/xsltexports.h +64 -0
  120. lxml/includes/libxslt/xsltlocale.h +44 -0
  121. lxml/includes/libxslt/xsltutils.h +343 -0
  122. lxml/includes/lxml-version.h +3 -0
  123. lxml/includes/relaxng.pxd +64 -0
  124. lxml/includes/schematron.pxd +34 -0
  125. lxml/includes/tree.pxd +494 -0
  126. lxml/includes/uri.pxd +5 -0
  127. lxml/includes/xinclude.pxd +22 -0
  128. lxml/includes/xmlerror.pxd +852 -0
  129. lxml/includes/xmlparser.pxd +265 -0
  130. lxml/includes/xmlschema.pxd +35 -0
  131. lxml/includes/xpath.pxd +136 -0
  132. lxml/includes/xslt.pxd +190 -0
  133. lxml/isoschematron/__init__.py +348 -0
  134. lxml/isoschematron/resources/rng/iso-schematron.rng +709 -0
  135. lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl +75 -0
  136. lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl +77 -0
  137. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl +313 -0
  138. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl +1160 -0
  139. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl +55 -0
  140. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl +1796 -0
  141. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl +588 -0
  142. lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt +84 -0
  143. lxml/iterparse.pxi +438 -0
  144. lxml/lxml.etree.h +248 -0
  145. lxml/lxml.etree_api.h +195 -0
  146. lxml/nsclasses.pxi +281 -0
  147. lxml/objectify.cp310-win32.pyd +0 -0
  148. lxml/objectify.pyx +2145 -0
  149. lxml/objectpath.pxi +332 -0
  150. lxml/parser.pxi +2000 -0
  151. lxml/parsertarget.pxi +180 -0
  152. lxml/proxy.pxi +619 -0
  153. lxml/public-api.pxi +178 -0
  154. lxml/pyclasslookup.py +3 -0
  155. lxml/readonlytree.pxi +565 -0
  156. lxml/relaxng.pxi +165 -0
  157. lxml/sax.cp310-win32.pyd +0 -0
  158. lxml/sax.py +275 -0
  159. lxml/saxparser.pxi +875 -0
  160. lxml/schematron.pxi +168 -0
  161. lxml/serializer.pxi +1781 -0
  162. lxml/usedoctest.py +13 -0
  163. lxml/xinclude.pxi +67 -0
  164. lxml/xmlerror.pxi +1654 -0
  165. lxml/xmlid.pxi +179 -0
  166. lxml/xmlschema.pxi +215 -0
  167. lxml/xpath.pxi +487 -0
  168. lxml/xslt.pxi +950 -0
  169. lxml/xsltext.pxi +242 -0
  170. lxml-5.3.2.dist-info/METADATA +100 -0
  171. lxml-5.3.2.dist-info/RECORD +175 -0
  172. lxml-5.3.2.dist-info/WHEEL +5 -0
  173. lxml-5.3.2.dist-info/licenses/LICENSE.txt +29 -0
  174. lxml-5.3.2.dist-info/licenses/LICENSES.txt +29 -0
  175. lxml-5.3.2.dist-info/top_level.txt +1 -0
lxml/parser.pxi ADDED
@@ -0,0 +1,2000 @@
1
+ # Parsers for XML and HTML
2
+
3
+ from lxml.includes cimport xmlparser
4
+ from lxml.includes cimport htmlparser
5
+
6
+
7
+ class ParseError(LxmlSyntaxError):
8
+ """Syntax error while parsing an XML document.
9
+
10
+ For compatibility with ElementTree 1.3 and later.
11
+ """
12
+ def __init__(self, message, code, line, column, filename=None):
13
+ super(_ParseError, self).__init__(message)
14
+ self.lineno, self.offset = (line, column - 1)
15
+ self.code = code
16
+ self.filename = filename
17
+
18
+ @property
19
+ def position(self):
20
+ return self.lineno, self.offset + 1
21
+
22
+ @position.setter
23
+ def position(self, new_pos):
24
+ self.lineno, column = new_pos
25
+ self.offset = column - 1
26
+
27
+ cdef object _ParseError = ParseError
28
+
29
+
30
+ class XMLSyntaxError(ParseError):
31
+ """Syntax error while parsing an XML document.
32
+ """
33
+
34
+ cdef class ParserError(LxmlError):
35
+ """Internal lxml parser error.
36
+ """
37
+
38
+
39
+ @cython.final
40
+ @cython.internal
41
+ cdef class _ParserDictionaryContext:
42
+ # Global parser context to share the string dictionary.
43
+ #
44
+ # This class is a delegate singleton!
45
+ #
46
+ # It creates _ParserDictionaryContext objects for each thread to keep thread state,
47
+ # but those must never be used directly. Always stick to using the static
48
+ # __GLOBAL_PARSER_CONTEXT as defined below the class.
49
+ #
50
+
51
+ cdef tree.xmlDict* _c_dict
52
+ cdef _BaseParser _default_parser
53
+ cdef list _implied_parser_contexts
54
+
55
+ def __cinit__(self):
56
+ self._c_dict = NULL
57
+ self._implied_parser_contexts = []
58
+
59
+ def __dealloc__(self):
60
+ if self._c_dict is not NULL:
61
+ xmlparser.xmlDictFree(self._c_dict)
62
+
63
+ cdef int initMainParserContext(self) except -1:
64
+ """Put the global context into the thread dictionary of the main
65
+ thread. To be called once and only in the main thread."""
66
+ thread_dict = python.PyThreadState_GetDict()
67
+ if thread_dict is not NULL:
68
+ (<dict>thread_dict)["_ParserDictionaryContext"] = self
69
+
70
+ cdef _ParserDictionaryContext _findThreadParserContext(self):
71
+ "Find (or create) the _ParserDictionaryContext object for the current thread"
72
+ cdef _ParserDictionaryContext context
73
+ thread_dict = python.PyThreadState_GetDict()
74
+ if thread_dict is NULL:
75
+ return self
76
+ d = <dict>thread_dict
77
+ result = python.PyDict_GetItem(d, "_ParserDictionaryContext")
78
+ if result is not NULL:
79
+ return <object>result
80
+ context = <_ParserDictionaryContext>_ParserDictionaryContext.__new__(_ParserDictionaryContext)
81
+ d["_ParserDictionaryContext"] = context
82
+ return context
83
+
84
+ cdef int setDefaultParser(self, _BaseParser parser) except -1:
85
+ "Set the default parser for the current thread"
86
+ cdef _ParserDictionaryContext context
87
+ context = self._findThreadParserContext()
88
+ context._default_parser = parser
89
+
90
+ cdef _BaseParser getDefaultParser(self):
91
+ "Return (or create) the default parser of the current thread"
92
+ cdef _ParserDictionaryContext context
93
+ context = self._findThreadParserContext()
94
+ if context._default_parser is None:
95
+ if self._default_parser is None:
96
+ self._default_parser = __DEFAULT_XML_PARSER._copy()
97
+ if context is not self:
98
+ context._default_parser = self._default_parser._copy()
99
+ return context._default_parser
100
+
101
+ cdef tree.xmlDict* _getThreadDict(self, tree.xmlDict* default):
102
+ "Return the thread-local dict or create a new one if necessary."
103
+ cdef _ParserDictionaryContext context
104
+ context = self._findThreadParserContext()
105
+ if context._c_dict is NULL:
106
+ # thread dict not yet set up => use default or create a new one
107
+ if default is not NULL:
108
+ context._c_dict = default
109
+ xmlparser.xmlDictReference(default)
110
+ return default
111
+ if self._c_dict is NULL:
112
+ self._c_dict = xmlparser.xmlDictCreate()
113
+ if context is not self:
114
+ context._c_dict = xmlparser.xmlDictCreateSub(self._c_dict)
115
+ return context._c_dict
116
+
117
+ cdef int initThreadDictRef(self, tree.xmlDict** c_dict_ref) except -1:
118
+ c_dict = c_dict_ref[0]
119
+ c_thread_dict = self._getThreadDict(c_dict)
120
+ if c_dict is c_thread_dict:
121
+ return 0
122
+ if c_dict is not NULL:
123
+ xmlparser.xmlDictFree(c_dict)
124
+ c_dict_ref[0] = c_thread_dict
125
+ xmlparser.xmlDictReference(c_thread_dict)
126
+
127
+ cdef int initParserDict(self, xmlparser.xmlParserCtxt* pctxt) except -1:
128
+ "Assure we always use the same string dictionary."
129
+ self.initThreadDictRef(&pctxt.dict)
130
+ pctxt.dictNames = 1
131
+
132
+ cdef int initXPathParserDict(self, xpath.xmlXPathContext* pctxt) except -1:
133
+ "Assure we always use the same string dictionary."
134
+ self.initThreadDictRef(&pctxt.dict)
135
+
136
+ cdef int initDocDict(self, xmlDoc* result) except -1:
137
+ "Store dict of last object parsed if no shared dict yet"
138
+ # XXX We also free the result dict here if there already was one.
139
+ # This case should only occur for new documents with empty dicts,
140
+ # otherwise we'd free data that's in use => segfault
141
+ self.initThreadDictRef(&result.dict)
142
+
143
+ cdef _ParserContext findImpliedContext(self):
144
+ """Return any current implied xml parser context for the current
145
+ thread. This is used when the resolver functions are called
146
+ with an xmlParserCtxt that was generated from within libxml2
147
+ (i.e. without a _ParserContext) - which happens when parsing
148
+ schema and xinclude external references."""
149
+ cdef _ParserDictionaryContext context
150
+ cdef _ParserContext implied_context
151
+
152
+ # see if we have a current implied parser
153
+ context = self._findThreadParserContext()
154
+ if context._implied_parser_contexts:
155
+ implied_context = context._implied_parser_contexts[-1]
156
+ return implied_context
157
+ return None
158
+
159
+ cdef int pushImpliedContextFromParser(self, _BaseParser parser) except -1:
160
+ "Push a new implied context object taken from the parser."
161
+ if parser is not None:
162
+ self.pushImpliedContext(parser._getParserContext())
163
+ else:
164
+ self.pushImpliedContext(None)
165
+
166
+ cdef int pushImpliedContext(self, _ParserContext parser_context) except -1:
167
+ "Push a new implied context object."
168
+ cdef _ParserDictionaryContext context
169
+ context = self._findThreadParserContext()
170
+ context._implied_parser_contexts.append(parser_context)
171
+
172
+ cdef int popImpliedContext(self) except -1:
173
+ "Pop the current implied context object."
174
+ cdef _ParserDictionaryContext context
175
+ context = self._findThreadParserContext()
176
+ context._implied_parser_contexts.pop()
177
+
178
+ cdef _ParserDictionaryContext __GLOBAL_PARSER_CONTEXT = _ParserDictionaryContext()
179
+ __GLOBAL_PARSER_CONTEXT.initMainParserContext()
180
+
181
+ ############################################################
182
+ ## support for Python unicode I/O
183
+ ############################################################
184
+
185
+ # name of Python Py_UNICODE encoding as known to libxml2
186
+ cdef const_char* _PY_UNICODE_ENCODING = NULL
187
+
188
+ cdef int _setupPythonUnicode() except -1:
189
+ """Sets _PY_UNICODE_ENCODING to the internal encoding name of Python unicode
190
+ strings if libxml2 supports reading native Python unicode. This depends
191
+ on iconv and the local Python installation, so we simply check if we find
192
+ a matching encoding handler.
193
+ """
194
+ cdef tree.xmlCharEncodingHandler* enchandler
195
+ cdef Py_ssize_t l
196
+ cdef const_char* enc
197
+ cdef Py_UNICODE *uchars = [c'<', c't', c'e', c's', c't', c'/', c'>']
198
+ cdef const_xmlChar* buffer = <const_xmlChar*>uchars
199
+ # apparently, libxml2 can't detect UTF-16 on some systems
200
+ if (buffer[0] == c'<' and buffer[1] == c'\0' and
201
+ buffer[2] == c't' and buffer[3] == c'\0'):
202
+ enc = "UTF-16LE"
203
+ elif (buffer[0] == c'\0' and buffer[1] == c'<' and
204
+ buffer[2] == c'\0' and buffer[3] == c't'):
205
+ enc = "UTF-16BE"
206
+ else:
207
+ # let libxml2 give it a try
208
+ enc = _findEncodingName(buffer, sizeof(Py_UNICODE) * 7)
209
+ if enc is NULL:
210
+ # not my fault, it's YOUR broken system :)
211
+ return 0
212
+ enchandler = tree.xmlFindCharEncodingHandler(enc)
213
+ if enchandler is not NULL:
214
+ global _PY_UNICODE_ENCODING
215
+ tree.xmlCharEncCloseFunc(enchandler)
216
+ _PY_UNICODE_ENCODING = enc
217
+ return 0
218
+
219
+ cdef const_char* _findEncodingName(const_xmlChar* buffer, int size):
220
+ "Work around bug in libxml2: find iconv name of encoding on our own."
221
+ cdef tree.xmlCharEncoding enc
222
+ enc = tree.xmlDetectCharEncoding(buffer, size)
223
+ if enc == tree.XML_CHAR_ENCODING_UTF16LE:
224
+ if size >= 4 and (buffer[0] == <const_xmlChar> b'\xFF' and
225
+ buffer[1] == <const_xmlChar> b'\xFE' and
226
+ buffer[2] == 0 and buffer[3] == 0):
227
+ return "UTF-32LE" # according to BOM
228
+ else:
229
+ return "UTF-16LE"
230
+ elif enc == tree.XML_CHAR_ENCODING_UTF16BE:
231
+ return "UTF-16BE"
232
+ elif enc == tree.XML_CHAR_ENCODING_UCS4LE:
233
+ return "UCS-4LE"
234
+ elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
235
+ return "UCS-4BE"
236
+ elif enc == tree.XML_CHAR_ENCODING_NONE:
237
+ return NULL
238
+ else:
239
+ # returns a constant char*, no need to free it
240
+ return tree.xmlGetCharEncodingName(enc)
241
+
242
+ # Python 3.12 removed support for "Py_UNICODE".
243
+ if python.PY_VERSION_HEX < 0x030C0000:
244
+ _setupPythonUnicode()
245
+
246
+
247
+ cdef unicode _find_PyUCS4EncodingName():
248
+ """
249
+ Find a suitable encoding for Py_UCS4 PyUnicode strings in libxml2.
250
+ """
251
+ ustring = "<xml>\U0001F92A</xml>"
252
+ cdef const xmlChar* buffer = <const xmlChar*> python.PyUnicode_DATA(ustring)
253
+ cdef Py_ssize_t py_buffer_len = python.PyUnicode_GET_LENGTH(ustring)
254
+
255
+ encoding_name = ''
256
+ cdef tree.xmlCharEncoding enc = tree.xmlDetectCharEncoding(buffer, py_buffer_len)
257
+ enchandler = tree.xmlGetCharEncodingHandler(enc)
258
+ if enchandler is not NULL:
259
+ try:
260
+ if enchandler.name:
261
+ encoding_name = enchandler.name.decode('UTF-8')
262
+ finally:
263
+ tree.xmlCharEncCloseFunc(enchandler)
264
+ else:
265
+ c_name = tree.xmlGetCharEncodingName(enc)
266
+ if c_name:
267
+ encoding_name = c_name.decode('UTF-8')
268
+
269
+
270
+ if encoding_name and not encoding_name.endswith('LE') and not encoding_name.endswith('BE'):
271
+ encoding_name += 'BE' if python.PY_BIG_ENDIAN else 'LE'
272
+ return encoding_name or None
273
+
274
+ _pyucs4_encoding_name = _find_PyUCS4EncodingName()
275
+
276
+
277
+ ############################################################
278
+ ## support for file-like objects
279
+ ############################################################
280
+
281
+ @cython.final
282
+ @cython.internal
283
+ cdef class _FileReaderContext:
284
+ cdef object _filelike
285
+ cdef object _encoding
286
+ cdef object _url
287
+ cdef object _bytes
288
+ cdef _ExceptionContext _exc_context
289
+ cdef Py_ssize_t _bytes_read
290
+ cdef char* _c_url
291
+ cdef bint _close_file_after_read
292
+
293
+ def __cinit__(self, filelike, exc_context not None, url, encoding=None, bint close_file=False):
294
+ self._exc_context = exc_context
295
+ self._filelike = filelike
296
+ self._close_file_after_read = close_file
297
+ self._encoding = encoding
298
+ if url is None:
299
+ self._c_url = NULL
300
+ else:
301
+ url = _encodeFilename(url)
302
+ self._c_url = _cstr(url)
303
+ self._url = url
304
+ self._bytes = b''
305
+ self._bytes_read = 0
306
+
307
+ cdef _close_file(self):
308
+ if self._filelike is None or not self._close_file_after_read:
309
+ return
310
+ try:
311
+ close = self._filelike.close
312
+ except AttributeError:
313
+ close = None
314
+ finally:
315
+ self._filelike = None
316
+ if close is not None:
317
+ close()
318
+
319
+ cdef xmlparser.xmlParserInputBuffer* _createParserInputBuffer(self) noexcept:
320
+ cdef xmlparser.xmlParserInputBuffer* c_buffer = xmlparser.xmlAllocParserInputBuffer(0)
321
+ if c_buffer:
322
+ c_buffer.readcallback = _readFilelikeParser
323
+ c_buffer.context = <python.PyObject*> self
324
+ return c_buffer
325
+
326
+ cdef xmlparser.xmlParserInput* _createParserInput(
327
+ self, xmlparser.xmlParserCtxt* ctxt) noexcept:
328
+ cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
329
+ if not c_buffer:
330
+ return NULL
331
+ return xmlparser.xmlNewIOInputStream(ctxt, c_buffer, 0)
332
+
333
+ cdef tree.xmlDtd* _readDtd(self) noexcept:
334
+ cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
335
+ if not c_buffer:
336
+ return NULL
337
+ with nogil:
338
+ return xmlparser.xmlIOParseDTD(NULL, c_buffer, 0)
339
+
340
+ cdef xmlDoc* _readDoc(self, xmlparser.xmlParserCtxt* ctxt, int options) noexcept:
341
+ cdef xmlDoc* result
342
+ cdef void* c_callback_context = <python.PyObject*> self
343
+ cdef char* c_encoding = _cstr(self._encoding) if self._encoding is not None else NULL
344
+
345
+ orig_options = ctxt.options
346
+ with nogil:
347
+ if ctxt.html:
348
+ result = htmlparser.htmlCtxtReadIO(
349
+ ctxt, _readFilelikeParser, NULL, c_callback_context,
350
+ self._c_url, c_encoding, options)
351
+ if result is not NULL:
352
+ if _fixHtmlDictNames(ctxt.dict, result) < 0:
353
+ tree.xmlFreeDoc(result)
354
+ result = NULL
355
+ else:
356
+ result = xmlparser.xmlCtxtReadIO(
357
+ ctxt, _readFilelikeParser, NULL, c_callback_context,
358
+ self._c_url, c_encoding, options)
359
+ ctxt.options = orig_options # work around libxml2 problem
360
+
361
+ try:
362
+ self._close_file()
363
+ except:
364
+ self._exc_context._store_raised()
365
+ finally:
366
+ return result # swallow any exceptions
367
+
368
+ cdef int copyToBuffer(self, char* c_buffer, int c_requested) noexcept:
369
+ cdef int c_byte_count = 0
370
+ cdef char* c_start
371
+ cdef Py_ssize_t byte_count, remaining
372
+ if self._bytes_read < 0:
373
+ return 0
374
+ try:
375
+ byte_count = python.PyBytes_GET_SIZE(self._bytes)
376
+ remaining = byte_count - self._bytes_read
377
+ while c_requested > remaining:
378
+ c_start = _cstr(self._bytes) + self._bytes_read
379
+ cstring_h.memcpy(c_buffer, c_start, remaining)
380
+ c_byte_count += remaining
381
+ c_buffer += remaining
382
+ c_requested -= remaining
383
+
384
+ self._bytes = self._filelike.read(c_requested)
385
+ if not isinstance(self._bytes, bytes):
386
+ if isinstance(self._bytes, unicode):
387
+ if self._encoding is None:
388
+ self._bytes = (<unicode>self._bytes).encode('utf8')
389
+ else:
390
+ self._bytes = python.PyUnicode_AsEncodedString(
391
+ self._bytes, _cstr(self._encoding), NULL)
392
+ else:
393
+ self._close_file()
394
+ raise TypeError, \
395
+ "reading from file-like objects must return byte strings or unicode strings"
396
+
397
+ remaining = python.PyBytes_GET_SIZE(self._bytes)
398
+ if remaining == 0:
399
+ self._bytes_read = -1
400
+ self._close_file()
401
+ return c_byte_count
402
+ self._bytes_read = 0
403
+
404
+ if c_requested > 0:
405
+ c_start = _cstr(self._bytes) + self._bytes_read
406
+ cstring_h.memcpy(c_buffer, c_start, c_requested)
407
+ c_byte_count += c_requested
408
+ self._bytes_read += c_requested
409
+ except:
410
+ c_byte_count = -1
411
+ self._exc_context._store_raised()
412
+ try:
413
+ self._close_file()
414
+ except:
415
+ self._exc_context._store_raised()
416
+ finally:
417
+ return c_byte_count # swallow any exceptions
418
+
419
+ cdef int _readFilelikeParser(void* ctxt, char* c_buffer, int c_size) noexcept with gil:
420
+ return (<_FileReaderContext>ctxt).copyToBuffer(c_buffer, c_size)
421
+
422
+ cdef int _readFileParser(void* ctxt, char* c_buffer, int c_size) noexcept nogil:
423
+ return stdio.fread(c_buffer, 1, c_size, <stdio.FILE*>ctxt)
424
+
425
+ ############################################################
426
+ ## support for custom document loaders
427
+ ############################################################
428
+
429
+ cdef xmlparser.xmlParserInput* _local_resolver(const_char* c_url, const_char* c_pubid,
430
+ xmlparser.xmlParserCtxt* c_context) noexcept with gil:
431
+ cdef _ResolverContext context
432
+ cdef xmlparser.xmlParserInput* c_input
433
+ cdef _InputDocument doc_ref
434
+ cdef _FileReaderContext file_context
435
+ # if there is no _ParserContext associated with the xmlParserCtxt
436
+ # passed, check to see if the thread state object has an implied
437
+ # context.
438
+ if c_context._private is not NULL:
439
+ context = <_ResolverContext>c_context._private
440
+ else:
441
+ context = __GLOBAL_PARSER_CONTEXT.findImpliedContext()
442
+
443
+ if context is None:
444
+ if __DEFAULT_ENTITY_LOADER is NULL:
445
+ return NULL
446
+ with nogil:
447
+ # free the GIL as we might do serious I/O here (e.g. HTTP)
448
+ c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
449
+ return c_input
450
+
451
+ try:
452
+ if c_url is NULL:
453
+ url = None
454
+ else:
455
+ # parsing a related document (DTD etc.) => UTF-8 encoded URL?
456
+ url = _decodeFilename(<const_xmlChar*>c_url)
457
+ if c_pubid is NULL:
458
+ pubid = None
459
+ else:
460
+ pubid = funicode(<const_xmlChar*>c_pubid) # always UTF-8
461
+
462
+ doc_ref = context._resolvers.resolve(url, pubid, context)
463
+ except:
464
+ context._store_raised()
465
+ return NULL
466
+
467
+ if doc_ref is not None:
468
+ if doc_ref._type == PARSER_DATA_STRING:
469
+ data = doc_ref._data_bytes
470
+ filename = doc_ref._filename
471
+ if not filename:
472
+ filename = None
473
+ elif not isinstance(filename, bytes):
474
+ # most likely a text URL
475
+ filename = filename.encode('utf8')
476
+ if not isinstance(filename, bytes):
477
+ filename = None
478
+
479
+ c_input = xmlparser.xmlNewInputStream(c_context)
480
+ if c_input is not NULL:
481
+ if filename is not None:
482
+ c_input.filename = <char *>tree.xmlStrdup(_xcstr(filename))
483
+ c_input.base = _xcstr(data)
484
+ c_input.length = python.PyBytes_GET_SIZE(data)
485
+ c_input.cur = c_input.base
486
+ c_input.end = c_input.base + c_input.length
487
+ elif doc_ref._type == PARSER_DATA_FILENAME:
488
+ data = None
489
+ c_filename = _cstr(doc_ref._filename)
490
+ with nogil:
491
+ # free the GIL as we might do serious I/O here
492
+ c_input = xmlparser.xmlNewInputFromFile(
493
+ c_context, c_filename)
494
+ elif doc_ref._type == PARSER_DATA_FILE:
495
+ file_context = _FileReaderContext(doc_ref._file, context, url,
496
+ None, doc_ref._close_file)
497
+ c_input = file_context._createParserInput(c_context)
498
+ data = file_context
499
+ else:
500
+ data = None
501
+ c_input = NULL
502
+
503
+ if data is not None:
504
+ context._storage.add(data)
505
+ if c_input is not NULL:
506
+ return c_input
507
+
508
+ if __DEFAULT_ENTITY_LOADER is NULL:
509
+ return NULL
510
+
511
+ with nogil:
512
+ # free the GIL as we might do serious I/O here (e.g. HTTP)
513
+ c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
514
+ return c_input
515
+
516
+ cdef xmlparser.xmlExternalEntityLoader __DEFAULT_ENTITY_LOADER
517
+ __DEFAULT_ENTITY_LOADER = xmlparser.xmlGetExternalEntityLoader()
518
+
519
+
520
+ cdef xmlparser.xmlExternalEntityLoader _register_document_loader() noexcept nogil:
521
+ cdef xmlparser.xmlExternalEntityLoader old = xmlparser.xmlGetExternalEntityLoader()
522
+ xmlparser.xmlSetExternalEntityLoader(<xmlparser.xmlExternalEntityLoader>_local_resolver)
523
+ return old
524
+
525
+ cdef void _reset_document_loader(xmlparser.xmlExternalEntityLoader old) noexcept nogil:
526
+ xmlparser.xmlSetExternalEntityLoader(old)
527
+
528
+
529
+ ############################################################
530
+ ## Parsers
531
+ ############################################################
532
+
533
+ @cython.no_gc_clear # May have to call "self._validator.disconnect()" on dealloc.
534
+ @cython.internal
535
+ cdef class _ParserContext(_ResolverContext):
536
+ cdef _ErrorLog _error_log
537
+ cdef _ParserSchemaValidationContext _validator
538
+ cdef xmlparser.xmlParserCtxt* _c_ctxt
539
+ cdef xmlparser.xmlExternalEntityLoader _orig_loader
540
+ cdef python.PyThread_type_lock _lock
541
+ cdef _Document _doc
542
+ cdef bint _collect_ids
543
+
544
+ def __cinit__(self):
545
+ self._c_ctxt = NULL
546
+ self._collect_ids = True
547
+ if not config.ENABLE_THREADING:
548
+ self._lock = NULL
549
+ else:
550
+ self._lock = python.PyThread_allocate_lock()
551
+ self._error_log = _ErrorLog()
552
+
553
+ def __dealloc__(self):
554
+ if config.ENABLE_THREADING and self._lock is not NULL:
555
+ python.PyThread_free_lock(self._lock)
556
+ self._lock = NULL
557
+ if self._c_ctxt is not NULL:
558
+ if <void*>self._validator is not NULL and self._validator is not None:
559
+ # If the parser was not closed correctly (e.g. interrupted iterparse()),
560
+ # and the schema validator wasn't freed and cleaned up yet, the libxml2 SAX
561
+ # validator plug might still be in place, which will make xmlFreeParserCtxt()
562
+ # crash when trying to xmlFree() a static SAX handler.
563
+ # Thus, make sure we disconnect the handler interceptor here at the latest.
564
+ self._validator.disconnect()
565
+ xmlparser.xmlFreeParserCtxt(self._c_ctxt)
566
+
567
+ cdef _ParserContext _copy(self):
568
+ cdef _ParserContext context
569
+ context = self.__class__()
570
+ context._collect_ids = self._collect_ids
571
+ context._validator = self._validator.copy()
572
+ _initParserContext(context, self._resolvers._copy(), NULL)
573
+ return context
574
+
575
+ cdef void _initParserContext(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
576
+ self._c_ctxt = c_ctxt
577
+ c_ctxt._private = <void*>self
578
+
579
+ cdef void _resetParserContext(self) noexcept:
580
+ if self._c_ctxt is not NULL:
581
+ if self._c_ctxt.html:
582
+ htmlparser.htmlCtxtReset(self._c_ctxt)
583
+ self._c_ctxt.disableSAX = 0 # work around bug in libxml2
584
+ else:
585
+ xmlparser.xmlClearParserCtxt(self._c_ctxt)
586
+ # work around bug in libxml2 [2.9.10 .. 2.9.14]:
587
+ # https://gitlab.gnome.org/GNOME/libxml2/-/issues/378
588
+ self._c_ctxt.nsNr = 0
589
+
590
+ cdef int prepare(self, bint set_document_loader=True) except -1:
591
+ cdef int result
592
+ if config.ENABLE_THREADING and self._lock is not NULL:
593
+ with nogil:
594
+ result = python.PyThread_acquire_lock(
595
+ self._lock, python.WAIT_LOCK)
596
+ if result == 0:
597
+ raise ParserError, "parser locking failed"
598
+ self._error_log.clear()
599
+ self._doc = None
600
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
601
+ self._c_ctxt.sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
602
+ self._orig_loader = _register_document_loader() if set_document_loader else NULL
603
+ if self._validator is not None:
604
+ self._validator.connect(self._c_ctxt, self._error_log)
605
+ return 0
606
+
607
+ cdef int cleanup(self) except -1:
608
+ if self._orig_loader is not NULL:
609
+ _reset_document_loader(self._orig_loader)
610
+ try:
611
+ if self._validator is not None:
612
+ self._validator.disconnect()
613
+ self._resetParserContext()
614
+ self.clear()
615
+ self._doc = None
616
+ self._c_ctxt.sax.serror = NULL
617
+ finally:
618
+ if config.ENABLE_THREADING and self._lock is not NULL:
619
+ python.PyThread_release_lock(self._lock)
620
+ return 0
621
+
622
+ cdef object _handleParseResult(self, _BaseParser parser,
623
+ xmlDoc* result, filename):
624
+ c_doc = self._handleParseResultDoc(parser, result, filename)
625
+ if self._doc is not None and self._doc._c_doc is c_doc:
626
+ return self._doc
627
+ else:
628
+ return _documentFactory(c_doc, parser)
629
+
630
+ cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser,
631
+ xmlDoc* result, filename) except NULL:
632
+ recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
633
+ return _handleParseResult(self, self._c_ctxt, result,
634
+ filename, recover,
635
+ free_doc=self._doc is None)
636
+
637
+ cdef _initParserContext(_ParserContext context,
638
+ _ResolverRegistry resolvers,
639
+ xmlparser.xmlParserCtxt* c_ctxt):
640
+ _initResolverContext(context, resolvers)
641
+ if c_ctxt is not NULL:
642
+ context._initParserContext(c_ctxt)
643
+
644
+ cdef void _forwardParserError(xmlparser.xmlParserCtxt* _parser_context, const xmlerror.xmlError* error) noexcept with gil:
645
+ (<_ParserContext>_parser_context._private)._error_log._receive(error)
646
+
647
+ cdef void _receiveParserError(void* c_context, const xmlerror.xmlError* error) noexcept nogil:
648
+ if __DEBUG:
649
+ if c_context is NULL or (<xmlparser.xmlParserCtxt*>c_context)._private is NULL:
650
+ _forwardError(NULL, error)
651
+ else:
652
+ _forwardParserError(<xmlparser.xmlParserCtxt*>c_context, error)
653
+
654
+ cdef int _raiseParseError(xmlparser.xmlParserCtxt* ctxt, filename,
655
+ _ErrorLog error_log) except -1:
656
+ if filename is not None and \
657
+ ctxt.lastError.domain == xmlerror.XML_FROM_IO:
658
+ if isinstance(filename, bytes):
659
+ filename = _decodeFilenameWithLength(
660
+ <bytes>filename, len(<bytes>filename))
661
+ if ctxt.lastError.message is not NULL:
662
+ try:
663
+ message = ctxt.lastError.message.decode('utf-8')
664
+ except UnicodeDecodeError:
665
+ # the filename may be in there => play it safe
666
+ message = ctxt.lastError.message.decode('iso8859-1')
667
+ message = f"Error reading file '{filename}': {message.strip()}"
668
+ else:
669
+ message = f"Error reading '{filename}'"
670
+ raise IOError, message
671
+ elif error_log:
672
+ raise error_log._buildParseException(
673
+ XMLSyntaxError, "Document is not well formed")
674
+ elif ctxt.lastError.message is not NULL:
675
+ message = ctxt.lastError.message.strip()
676
+ code = ctxt.lastError.code
677
+ line = ctxt.lastError.line
678
+ column = ctxt.lastError.int2
679
+ if ctxt.lastError.line > 0:
680
+ message = f"line {line}: {message}"
681
+ raise XMLSyntaxError(message, code, line, column, filename)
682
+ else:
683
+ raise XMLSyntaxError(None, xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
684
+ filename)
685
+
686
+ cdef xmlDoc* _handleParseResult(_ParserContext context,
687
+ xmlparser.xmlParserCtxt* c_ctxt,
688
+ xmlDoc* result, filename,
689
+ bint recover, bint free_doc) except NULL:
690
+ cdef bint well_formed
691
+ if result is not NULL:
692
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
693
+
694
+ if c_ctxt.myDoc is not NULL:
695
+ if c_ctxt.myDoc is not result:
696
+ __GLOBAL_PARSER_CONTEXT.initDocDict(c_ctxt.myDoc)
697
+ tree.xmlFreeDoc(c_ctxt.myDoc)
698
+ c_ctxt.myDoc = NULL
699
+
700
+ if result is not NULL:
701
+ if (context._validator is not None and
702
+ not context._validator.isvalid()):
703
+ well_formed = 0 # actually not 'valid', but anyway ...
704
+ elif (not c_ctxt.wellFormed and not c_ctxt.html and
705
+ c_ctxt.charset == tree.XML_CHAR_ENCODING_8859_1 and
706
+ [1 for error in context._error_log
707
+ if error.type == ErrorTypes.ERR_INVALID_CHAR]):
708
+ # An encoding error occurred and libxml2 switched from UTF-8
709
+ # input to (undecoded) Latin-1, at some arbitrary point in the
710
+ # document. Better raise an error than allowing for a broken
711
+ # tree with mixed encodings. This is fixed in libxml2 2.12.
712
+ well_formed = 0
713
+ elif recover or (c_ctxt.wellFormed and
714
+ c_ctxt.lastError.level < xmlerror.XML_ERR_ERROR):
715
+ well_formed = 1
716
+ elif not c_ctxt.replaceEntities and not c_ctxt.validate \
717
+ and context is not None:
718
+ # in this mode, we ignore errors about undefined entities
719
+ for error in context._error_log.filter_from_errors():
720
+ if error.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
721
+ error.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
722
+ well_formed = 0
723
+ break
724
+ else:
725
+ well_formed = 1
726
+ else:
727
+ well_formed = 0
728
+
729
+ if not well_formed:
730
+ if free_doc:
731
+ tree.xmlFreeDoc(result)
732
+ result = NULL
733
+
734
+ if context is not None and context._has_raised():
735
+ if result is not NULL:
736
+ if free_doc:
737
+ tree.xmlFreeDoc(result)
738
+ result = NULL
739
+ context._raise_if_stored()
740
+
741
+ if result is NULL:
742
+ if context is not None:
743
+ _raiseParseError(c_ctxt, filename, context._error_log)
744
+ else:
745
+ _raiseParseError(c_ctxt, filename, None)
746
+ else:
747
+ if result.URL is NULL and filename is not None:
748
+ result.URL = tree.xmlStrdup(_xcstr(filename))
749
+ if result.encoding is NULL:
750
+ result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
751
+
752
+ if context._validator is not None and \
753
+ context._validator._add_default_attributes:
754
+ # we currently need to do this here as libxml2 does not
755
+ # support inserting default attributes during parse-time
756
+ # validation
757
+ context._validator.inject_default_attributes(result)
758
+
759
+ return result
760
+
761
+ cdef int _fixHtmlDictNames(tree.xmlDict* c_dict, xmlDoc* c_doc) noexcept nogil:
762
+ cdef xmlNode* c_node
763
+ if c_doc is NULL:
764
+ return 0
765
+ c_node = c_doc.children
766
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
767
+ if c_node.type == tree.XML_ELEMENT_NODE:
768
+ if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
769
+ return -1
770
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
771
+ return 0
772
+
773
+ cdef int _fixHtmlDictSubtreeNames(tree.xmlDict* c_dict, xmlDoc* c_doc,
774
+ xmlNode* c_start_node) noexcept nogil:
775
+ """
776
+ Move names to the dict, iterating in document order, starting at
777
+ c_start_node. This is used in incremental parsing after each chunk.
778
+ """
779
+ cdef xmlNode* c_node
780
+ if not c_doc:
781
+ return 0
782
+ if not c_start_node:
783
+ return _fixHtmlDictNames(c_dict, c_doc)
784
+ c_node = c_start_node
785
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
786
+ if c_node.type == tree.XML_ELEMENT_NODE:
787
+ if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
788
+ return -1
789
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
790
+ return 0
791
+
792
+ cdef inline int _fixHtmlDictNodeNames(tree.xmlDict* c_dict,
793
+ xmlNode* c_node) noexcept nogil:
794
+ cdef xmlNode* c_attr
795
+ c_name = tree.xmlDictLookup(c_dict, c_node.name, -1)
796
+ if c_name is NULL:
797
+ return -1
798
+ if c_name is not c_node.name:
799
+ tree.xmlFree(<char*>c_node.name)
800
+ c_node.name = c_name
801
+ c_attr = <xmlNode*>c_node.properties
802
+ while c_attr is not NULL:
803
+ c_name = tree.xmlDictLookup(c_dict, c_attr.name, -1)
804
+ if c_name is NULL:
805
+ return -1
806
+ if c_name is not c_attr.name:
807
+ tree.xmlFree(<char*>c_attr.name)
808
+ c_attr.name = c_name
809
+ c_attr = c_attr.next
810
+ return 0
811
+
812
+
813
+ @cython.internal
814
+ cdef class _BaseParser:
815
+ cdef ElementClassLookup _class_lookup
816
+ cdef _ResolverRegistry _resolvers
817
+ cdef _ParserContext _parser_context
818
+ cdef _ParserContext _push_parser_context
819
+ cdef int _parse_options
820
+ cdef bint _for_html
821
+ cdef bint _remove_comments
822
+ cdef bint _remove_pis
823
+ cdef bint _strip_cdata
824
+ cdef bint _collect_ids
825
+ cdef bint _resolve_external_entities
826
+ cdef XMLSchema _schema
827
+ cdef bytes _filename
828
+ cdef readonly object target
829
+ cdef object _default_encoding
830
+ cdef tuple _events_to_collect # (event_types, tag)
831
+
832
+ def __init__(self, int parse_options, bint for_html, XMLSchema schema,
833
+ remove_comments, remove_pis, strip_cdata, collect_ids,
834
+ target, encoding, bint resolve_external_entities=True):
835
+ cdef tree.xmlCharEncodingHandler* enchandler
836
+ cdef int c_encoding
837
+ if not isinstance(self, (XMLParser, HTMLParser)):
838
+ raise TypeError, "This class cannot be instantiated"
839
+
840
+ self._parse_options = parse_options
841
+ self.target = target
842
+ self._for_html = for_html
843
+ self._remove_comments = remove_comments
844
+ self._remove_pis = remove_pis
845
+ self._strip_cdata = strip_cdata
846
+ self._collect_ids = collect_ids
847
+ self._resolve_external_entities = resolve_external_entities
848
+ self._schema = schema
849
+
850
+ self._resolvers = _ResolverRegistry()
851
+
852
+ if encoding is None:
853
+ self._default_encoding = None
854
+ else:
855
+ encoding = _utf8(encoding)
856
+ enchandler = tree.xmlFindCharEncodingHandler(_cstr(encoding))
857
+ if enchandler is NULL:
858
+ raise LookupError, f"unknown encoding: '{encoding}'"
859
+ tree.xmlCharEncCloseFunc(enchandler)
860
+ self._default_encoding = encoding
861
+
862
+ cdef _setBaseURL(self, base_url):
863
+ self._filename = _encodeFilename(base_url)
864
+
865
+ cdef _collectEvents(self, event_types, tag):
866
+ if event_types is None:
867
+ event_types = ()
868
+ else:
869
+ event_types = tuple(set(event_types))
870
+ _buildParseEventFilter(event_types) # purely for validation
871
+ self._events_to_collect = (event_types, tag)
872
+
873
+ cdef _ParserContext _getParserContext(self):
874
+ cdef xmlparser.xmlParserCtxt* pctxt
875
+ if self._parser_context is None:
876
+ self._parser_context = self._createContext(self.target, None)
877
+ self._parser_context._collect_ids = self._collect_ids
878
+ if self._schema is not None:
879
+ self._parser_context._validator = \
880
+ self._schema._newSaxValidator(
881
+ self._parse_options & xmlparser.XML_PARSE_DTDATTR)
882
+ pctxt = self._newParserCtxt()
883
+ _initParserContext(self._parser_context, self._resolvers, pctxt)
884
+ self._configureSaxContext(pctxt)
885
+ return self._parser_context
886
+
887
+ cdef _ParserContext _getPushParserContext(self):
888
+ cdef xmlparser.xmlParserCtxt* pctxt
889
+ if self._push_parser_context is None:
890
+ self._push_parser_context = self._createContext(
891
+ self.target, self._events_to_collect)
892
+ self._push_parser_context._collect_ids = self._collect_ids
893
+ if self._schema is not None:
894
+ self._push_parser_context._validator = \
895
+ self._schema._newSaxValidator(
896
+ self._parse_options & xmlparser.XML_PARSE_DTDATTR)
897
+ pctxt = self._newPushParserCtxt()
898
+ _initParserContext(
899
+ self._push_parser_context, self._resolvers, pctxt)
900
+ self._configureSaxContext(pctxt)
901
+ return self._push_parser_context
902
+
903
+ cdef _ParserContext _createContext(self, target, events_to_collect):
904
+ cdef _SaxParserContext sax_context
905
+ if target is not None:
906
+ sax_context = _TargetParserContext(self)
907
+ (<_TargetParserContext>sax_context)._setTarget(target)
908
+ elif events_to_collect:
909
+ sax_context = _SaxParserContext(self)
910
+ else:
911
+ # nothing special to configure
912
+ return _ParserContext()
913
+ if events_to_collect:
914
+ events, tag = events_to_collect
915
+ sax_context._setEventFilter(events, tag)
916
+ return sax_context
917
+
918
+ @cython.final
919
+ cdef int _configureSaxContext(self, xmlparser.xmlParserCtxt* pctxt) except -1:
920
+ if self._remove_comments:
921
+ pctxt.sax.comment = NULL
922
+ if self._remove_pis:
923
+ pctxt.sax.processingInstruction = NULL
924
+ if self._strip_cdata:
925
+ # hard switch-off for CDATA nodes => makes them plain text
926
+ pctxt.sax.cdataBlock = NULL
927
+ if not self._resolve_external_entities:
928
+ pctxt.sax.getEntity = _getInternalEntityOnly
929
+
930
+ cdef int _registerHtmlErrorHandler(self, xmlparser.xmlParserCtxt* c_ctxt) except -1:
931
+ cdef xmlparser.xmlSAXHandler* sax = c_ctxt.sax
932
+ if sax is not NULL and sax.initialized and sax.initialized != xmlparser.XML_SAX2_MAGIC:
933
+ # need to extend SAX1 context to SAX2 to get proper error reports
934
+ if <xmlparser.xmlSAXHandlerV1*>sax is &htmlparser.htmlDefaultSAXHandler:
935
+ sax = <xmlparser.xmlSAXHandler*> tree.xmlMalloc(sizeof(xmlparser.xmlSAXHandler))
936
+ if sax is NULL:
937
+ raise MemoryError()
938
+ cstring_h.memcpy(sax, &htmlparser.htmlDefaultSAXHandler,
939
+ sizeof(htmlparser.htmlDefaultSAXHandler))
940
+ c_ctxt.sax = sax
941
+ sax.initialized = xmlparser.XML_SAX2_MAGIC
942
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
943
+ sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
944
+ sax.startElementNs = NULL
945
+ sax.endElementNs = NULL
946
+ sax._private = NULL
947
+ return 0
948
+
949
+ cdef xmlparser.xmlParserCtxt* _newParserCtxt(self) except NULL:
950
+ cdef xmlparser.xmlParserCtxt* c_ctxt
951
+ if self._for_html:
952
+ c_ctxt = htmlparser.htmlCreateMemoryParserCtxt('dummy', 5)
953
+ if c_ctxt is not NULL:
954
+ self._registerHtmlErrorHandler(c_ctxt)
955
+ else:
956
+ c_ctxt = xmlparser.xmlNewParserCtxt()
957
+ if c_ctxt is NULL:
958
+ raise MemoryError
959
+ c_ctxt.sax.startDocument = _initSaxDocument
960
+ return c_ctxt
961
+
962
+ cdef xmlparser.xmlParserCtxt* _newPushParserCtxt(self) except NULL:
963
+ cdef xmlparser.xmlParserCtxt* c_ctxt
964
+ cdef char* c_filename = _cstr(self._filename) if self._filename is not None else NULL
965
+ if self._for_html:
966
+ c_ctxt = htmlparser.htmlCreatePushParserCtxt(
967
+ NULL, NULL, NULL, 0, c_filename, tree.XML_CHAR_ENCODING_NONE)
968
+ if c_ctxt is not NULL:
969
+ self._registerHtmlErrorHandler(c_ctxt)
970
+ htmlparser.htmlCtxtUseOptions(c_ctxt, self._parse_options)
971
+ else:
972
+ c_ctxt = xmlparser.xmlCreatePushParserCtxt(
973
+ NULL, NULL, NULL, 0, c_filename)
974
+ if c_ctxt is not NULL:
975
+ xmlparser.xmlCtxtUseOptions(c_ctxt, self._parse_options)
976
+ if c_ctxt is NULL:
977
+ raise MemoryError()
978
+ c_ctxt.sax.startDocument = _initSaxDocument
979
+ return c_ctxt
980
+
981
+ @property
982
+ def error_log(self):
983
+ """The error log of the last parser run.
984
+ """
985
+ cdef _ParserContext context
986
+ context = self._getParserContext()
987
+ return context._error_log.copy()
988
+
989
+ @property
990
+ def resolvers(self):
991
+ """The custom resolver registry of this parser."""
992
+ return self._resolvers
993
+
994
+ @property
995
+ def version(self):
996
+ """The version of the underlying XML parser."""
997
+ return "libxml2 %d.%d.%d" % LIBXML_VERSION
998
+
999
+ def set_element_class_lookup(self, ElementClassLookup lookup = None):
1000
+ """set_element_class_lookup(self, lookup = None)
1001
+
1002
+ Set a lookup scheme for element classes generated from this parser.
1003
+
1004
+ Reset it by passing None or nothing.
1005
+ """
1006
+ self._class_lookup = lookup
1007
+
1008
+ cdef _BaseParser _copy(self):
1009
+ "Create a new parser with the same configuration."
1010
+ cdef _BaseParser parser
1011
+ parser = self.__class__()
1012
+ parser._parse_options = self._parse_options
1013
+ parser._for_html = self._for_html
1014
+ parser._remove_comments = self._remove_comments
1015
+ parser._remove_pis = self._remove_pis
1016
+ parser._strip_cdata = self._strip_cdata
1017
+ parser._filename = self._filename
1018
+ parser._resolvers = self._resolvers
1019
+ parser.target = self.target
1020
+ parser._class_lookup = self._class_lookup
1021
+ parser._default_encoding = self._default_encoding
1022
+ parser._schema = self._schema
1023
+ parser._events_to_collect = self._events_to_collect
1024
+ return parser
1025
+
1026
+ def copy(self):
1027
+ """copy(self)
1028
+
1029
+ Create a new parser with the same configuration.
1030
+ """
1031
+ return self._copy()
1032
+
1033
+ def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
1034
+ """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
1035
+
1036
+ Creates a new element associated with this parser.
1037
+ """
1038
+ return _makeElement(_tag, NULL, None, self, None, None,
1039
+ attrib, nsmap, _extra)
1040
+
1041
+ # internal parser methods
1042
+
1043
+ cdef xmlDoc* _parseUnicodeDoc(self, utext, char* c_filename) except NULL:
1044
+ """Parse unicode document, share dictionary if possible.
1045
+ """
1046
+ cdef _ParserContext context
1047
+ cdef xmlDoc* result
1048
+ cdef xmlparser.xmlParserCtxt* pctxt
1049
+ cdef Py_ssize_t py_buffer_len
1050
+ cdef int buffer_len, c_kind
1051
+ cdef const_char* c_text
1052
+ cdef const_char* c_encoding = _PY_UNICODE_ENCODING
1053
+ if python.PyUnicode_IS_READY(utext):
1054
+ # PEP-393 string
1055
+ c_text = <const_char*>python.PyUnicode_DATA(utext)
1056
+ py_buffer_len = python.PyUnicode_GET_LENGTH(utext)
1057
+ c_kind = python.PyUnicode_KIND(utext)
1058
+ if c_kind == 1:
1059
+ if python.PyUnicode_MAX_CHAR_VALUE(utext) <= 127:
1060
+ c_encoding = 'UTF-8'
1061
+ else:
1062
+ c_encoding = 'ISO-8859-1'
1063
+ elif c_kind == 2:
1064
+ py_buffer_len *= 2
1065
+ if python.PY_BIG_ENDIAN:
1066
+ c_encoding = 'UTF-16BE' # actually UCS-2
1067
+ else:
1068
+ c_encoding = 'UTF-16LE' # actually UCS-2
1069
+ elif c_kind == 4:
1070
+ py_buffer_len *= 4
1071
+ if python.PY_BIG_ENDIAN:
1072
+ c_encoding = 'UTF-32BE' # actually UCS-4
1073
+ else:
1074
+ c_encoding = 'UTF-32LE' # actually UCS-4
1075
+ else:
1076
+ assert False, f"Illegal Unicode kind {c_kind}"
1077
+ else:
1078
+ # old Py_UNICODE string
1079
+ py_buffer_len = python.PyUnicode_GET_DATA_SIZE(utext)
1080
+ c_text = python.PyUnicode_AS_DATA(utext)
1081
+ assert 0 <= py_buffer_len <= limits.INT_MAX
1082
+ buffer_len = py_buffer_len
1083
+
1084
+ context = self._getParserContext()
1085
+ context.prepare()
1086
+ try:
1087
+ pctxt = context._c_ctxt
1088
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1089
+ orig_options = pctxt.options
1090
+ with nogil:
1091
+ if self._for_html:
1092
+ result = htmlparser.htmlCtxtReadMemory(
1093
+ pctxt, c_text, buffer_len, c_filename, c_encoding,
1094
+ self._parse_options)
1095
+ if result is not NULL:
1096
+ if _fixHtmlDictNames(pctxt.dict, result) < 0:
1097
+ tree.xmlFreeDoc(result)
1098
+ result = NULL
1099
+ else:
1100
+ result = xmlparser.xmlCtxtReadMemory(
1101
+ pctxt, c_text, buffer_len, c_filename, c_encoding,
1102
+ self._parse_options)
1103
+ pctxt.options = orig_options # work around libxml2 problem
1104
+
1105
+ return context._handleParseResultDoc(self, result, None)
1106
+ finally:
1107
+ context.cleanup()
1108
+
1109
+ cdef xmlDoc* _parseDoc(self, char* c_text, int c_len,
1110
+ char* c_filename) except NULL:
1111
+ """Parse document, share dictionary if possible.
1112
+ """
1113
+ cdef _ParserContext context
1114
+ cdef xmlDoc* result
1115
+ cdef xmlparser.xmlParserCtxt* pctxt
1116
+ cdef char* c_encoding
1117
+ cdef tree.xmlCharEncoding enc
1118
+ context = self._getParserContext()
1119
+ context.prepare()
1120
+ try:
1121
+ pctxt = context._c_ctxt
1122
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1123
+
1124
+ if self._default_encoding is None:
1125
+ c_encoding = NULL
1126
+ # libxml2 (at least 2.9.3) does not recognise UTF-32 BOMs
1127
+ # NOTE: limit to problematic cases because it changes character offsets
1128
+ if c_len >= 4 and (c_text[0] == b'\xFF' and c_text[1] == b'\xFE' and
1129
+ c_text[2] == 0 and c_text[3] == 0):
1130
+ c_encoding = "UTF-32LE"
1131
+ c_text += 4
1132
+ c_len -= 4
1133
+ elif c_len >= 4 and (c_text[0] == 0 and c_text[1] == 0 and
1134
+ c_text[2] == b'\xFE' and c_text[3] == b'\xFF'):
1135
+ c_encoding = "UTF-32BE"
1136
+ c_text += 4
1137
+ c_len -= 4
1138
+ else:
1139
+ # no BOM => try to determine encoding
1140
+ enc = tree.xmlDetectCharEncoding(<const_xmlChar*>c_text, c_len)
1141
+ if enc == tree.XML_CHAR_ENCODING_UCS4LE:
1142
+ c_encoding = 'UTF-32LE'
1143
+ elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
1144
+ c_encoding = 'UTF-32BE'
1145
+ else:
1146
+ c_encoding = _cstr(self._default_encoding)
1147
+
1148
+ orig_options = pctxt.options
1149
+ with nogil:
1150
+ if self._for_html:
1151
+ result = htmlparser.htmlCtxtReadMemory(
1152
+ pctxt, c_text, c_len, c_filename,
1153
+ c_encoding, self._parse_options)
1154
+ if result is not NULL:
1155
+ if _fixHtmlDictNames(pctxt.dict, result) < 0:
1156
+ tree.xmlFreeDoc(result)
1157
+ result = NULL
1158
+ else:
1159
+ result = xmlparser.xmlCtxtReadMemory(
1160
+ pctxt, c_text, c_len, c_filename,
1161
+ c_encoding, self._parse_options)
1162
+ pctxt.options = orig_options # work around libxml2 problem
1163
+
1164
+ return context._handleParseResultDoc(self, result, None)
1165
+ finally:
1166
+ context.cleanup()
1167
+
1168
+ cdef xmlDoc* _parseDocFromFile(self, char* c_filename) except NULL:
1169
+ cdef _ParserContext context
1170
+ cdef xmlDoc* result
1171
+ cdef xmlparser.xmlParserCtxt* pctxt
1172
+ cdef char* c_encoding
1173
+ result = NULL
1174
+
1175
+ context = self._getParserContext()
1176
+ context.prepare()
1177
+ try:
1178
+ pctxt = context._c_ctxt
1179
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1180
+
1181
+ if self._default_encoding is None:
1182
+ c_encoding = NULL
1183
+ else:
1184
+ c_encoding = _cstr(self._default_encoding)
1185
+
1186
+ orig_options = pctxt.options
1187
+ with nogil:
1188
+ if self._for_html:
1189
+ result = htmlparser.htmlCtxtReadFile(
1190
+ pctxt, c_filename, c_encoding, self._parse_options)
1191
+ if result is not NULL:
1192
+ if _fixHtmlDictNames(pctxt.dict, result) < 0:
1193
+ tree.xmlFreeDoc(result)
1194
+ result = NULL
1195
+ else:
1196
+ result = xmlparser.xmlCtxtReadFile(
1197
+ pctxt, c_filename, c_encoding, self._parse_options)
1198
+ pctxt.options = orig_options # work around libxml2 problem
1199
+
1200
+ return context._handleParseResultDoc(self, result, c_filename)
1201
+ finally:
1202
+ context.cleanup()
1203
+
1204
+ cdef xmlDoc* _parseDocFromFilelike(self, filelike, filename,
1205
+ encoding) except NULL:
1206
+ cdef _ParserContext context
1207
+ cdef _FileReaderContext file_context
1208
+ cdef xmlDoc* result
1209
+ cdef xmlparser.xmlParserCtxt* pctxt
1210
+ cdef char* c_filename
1211
+ if not filename:
1212
+ filename = None
1213
+
1214
+ context = self._getParserContext()
1215
+ context.prepare()
1216
+ try:
1217
+ pctxt = context._c_ctxt
1218
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1219
+ file_context = _FileReaderContext(
1220
+ filelike, context, filename,
1221
+ encoding or self._default_encoding)
1222
+ result = file_context._readDoc(pctxt, self._parse_options)
1223
+
1224
+ return context._handleParseResultDoc(
1225
+ self, result, filename)
1226
+ finally:
1227
+ context.cleanup()
1228
+
1229
+
1230
+ cdef tree.xmlEntity* _getInternalEntityOnly(void* ctxt, const_xmlChar* name) noexcept nogil:
1231
+ """
1232
+ Callback function to intercept the entity resolution when external entity loading is disabled.
1233
+ """
1234
+ cdef tree.xmlEntity* entity = xmlparser.xmlSAX2GetEntity(ctxt, name)
1235
+ if not entity:
1236
+ return NULL
1237
+ if entity.etype not in (
1238
+ tree.xmlEntityType.XML_EXTERNAL_GENERAL_PARSED_ENTITY,
1239
+ tree.xmlEntityType.XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,
1240
+ tree.xmlEntityType.XML_EXTERNAL_PARAMETER_ENTITY):
1241
+ return entity
1242
+
1243
+ # Reject all external entities and fail the parsing instead. There is currently
1244
+ # no way in libxml2 to just prevent the entity resolution in this case.
1245
+ cdef xmlerror.xmlError c_error
1246
+ cdef xmlerror.xmlStructuredErrorFunc err_func
1247
+ cdef xmlparser.xmlParserInput* parser_input
1248
+ cdef void* err_context
1249
+
1250
+ c_ctxt = <xmlparser.xmlParserCtxt *> ctxt
1251
+ err_func = xmlerror.xmlStructuredError
1252
+ if err_func:
1253
+ parser_input = c_ctxt.input
1254
+ # Copied from xmlVErrParser() in libxml2: get current input from stack.
1255
+ if parser_input and parser_input.filename is NULL and c_ctxt.inputNr > 1:
1256
+ parser_input = c_ctxt.inputTab[c_ctxt.inputNr - 2]
1257
+
1258
+ c_error = xmlerror.xmlError(
1259
+ domain=xmlerror.xmlErrorDomain.XML_FROM_PARSER,
1260
+ code=xmlerror.xmlParserErrors.XML_ERR_EXT_ENTITY_STANDALONE,
1261
+ level=xmlerror.xmlErrorLevel.XML_ERR_FATAL,
1262
+ message=b"External entity resolution is disabled for security reasons "
1263
+ b"when resolving '&%s;'. Use 'XMLParser(resolve_entities=True)' "
1264
+ b"if you consider it safe to enable it.",
1265
+ file=parser_input.filename,
1266
+ node=entity,
1267
+ str1=<char*> name,
1268
+ str2=NULL,
1269
+ str3=NULL,
1270
+ line=parser_input.line if parser_input else 0,
1271
+ int1=0,
1272
+ int2=parser_input.col if parser_input else 0,
1273
+ )
1274
+ err_context = xmlerror.xmlStructuredErrorContext
1275
+ err_func(err_context, &c_error)
1276
+
1277
+ c_ctxt.wellFormed = 0
1278
+ # The entity was looked up and does not need to be freed.
1279
+ return NULL
1280
+
1281
+
1282
+ cdef void _initSaxDocument(void* ctxt) noexcept with gil:
1283
+ xmlparser.xmlSAX2StartDocument(ctxt)
1284
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
1285
+ c_doc = c_ctxt.myDoc
1286
+
1287
+ # set up document dict
1288
+ if c_doc and c_ctxt.dict and not c_doc.dict:
1289
+ # I have no idea why libxml2 disables this - we need it
1290
+ c_ctxt.dictNames = 1
1291
+ c_doc.dict = c_ctxt.dict
1292
+ xmlparser.xmlDictReference(c_ctxt.dict)
1293
+
1294
+ # set up XML ID hash table
1295
+ if c_ctxt._private:
1296
+ context = <_ParserContext>c_ctxt._private
1297
+ if context._collect_ids:
1298
+ # keep the global parser dict from filling up with XML IDs
1299
+ if c_doc and not c_doc.ids:
1300
+ # memory errors are not fatal here
1301
+ c_dict = xmlparser.xmlDictCreate()
1302
+ if c_dict:
1303
+ c_doc.ids = tree.xmlHashCreateDict(0, c_dict)
1304
+ xmlparser.xmlDictFree(c_dict)
1305
+ else:
1306
+ c_doc.ids = tree.xmlHashCreate(0)
1307
+ else:
1308
+ c_ctxt.loadsubset |= xmlparser.XML_SKIP_IDS
1309
+ if c_doc and c_doc.ids and not tree.xmlHashSize(c_doc.ids):
1310
+ # already initialised but empty => clear
1311
+ tree.xmlHashFree(c_doc.ids, NULL)
1312
+ c_doc.ids = NULL
1313
+
1314
+
1315
+ ############################################################
1316
+ ## ET feed parser
1317
+ ############################################################
1318
+
1319
+ cdef class _FeedParser(_BaseParser):
1320
+ cdef bint _feed_parser_running
1321
+
1322
+ @property
1323
+ def feed_error_log(self):
1324
+ """The error log of the last (or current) run of the feed parser.
1325
+
1326
+ Note that this is local to the feed parser and thus is
1327
+ different from what the ``error_log`` property returns.
1328
+ """
1329
+ return self._getPushParserContext()._error_log.copy()
1330
+
1331
+ cpdef feed(self, data):
1332
+ """feed(self, data)
1333
+
1334
+ Feeds data to the parser. The argument should be an 8-bit string
1335
+ buffer containing encoded data, although Unicode is supported as long
1336
+ as both string types are not mixed.
1337
+
1338
+ This is the main entry point to the consumer interface of a
1339
+ parser. The parser will parse as much of the XML stream as it
1340
+ can on each call. To finish parsing or to reset the parser,
1341
+ call the ``close()`` method. Both methods may raise
1342
+ ParseError if errors occur in the input data. If an error is
1343
+ raised, there is no longer a need to call ``close()``.
1344
+
1345
+ The feed parser interface is independent of the normal parser
1346
+ usage. You can use the same parser as a feed parser and in
1347
+ the ``parse()`` function concurrently.
1348
+ """
1349
+ cdef _ParserContext context
1350
+ cdef bytes bstring
1351
+ cdef xmlparser.xmlParserCtxt* pctxt
1352
+ cdef Py_ssize_t py_buffer_len, ustart
1353
+ cdef const_char* char_data
1354
+ cdef const_char* c_encoding
1355
+ cdef int buffer_len
1356
+ cdef int error
1357
+ cdef bint recover = self._parse_options & xmlparser.XML_PARSE_RECOVER
1358
+
1359
+ if isinstance(data, bytes):
1360
+ if self._default_encoding is None:
1361
+ c_encoding = NULL
1362
+ else:
1363
+ c_encoding = self._default_encoding
1364
+ char_data = _cstr(data)
1365
+ py_buffer_len = python.PyBytes_GET_SIZE(data)
1366
+ ustart = 0
1367
+ elif isinstance(data, unicode):
1368
+ c_encoding = b"UTF-8"
1369
+ char_data = NULL
1370
+ py_buffer_len = len(<unicode> data)
1371
+ ustart = 0
1372
+ else:
1373
+ raise TypeError, "Parsing requires string data"
1374
+
1375
+ context = self._getPushParserContext()
1376
+ pctxt = context._c_ctxt
1377
+ error = 0
1378
+ if not self._feed_parser_running:
1379
+ context.prepare(set_document_loader=False)
1380
+ self._feed_parser_running = 1
1381
+ c_filename = (_cstr(self._filename)
1382
+ if self._filename is not None else NULL)
1383
+
1384
+ # We have to give *mlCtxtResetPush() enough input to figure
1385
+ # out the character encoding (at least four bytes),
1386
+ # however if we give it all we got, we'll have nothing for
1387
+ # *mlParseChunk() and things go wrong.
1388
+ buffer_len = 0
1389
+ if char_data is not NULL:
1390
+ buffer_len = 4 if py_buffer_len > 4 else <int>py_buffer_len
1391
+ orig_loader = _register_document_loader()
1392
+ if self._for_html:
1393
+ error = _htmlCtxtResetPush(
1394
+ pctxt, char_data, buffer_len, c_filename, c_encoding,
1395
+ self._parse_options)
1396
+ else:
1397
+ xmlparser.xmlCtxtUseOptions(pctxt, self._parse_options)
1398
+ error = xmlparser.xmlCtxtResetPush(
1399
+ pctxt, char_data, buffer_len, c_filename, c_encoding)
1400
+ _reset_document_loader(orig_loader)
1401
+ py_buffer_len -= buffer_len
1402
+ char_data += buffer_len
1403
+ if error:
1404
+ raise MemoryError()
1405
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1406
+
1407
+ #print pctxt.charset, 'NONE' if c_encoding is NULL else c_encoding
1408
+
1409
+ fixup_error = 0
1410
+ while py_buffer_len > 0 and (error == 0 or recover):
1411
+ if char_data is NULL:
1412
+ # Unicode parsing by converting chunks to UTF-8
1413
+ buffer_len = 2**19 # len(bytes) <= 4 * (2**19) == 2 MiB
1414
+ bstring = (<unicode> data)[ustart : ustart+buffer_len].encode('UTF-8')
1415
+ ustart += buffer_len
1416
+ py_buffer_len -= buffer_len # may end up < 0
1417
+ error, fixup_error = _parse_data_chunk(pctxt, <const char*> bstring, <int> len(bstring))
1418
+ else:
1419
+ # Direct byte string parsing.
1420
+ buffer_len = <int>py_buffer_len if py_buffer_len <= limits.INT_MAX else limits.INT_MAX
1421
+ error, fixup_error = _parse_data_chunk(pctxt, char_data, buffer_len)
1422
+ py_buffer_len -= buffer_len
1423
+ char_data += buffer_len
1424
+
1425
+ if fixup_error:
1426
+ context.store_exception(MemoryError())
1427
+
1428
+ if context._has_raised():
1429
+ # propagate Python exceptions immediately
1430
+ recover = 0
1431
+ error = 1
1432
+ break
1433
+
1434
+ if error and not pctxt.replaceEntities and not pctxt.validate:
1435
+ # in this mode, we ignore errors about undefined entities
1436
+ for entry in context._error_log.filter_from_errors():
1437
+ if entry.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
1438
+ entry.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
1439
+ break
1440
+ else:
1441
+ error = 0
1442
+
1443
+ if not pctxt.wellFormed and pctxt.disableSAX and context._has_raised():
1444
+ # propagate Python exceptions immediately
1445
+ recover = 0
1446
+ error = 1
1447
+
1448
+ if fixup_error or not recover and (error or not pctxt.wellFormed):
1449
+ self._feed_parser_running = 0
1450
+ try:
1451
+ context._handleParseResult(self, pctxt.myDoc, None)
1452
+ finally:
1453
+ context.cleanup()
1454
+
1455
+ cpdef close(self):
1456
+ """close(self)
1457
+
1458
+ Terminates feeding data to this parser. This tells the parser to
1459
+ process any remaining data in the feed buffer, and then returns the
1460
+ root Element of the tree that was parsed.
1461
+
1462
+ This method must be called after passing the last chunk of data into
1463
+ the ``feed()`` method. It should only be called when using the feed
1464
+ parser interface, all other usage is undefined.
1465
+ """
1466
+ if not self._feed_parser_running:
1467
+ raise XMLSyntaxError("no element found",
1468
+ xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
1469
+ self._filename)
1470
+
1471
+ context = self._getPushParserContext()
1472
+ pctxt = context._c_ctxt
1473
+
1474
+ self._feed_parser_running = 0
1475
+ if self._for_html:
1476
+ htmlparser.htmlParseChunk(pctxt, NULL, 0, 1)
1477
+ else:
1478
+ xmlparser.xmlParseChunk(pctxt, NULL, 0, 1)
1479
+
1480
+ if (pctxt.recovery and not pctxt.disableSAX and
1481
+ isinstance(context, _SaxParserContext)):
1482
+ # apply any left-over 'end' events
1483
+ (<_SaxParserContext>context).flushEvents()
1484
+
1485
+ try:
1486
+ result = context._handleParseResult(self, pctxt.myDoc, None)
1487
+ finally:
1488
+ context.cleanup()
1489
+
1490
+ if isinstance(result, _Document):
1491
+ return (<_Document>result).getroot()
1492
+ else:
1493
+ return result
1494
+
1495
+
1496
+ cdef (int, int) _parse_data_chunk(xmlparser.xmlParserCtxt* c_ctxt,
1497
+ const char* char_data, int buffer_len):
1498
+ fixup_error = 0
1499
+ with nogil:
1500
+ if c_ctxt.html:
1501
+ c_node = c_ctxt.node # last node where the parser stopped
1502
+ orig_loader = _register_document_loader()
1503
+ error = htmlparser.htmlParseChunk(c_ctxt, char_data, buffer_len, 0)
1504
+ _reset_document_loader(orig_loader)
1505
+ # and now for the fun part: move node names to the dict
1506
+ if c_ctxt.myDoc:
1507
+ fixup_error = _fixHtmlDictSubtreeNames(
1508
+ c_ctxt.dict, c_ctxt.myDoc, c_node)
1509
+ if c_ctxt.myDoc.dict and c_ctxt.myDoc.dict is not c_ctxt.dict:
1510
+ xmlparser.xmlDictFree(c_ctxt.myDoc.dict)
1511
+ c_ctxt.myDoc.dict = c_ctxt.dict
1512
+ xmlparser.xmlDictReference(c_ctxt.dict)
1513
+ else:
1514
+ orig_loader = _register_document_loader()
1515
+ error = xmlparser.xmlParseChunk(c_ctxt, char_data, buffer_len, 0)
1516
+ _reset_document_loader(orig_loader)
1517
+ return (error, fixup_error)
1518
+
1519
+
1520
+ cdef int _htmlCtxtResetPush(xmlparser.xmlParserCtxt* c_ctxt,
1521
+ const_char* c_data, int buffer_len,
1522
+ const_char* c_filename, const_char* c_encoding,
1523
+ int parse_options) except -1:
1524
+ cdef xmlparser.xmlParserInput* c_input_stream
1525
+ # libxml2 lacks an HTML push parser setup function
1526
+ error = xmlparser.xmlCtxtResetPush(
1527
+ c_ctxt, c_data, buffer_len, c_filename, c_encoding)
1528
+ if error:
1529
+ return error
1530
+
1531
+ # fix libxml2 setup for HTML
1532
+ c_ctxt.progressive = 1
1533
+ c_ctxt.html = 1
1534
+ htmlparser.htmlCtxtUseOptions(c_ctxt, parse_options)
1535
+
1536
+ return 0
1537
+
1538
+
1539
+ ############################################################
1540
+ ## XML parser
1541
+ ############################################################
1542
+
1543
+ cdef int _XML_DEFAULT_PARSE_OPTIONS
1544
+ _XML_DEFAULT_PARSE_OPTIONS = (
1545
+ xmlparser.XML_PARSE_NOENT |
1546
+ xmlparser.XML_PARSE_NOCDATA |
1547
+ xmlparser.XML_PARSE_NONET |
1548
+ xmlparser.XML_PARSE_COMPACT |
1549
+ xmlparser.XML_PARSE_BIG_LINES
1550
+ )
1551
+
1552
+ cdef class XMLParser(_FeedParser):
1553
+ """XMLParser(self, encoding=None, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, schema: XMLSchema =None, huge_tree=False, remove_blank_text=False, resolve_entities=True, remove_comments=False, remove_pis=False, strip_cdata=True, collect_ids=True, target=None, compact=True)
1554
+
1555
+ The XML parser.
1556
+
1557
+ Parsers can be supplied as additional argument to various parse
1558
+ functions of the lxml API. A default parser is always available
1559
+ and can be replaced by a call to the global function
1560
+ 'set_default_parser'. New parsers can be created at any time
1561
+ without a major run-time overhead.
1562
+
1563
+ The keyword arguments in the constructor are mainly based on the
1564
+ libxml2 parser configuration. A DTD will also be loaded if DTD
1565
+ validation or attribute default values are requested (unless you
1566
+ additionally provide an XMLSchema from which the default
1567
+ attributes can be read).
1568
+
1569
+ Available boolean keyword arguments:
1570
+
1571
+ - attribute_defaults - inject default attributes from DTD or XMLSchema
1572
+ - dtd_validation - validate against a DTD referenced by the document
1573
+ - load_dtd - use DTD for parsing
1574
+ - no_network - prevent network access for related files (default: True)
1575
+ - ns_clean - clean up redundant namespace declarations
1576
+ - recover - try hard to parse through broken XML
1577
+ - remove_blank_text - discard blank text nodes that appear ignorable
1578
+ - remove_comments - discard comments
1579
+ - remove_pis - discard processing instructions
1580
+ - strip_cdata - replace CDATA sections by normal text content (default: True)
1581
+ - compact - save memory for short text content (default: True)
1582
+ - collect_ids - use a hash table of XML IDs for fast access (default: True, always True with DTD validation)
1583
+ - huge_tree - disable security restrictions and support very deep trees
1584
+ and very long text content (only affects libxml2 2.7+)
1585
+
1586
+ Other keyword arguments:
1587
+
1588
+ - resolve_entities - replace entities by their text value: False for keeping the
1589
+ entity references, True for resolving them, and 'internal' for resolving
1590
+ internal definitions only (no external file/URL access).
1591
+ The default used to be True and was changed to 'internal' in lxml 5.0.
1592
+ - encoding - override the document encoding (note: libiconv encoding name)
1593
+ - target - a parser target object that will receive the parse events
1594
+ - schema - an XMLSchema to validate against
1595
+
1596
+ Note that you should avoid sharing parsers between threads. While this is
1597
+ not harmful, it is more efficient to use separate parsers. This does not
1598
+ apply to the default parser.
1599
+ """
1600
+ def __init__(self, *, encoding=None, attribute_defaults=False,
1601
+ dtd_validation=False, load_dtd=False, no_network=True,
1602
+ ns_clean=False, recover=False, XMLSchema schema=None,
1603
+ huge_tree=False, remove_blank_text=False, resolve_entities='internal',
1604
+ remove_comments=False, remove_pis=False, strip_cdata=True,
1605
+ collect_ids=True, target=None, compact=True):
1606
+ cdef int parse_options
1607
+ cdef bint resolve_external = True
1608
+ parse_options = _XML_DEFAULT_PARSE_OPTIONS
1609
+ if load_dtd:
1610
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
1611
+ if dtd_validation:
1612
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDVALID | \
1613
+ xmlparser.XML_PARSE_DTDLOAD
1614
+ if attribute_defaults:
1615
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDATTR
1616
+ if schema is None:
1617
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
1618
+ if ns_clean:
1619
+ parse_options = parse_options | xmlparser.XML_PARSE_NSCLEAN
1620
+ if recover:
1621
+ parse_options = parse_options | xmlparser.XML_PARSE_RECOVER
1622
+ if remove_blank_text:
1623
+ parse_options = parse_options | xmlparser.XML_PARSE_NOBLANKS
1624
+ if huge_tree:
1625
+ parse_options = parse_options | xmlparser.XML_PARSE_HUGE
1626
+ if not no_network:
1627
+ parse_options = parse_options ^ xmlparser.XML_PARSE_NONET
1628
+ if not compact:
1629
+ parse_options = parse_options ^ xmlparser.XML_PARSE_COMPACT
1630
+ if not resolve_entities:
1631
+ parse_options = parse_options ^ xmlparser.XML_PARSE_NOENT
1632
+ elif resolve_entities == 'internal':
1633
+ resolve_external = False
1634
+ if not strip_cdata:
1635
+ parse_options = parse_options ^ xmlparser.XML_PARSE_NOCDATA
1636
+
1637
+ _BaseParser.__init__(self, parse_options, False, schema,
1638
+ remove_comments, remove_pis, strip_cdata,
1639
+ collect_ids, target, encoding, resolve_external)
1640
+
1641
+
1642
+ cdef class XMLPullParser(XMLParser):
1643
+ """XMLPullParser(self, events=None, *, tag=None, **kwargs)
1644
+
1645
+ XML parser that collects parse events in an iterator.
1646
+
1647
+ The collected events are the same as for iterparse(), but the
1648
+ parser itself is non-blocking in the sense that it receives
1649
+ data chunks incrementally through its .feed() method, instead
1650
+ of reading them directly from a file(-like) object all by itself.
1651
+
1652
+ By default, it collects Element end events. To change that,
1653
+ pass any subset of the available events into the ``events``
1654
+ argument: ``'start'``, ``'end'``, ``'start-ns'``,
1655
+ ``'end-ns'``, ``'comment'``, ``'pi'``.
1656
+
1657
+ To support loading external dependencies relative to the input
1658
+ source, you can pass the ``base_url``.
1659
+ """
1660
+ def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
1661
+ XMLParser.__init__(self, **kwargs)
1662
+ if events is None:
1663
+ events = ('end',)
1664
+ self._setBaseURL(base_url)
1665
+ self._collectEvents(events, tag)
1666
+
1667
+ def read_events(self):
1668
+ return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
1669
+
1670
+
1671
+ cdef class ETCompatXMLParser(XMLParser):
1672
+ """ETCompatXMLParser(self, encoding=None, attribute_defaults=False, \
1673
+ dtd_validation=False, load_dtd=False, no_network=True, \
1674
+ ns_clean=False, recover=False, schema=None, \
1675
+ huge_tree=False, remove_blank_text=False, resolve_entities=True, \
1676
+ remove_comments=True, remove_pis=True, strip_cdata=True, \
1677
+ target=None, compact=True)
1678
+
1679
+ An XML parser with an ElementTree compatible default setup.
1680
+
1681
+ See the XMLParser class for details.
1682
+
1683
+ This parser has ``remove_comments`` and ``remove_pis`` enabled by default
1684
+ and thus ignores comments and processing instructions.
1685
+ """
1686
+ def __init__(self, *, encoding=None, attribute_defaults=False,
1687
+ dtd_validation=False, load_dtd=False, no_network=True,
1688
+ ns_clean=False, recover=False, schema=None,
1689
+ huge_tree=False, remove_blank_text=False, resolve_entities=True,
1690
+ remove_comments=True, remove_pis=True, strip_cdata=True,
1691
+ target=None, compact=True):
1692
+ XMLParser.__init__(self,
1693
+ attribute_defaults=attribute_defaults,
1694
+ dtd_validation=dtd_validation,
1695
+ load_dtd=load_dtd,
1696
+ no_network=no_network,
1697
+ ns_clean=ns_clean,
1698
+ recover=recover,
1699
+ remove_blank_text=remove_blank_text,
1700
+ huge_tree=huge_tree,
1701
+ compact=compact,
1702
+ resolve_entities=resolve_entities,
1703
+ remove_comments=remove_comments,
1704
+ remove_pis=remove_pis,
1705
+ strip_cdata=strip_cdata,
1706
+ target=target,
1707
+ encoding=encoding,
1708
+ schema=schema)
1709
+
1710
+ # ET 1.2 compatible name
1711
+ XMLTreeBuilder = ETCompatXMLParser
1712
+
1713
+
1714
+ cdef XMLParser __DEFAULT_XML_PARSER
1715
+ __DEFAULT_XML_PARSER = XMLParser()
1716
+
1717
+ __GLOBAL_PARSER_CONTEXT.setDefaultParser(__DEFAULT_XML_PARSER)
1718
+
1719
+ def set_default_parser(_BaseParser parser=None):
1720
+ """set_default_parser(parser=None)
1721
+
1722
+ Set a default parser for the current thread. This parser is used
1723
+ globally whenever no parser is supplied to the various parse functions of
1724
+ the lxml API. If this function is called without a parser (or if it is
1725
+ None), the default parser is reset to the original configuration.
1726
+
1727
+ Note that the pre-installed default parser is not thread-safe. Avoid the
1728
+ default parser in multi-threaded environments. You can create a separate
1729
+ parser for each thread explicitly or use a parser pool.
1730
+ """
1731
+ if parser is None:
1732
+ parser = __DEFAULT_XML_PARSER
1733
+ __GLOBAL_PARSER_CONTEXT.setDefaultParser(parser)
1734
+
1735
+ def get_default_parser():
1736
+ "get_default_parser()"
1737
+ return __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1738
+
1739
+ ############################################################
1740
+ ## HTML parser
1741
+ ############################################################
1742
+
1743
+ cdef int _HTML_DEFAULT_PARSE_OPTIONS
1744
+ _HTML_DEFAULT_PARSE_OPTIONS = (
1745
+ htmlparser.HTML_PARSE_RECOVER |
1746
+ htmlparser.HTML_PARSE_NONET |
1747
+ htmlparser.HTML_PARSE_COMPACT
1748
+ )
1749
+
1750
+ cdef object _UNUSED = object()
1751
+
1752
+ cdef class HTMLParser(_FeedParser):
1753
+ """HTMLParser(self, encoding=None, remove_blank_text=False, \
1754
+ remove_comments=False, remove_pis=False, \
1755
+ no_network=True, target=None, schema: XMLSchema =None, \
1756
+ recover=True, compact=True, collect_ids=True, huge_tree=False)
1757
+
1758
+ The HTML parser.
1759
+
1760
+ This parser allows reading HTML into a normal XML tree. By
1761
+ default, it can read broken (non well-formed) HTML, depending on
1762
+ the capabilities of libxml2. Use the 'recover' option to switch
1763
+ this off.
1764
+
1765
+ Available boolean keyword arguments:
1766
+
1767
+ - recover - try hard to parse through broken HTML (default: True)
1768
+ - no_network - prevent network access for related files (default: True)
1769
+ - remove_blank_text - discard empty text nodes that are ignorable (i.e. not actual text content)
1770
+ - remove_comments - discard comments
1771
+ - remove_pis - discard processing instructions
1772
+ - compact - save memory for short text content (default: True)
1773
+ - default_doctype - add a default doctype even if it is not found in the HTML (default: True)
1774
+ - collect_ids - use a hash table of XML IDs for fast access (default: True)
1775
+ - huge_tree - disable security restrictions and support very deep trees
1776
+ and very long text content (only affects libxml2 2.7+)
1777
+
1778
+ Other keyword arguments:
1779
+
1780
+ - encoding - override the document encoding (note: libiconv encoding name)
1781
+ - target - a parser target object that will receive the parse events
1782
+ - schema - an XMLSchema to validate against
1783
+
1784
+ Note that you should avoid sharing parsers between threads for performance
1785
+ reasons.
1786
+ """
1787
+ def __init__(self, *, encoding=None, remove_blank_text=False,
1788
+ remove_comments=False, remove_pis=False, strip_cdata=_UNUSED,
1789
+ no_network=True, target=None, XMLSchema schema=None,
1790
+ recover=True, compact=True, default_doctype=True,
1791
+ collect_ids=True, huge_tree=False):
1792
+ cdef int parse_options
1793
+ parse_options = _HTML_DEFAULT_PARSE_OPTIONS
1794
+ if remove_blank_text:
1795
+ parse_options = parse_options | htmlparser.HTML_PARSE_NOBLANKS
1796
+ if not recover:
1797
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_RECOVER
1798
+ if not no_network:
1799
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_NONET
1800
+ if not compact:
1801
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_COMPACT
1802
+ if not default_doctype:
1803
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_NODEFDTD
1804
+ if huge_tree:
1805
+ parse_options = parse_options | xmlparser.XML_PARSE_HUGE
1806
+
1807
+ if strip_cdata is not _UNUSED:
1808
+ import warnings
1809
+ warnings.warn(
1810
+ "The 'strip_cdata' option of HTMLParser() has never done anything and will eventually be removed.",
1811
+ DeprecationWarning)
1812
+ _BaseParser.__init__(self, parse_options, True, schema,
1813
+ remove_comments, remove_pis, strip_cdata,
1814
+ collect_ids, target, encoding)
1815
+
1816
+
1817
+ cdef HTMLParser __DEFAULT_HTML_PARSER
1818
+ __DEFAULT_HTML_PARSER = HTMLParser()
1819
+
1820
+
1821
+ cdef class HTMLPullParser(HTMLParser):
1822
+ """HTMLPullParser(self, events=None, *, tag=None, base_url=None, **kwargs)
1823
+
1824
+ HTML parser that collects parse events in an iterator.
1825
+
1826
+ The collected events are the same as for iterparse(), but the
1827
+ parser itself is non-blocking in the sense that it receives
1828
+ data chunks incrementally through its .feed() method, instead
1829
+ of reading them directly from a file(-like) object all by itself.
1830
+
1831
+ By default, it collects Element end events. To change that,
1832
+ pass any subset of the available events into the ``events``
1833
+ argument: ``'start'``, ``'end'``, ``'start-ns'``,
1834
+ ``'end-ns'``, ``'comment'``, ``'pi'``.
1835
+
1836
+ To support loading external dependencies relative to the input
1837
+ source, you can pass the ``base_url``.
1838
+ """
1839
+ def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
1840
+ HTMLParser.__init__(self, **kwargs)
1841
+ if events is None:
1842
+ events = ('end',)
1843
+ self._setBaseURL(base_url)
1844
+ self._collectEvents(events, tag)
1845
+
1846
+ def read_events(self):
1847
+ return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
1848
+
1849
+
1850
+ ############################################################
1851
+ ## helper functions for document creation
1852
+ ############################################################
1853
+
1854
+ cdef xmlDoc* _parseDoc(text, filename, _BaseParser parser) except NULL:
1855
+ cdef char* c_filename
1856
+ cdef char* c_text
1857
+ cdef Py_ssize_t c_len
1858
+ if parser is None:
1859
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1860
+ if not filename:
1861
+ c_filename = NULL
1862
+ else:
1863
+ filename_utf = _encodeFilenameUTF8(filename)
1864
+ c_filename = _cstr(filename_utf)
1865
+ if isinstance(text, unicode):
1866
+ if python.PyUnicode_IS_READY(text):
1867
+ # PEP-393 Unicode string
1868
+ c_len = python.PyUnicode_GET_LENGTH(text) * python.PyUnicode_KIND(text)
1869
+ else:
1870
+ # old Py_UNICODE string
1871
+ c_len = python.PyUnicode_GET_DATA_SIZE(text)
1872
+ if c_len > limits.INT_MAX:
1873
+ return (<_BaseParser>parser)._parseDocFromFilelike(
1874
+ StringIO(text), filename, None)
1875
+ return (<_BaseParser>parser)._parseUnicodeDoc(text, c_filename)
1876
+ else:
1877
+ c_len = python.PyBytes_GET_SIZE(text)
1878
+ if c_len > limits.INT_MAX:
1879
+ return (<_BaseParser>parser)._parseDocFromFilelike(
1880
+ BytesIO(text), filename, None)
1881
+ c_text = _cstr(text)
1882
+ return (<_BaseParser>parser)._parseDoc(c_text, c_len, c_filename)
1883
+
1884
+ cdef xmlDoc* _parseDocFromFile(filename8, _BaseParser parser) except NULL:
1885
+ if parser is None:
1886
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1887
+ return (<_BaseParser>parser)._parseDocFromFile(_cstr(filename8))
1888
+
1889
+ cdef xmlDoc* _parseDocFromFilelike(source, filename,
1890
+ _BaseParser parser) except NULL:
1891
+ if parser is None:
1892
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1893
+ return (<_BaseParser>parser)._parseDocFromFilelike(source, filename, None)
1894
+
1895
+ cdef xmlDoc* _newXMLDoc() except NULL:
1896
+ cdef xmlDoc* result
1897
+ result = tree.xmlNewDoc(NULL)
1898
+ if result is NULL:
1899
+ raise MemoryError()
1900
+ if result.encoding is NULL:
1901
+ result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
1902
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
1903
+ return result
1904
+
1905
+ cdef xmlDoc* _newHTMLDoc() except NULL:
1906
+ cdef xmlDoc* result
1907
+ result = tree.htmlNewDoc(NULL, NULL)
1908
+ if result is NULL:
1909
+ raise MemoryError()
1910
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
1911
+ return result
1912
+
1913
+ cdef xmlDoc* _copyDoc(xmlDoc* c_doc, int recursive) except NULL:
1914
+ cdef xmlDoc* result
1915
+ if recursive:
1916
+ with nogil:
1917
+ result = tree.xmlCopyDoc(c_doc, recursive)
1918
+ else:
1919
+ result = tree.xmlCopyDoc(c_doc, 0)
1920
+ if result is NULL:
1921
+ raise MemoryError()
1922
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
1923
+ return result
1924
+
1925
+ cdef xmlDoc* _copyDocRoot(xmlDoc* c_doc, xmlNode* c_new_root) except NULL:
1926
+ "Recursively copy the document and make c_new_root the new root node."
1927
+ cdef xmlDoc* result
1928
+ cdef xmlNode* c_node
1929
+ result = tree.xmlCopyDoc(c_doc, 0) # non recursive
1930
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
1931
+ with nogil:
1932
+ c_node = tree.xmlDocCopyNode(c_new_root, result, 1) # recursive
1933
+ if c_node is NULL:
1934
+ raise MemoryError()
1935
+ tree.xmlDocSetRootElement(result, c_node)
1936
+ _copyTail(c_new_root.next, c_node)
1937
+ return result
1938
+
1939
+ cdef xmlNode* _copyNodeToDoc(xmlNode* c_node, xmlDoc* c_doc) except NULL:
1940
+ "Recursively copy the element into the document. c_doc is not modified."
1941
+ cdef xmlNode* c_root
1942
+ c_root = tree.xmlDocCopyNode(c_node, c_doc, 1) # recursive
1943
+ if c_root is NULL:
1944
+ raise MemoryError()
1945
+ _copyTail(c_node.next, c_root)
1946
+ return c_root
1947
+
1948
+
1949
+ ############################################################
1950
+ ## API level helper functions for _Document creation
1951
+ ############################################################
1952
+
1953
+ cdef _Document _parseDocument(source, _BaseParser parser, base_url):
1954
+ cdef _Document doc
1955
+ source = _getFSPathOrObject(source)
1956
+ if _isString(source):
1957
+ # parse the file directly from the filesystem
1958
+ doc = _parseDocumentFromURL(_encodeFilename(source), parser)
1959
+ # fix base URL if requested
1960
+ if base_url is not None:
1961
+ base_url = _encodeFilenameUTF8(base_url)
1962
+ if doc._c_doc.URL is not NULL:
1963
+ tree.xmlFree(<char*>doc._c_doc.URL)
1964
+ doc._c_doc.URL = tree.xmlStrdup(_xcstr(base_url))
1965
+ return doc
1966
+
1967
+ if base_url is not None:
1968
+ url = base_url
1969
+ else:
1970
+ url = _getFilenameForFile(source)
1971
+
1972
+ if hasattr(source, 'getvalue') and hasattr(source, 'tell'):
1973
+ # StringIO - reading from start?
1974
+ if source.tell() == 0:
1975
+ return _parseMemoryDocument(source.getvalue(), url, parser)
1976
+
1977
+ # Support for file-like objects (urlgrabber.urlopen, ...)
1978
+ if hasattr(source, 'read'):
1979
+ return _parseFilelikeDocument(source, url, parser)
1980
+
1981
+ raise TypeError, f"cannot parse from '{python._fqtypename(source).decode('UTF-8')}'"
1982
+
1983
+ cdef _Document _parseDocumentFromURL(url, _BaseParser parser):
1984
+ c_doc = _parseDocFromFile(url, parser)
1985
+ return _documentFactory(c_doc, parser)
1986
+
1987
+ cdef _Document _parseMemoryDocument(text, url, _BaseParser parser):
1988
+ if isinstance(text, unicode):
1989
+ if _hasEncodingDeclaration(text):
1990
+ raise ValueError(
1991
+ "Unicode strings with encoding declaration are not supported. "
1992
+ "Please use bytes input or XML fragments without declaration.")
1993
+ elif not isinstance(text, bytes):
1994
+ raise ValueError, "can only parse strings"
1995
+ c_doc = _parseDoc(text, url, parser)
1996
+ return _documentFactory(c_doc, parser)
1997
+
1998
+ cdef _Document _parseFilelikeDocument(source, url, _BaseParser parser):
1999
+ c_doc = _parseDocFromFilelike(source, url, parser)
2000
+ return _documentFactory(c_doc, parser)