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/extensions.pxi ADDED
@@ -0,0 +1,833 @@
1
+ # support for extension functions in XPath and XSLT
2
+
3
+ cdef class XPathError(LxmlError):
4
+ """Base class of all XPath errors.
5
+ """
6
+
7
+ cdef class XPathEvalError(XPathError):
8
+ """Error during XPath evaluation.
9
+ """
10
+
11
+ cdef class XPathFunctionError(XPathEvalError):
12
+ """Internal error looking up an XPath extension function.
13
+ """
14
+
15
+ cdef class XPathResultError(XPathEvalError):
16
+ """Error handling an XPath result.
17
+ """
18
+
19
+
20
+ # forward declarations
21
+
22
+ ctypedef int (*_register_function)(void* ctxt, name_utf, ns_uri_utf)
23
+ cdef class _ExsltRegExp
24
+
25
+ ################################################################################
26
+ # Base class for XSLT and XPath evaluation contexts: functions, namespaces, ...
27
+
28
+ @cython.internal
29
+ cdef class _BaseContext:
30
+ cdef xpath.xmlXPathContext* _xpathCtxt
31
+ cdef _Document _doc
32
+ cdef dict _extensions
33
+ cdef list _namespaces
34
+ cdef list _global_namespaces
35
+ cdef dict _utf_refs
36
+ cdef dict _function_cache
37
+ cdef dict _eval_context_dict
38
+ cdef bint _build_smart_strings
39
+ # for exception handling and temporary reference keeping:
40
+ cdef _TempStore _temp_refs
41
+ cdef set _temp_documents
42
+ cdef _ExceptionContext _exc
43
+ cdef _ErrorLog _error_log
44
+
45
+ def __cinit__(self):
46
+ self._xpathCtxt = NULL
47
+
48
+ def __init__(self, namespaces, extensions, error_log, enable_regexp,
49
+ build_smart_strings):
50
+ cdef _ExsltRegExp _regexp
51
+ cdef dict new_extensions
52
+ cdef list ns
53
+ self._utf_refs = {}
54
+ self._global_namespaces = []
55
+ self._function_cache = {}
56
+ self._eval_context_dict = None
57
+ self._error_log = error_log
58
+
59
+ if extensions is not None:
60
+ # convert extensions to UTF-8
61
+ if isinstance(extensions, dict):
62
+ extensions = (extensions,)
63
+ # format: [ {(ns, name):function} ] -> {(ns_utf, name_utf):function}
64
+ new_extensions = {}
65
+ for extension in extensions:
66
+ for (ns_uri, name), function in extension.items():
67
+ if name is None:
68
+ raise ValueError, "extensions must have non empty names"
69
+ ns_utf = self._to_utf(ns_uri)
70
+ name_utf = self._to_utf(name)
71
+ new_extensions[(ns_utf, name_utf)] = function
72
+ extensions = new_extensions or None
73
+
74
+ if namespaces is not None:
75
+ if isinstance(namespaces, dict):
76
+ namespaces = namespaces.items()
77
+ if namespaces:
78
+ ns = []
79
+ for prefix, ns_uri in namespaces:
80
+ if prefix is None or not prefix:
81
+ raise TypeError, \
82
+ "empty namespace prefix is not supported in XPath"
83
+ if ns_uri is None or not ns_uri:
84
+ raise TypeError, \
85
+ "setting default namespace is not supported in XPath"
86
+ prefix_utf = self._to_utf(prefix)
87
+ ns_uri_utf = self._to_utf(ns_uri)
88
+ ns.append( (prefix_utf, ns_uri_utf) )
89
+ namespaces = ns
90
+ else:
91
+ namespaces = None
92
+
93
+ self._doc = None
94
+ self._exc = _ExceptionContext()
95
+ self._extensions = extensions
96
+ self._namespaces = namespaces
97
+ self._temp_refs = _TempStore()
98
+ self._temp_documents = set()
99
+ self._build_smart_strings = build_smart_strings
100
+
101
+ if enable_regexp:
102
+ _regexp = _ExsltRegExp()
103
+ _regexp._register_in_context(self)
104
+
105
+ cdef _BaseContext _copy(self):
106
+ cdef _BaseContext context
107
+ if self._namespaces is not None:
108
+ namespaces = self._namespaces[:]
109
+ else:
110
+ namespaces = None
111
+ context = self.__class__(namespaces, None, self._error_log, False,
112
+ self._build_smart_strings)
113
+ if self._extensions is not None:
114
+ context._extensions = self._extensions.copy()
115
+ return context
116
+
117
+ cdef bytes _to_utf(self, s):
118
+ "Convert to UTF-8 and keep a reference to the encoded string"
119
+ cdef python.PyObject* dict_result
120
+ if s is None:
121
+ return None
122
+ dict_result = python.PyDict_GetItem(self._utf_refs, s)
123
+ if dict_result is not NULL:
124
+ return <bytes>dict_result
125
+ utf = _utf8(s)
126
+ self._utf_refs[s] = utf
127
+ if python.IS_PYPY:
128
+ # use C level refs, PyPy refs are not enough!
129
+ python.Py_INCREF(utf)
130
+ return utf
131
+
132
+ cdef void _set_xpath_context(self, xpath.xmlXPathContext* xpathCtxt) noexcept:
133
+ self._xpathCtxt = xpathCtxt
134
+ xpathCtxt.userData = <void*>self
135
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
136
+ xpathCtxt.error = <xmlerror.xmlStructuredErrorFunc> _receiveXPathError
137
+
138
+ @cython.final
139
+ cdef _register_context(self, _Document doc):
140
+ self._doc = doc
141
+ self._exc.clear()
142
+
143
+ @cython.final
144
+ cdef _cleanup_context(self):
145
+ #xpath.xmlXPathRegisteredNsCleanup(self._xpathCtxt)
146
+ #self.unregisterGlobalNamespaces()
147
+ if python.IS_PYPY:
148
+ # clean up double refs in PyPy (see "_to_utf()" method)
149
+ for ref in self._utf_refs.itervalues():
150
+ python.Py_DECREF(ref)
151
+ self._utf_refs.clear()
152
+ self._eval_context_dict = None
153
+ self._doc = None
154
+
155
+ @cython.final
156
+ cdef _release_context(self):
157
+ if self._xpathCtxt is not NULL:
158
+ self._xpathCtxt.userData = NULL
159
+ self._xpathCtxt = NULL
160
+
161
+ # namespaces (internal UTF-8 methods with leading '_')
162
+
163
+ cdef addNamespace(self, prefix, ns_uri):
164
+ cdef list namespaces
165
+ if prefix is None:
166
+ raise TypeError, "empty prefix is not supported in XPath"
167
+ prefix_utf = self._to_utf(prefix)
168
+ ns_uri_utf = self._to_utf(ns_uri)
169
+ new_item = (prefix_utf, ns_uri_utf)
170
+ if self._namespaces is None:
171
+ self._namespaces = [new_item]
172
+ else:
173
+ namespaces = []
174
+ for item in self._namespaces:
175
+ if item[0] == prefix_utf:
176
+ item = new_item
177
+ new_item = None
178
+ namespaces.append(item)
179
+ if new_item is not None:
180
+ namespaces.append(new_item)
181
+ self._namespaces = namespaces
182
+ if self._xpathCtxt is not NULL:
183
+ xpath.xmlXPathRegisterNs(
184
+ self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf))
185
+
186
+ cdef registerNamespace(self, prefix, ns_uri):
187
+ if prefix is None:
188
+ raise TypeError, "empty prefix is not supported in XPath"
189
+ prefix_utf = self._to_utf(prefix)
190
+ ns_uri_utf = self._to_utf(ns_uri)
191
+ self._global_namespaces.append(prefix_utf)
192
+ xpath.xmlXPathRegisterNs(self._xpathCtxt,
193
+ _xcstr(prefix_utf), _xcstr(ns_uri_utf))
194
+
195
+ cdef registerLocalNamespaces(self):
196
+ if self._namespaces is None:
197
+ return
198
+ for prefix_utf, ns_uri_utf in self._namespaces:
199
+ xpath.xmlXPathRegisterNs(
200
+ self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf))
201
+
202
+ cdef registerGlobalNamespaces(self):
203
+ cdef list ns_prefixes = _find_all_extension_prefixes()
204
+ if python.PyList_GET_SIZE(ns_prefixes) > 0:
205
+ for prefix_utf, ns_uri_utf in ns_prefixes:
206
+ self._global_namespaces.append(prefix_utf)
207
+ xpath.xmlXPathRegisterNs(
208
+ self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf))
209
+
210
+ cdef unregisterGlobalNamespaces(self):
211
+ if python.PyList_GET_SIZE(self._global_namespaces) > 0:
212
+ for prefix_utf in self._global_namespaces:
213
+ xpath.xmlXPathRegisterNs(self._xpathCtxt,
214
+ _xcstr(prefix_utf), NULL)
215
+ del self._global_namespaces[:]
216
+
217
+ cdef void _unregisterNamespace(self, prefix_utf) noexcept:
218
+ xpath.xmlXPathRegisterNs(self._xpathCtxt,
219
+ _xcstr(prefix_utf), NULL)
220
+
221
+ # extension functions
222
+
223
+ cdef int _addLocalExtensionFunction(self, ns_utf, name_utf, function) except -1:
224
+ if self._extensions is None:
225
+ self._extensions = {}
226
+ self._extensions[(ns_utf, name_utf)] = function
227
+ return 0
228
+
229
+ cdef registerGlobalFunctions(self, void* ctxt,
230
+ _register_function reg_func):
231
+ cdef python.PyObject* dict_result
232
+ cdef dict d
233
+ for ns_utf, ns_functions in __FUNCTION_NAMESPACE_REGISTRIES.iteritems():
234
+ dict_result = python.PyDict_GetItem(
235
+ self._function_cache, ns_utf)
236
+ if dict_result is not NULL:
237
+ d = <dict>dict_result
238
+ else:
239
+ d = {}
240
+ self._function_cache[ns_utf] = d
241
+ for name_utf, function in ns_functions.iteritems():
242
+ d[name_utf] = function
243
+ reg_func(ctxt, name_utf, ns_utf)
244
+
245
+ cdef registerLocalFunctions(self, void* ctxt,
246
+ _register_function reg_func):
247
+ cdef python.PyObject* dict_result
248
+ cdef dict d
249
+ if self._extensions is None:
250
+ return # done
251
+ last_ns = None
252
+ d = None
253
+ for (ns_utf, name_utf), function in self._extensions.iteritems():
254
+ if ns_utf is not last_ns or d is None:
255
+ last_ns = ns_utf
256
+ dict_result = python.PyDict_GetItem(
257
+ self._function_cache, ns_utf)
258
+ if dict_result is not NULL:
259
+ d = <dict>dict_result
260
+ else:
261
+ d = {}
262
+ self._function_cache[ns_utf] = d
263
+ d[name_utf] = function
264
+ reg_func(ctxt, name_utf, ns_utf)
265
+
266
+ cdef unregisterAllFunctions(self, void* ctxt,
267
+ _register_function unreg_func):
268
+ for ns_utf, functions in self._function_cache.iteritems():
269
+ for name_utf in functions:
270
+ unreg_func(ctxt, name_utf, ns_utf)
271
+
272
+ cdef unregisterGlobalFunctions(self, void* ctxt,
273
+ _register_function unreg_func):
274
+ for ns_utf, functions in self._function_cache.items():
275
+ for name_utf in functions:
276
+ if self._extensions is None or \
277
+ (ns_utf, name_utf) not in self._extensions:
278
+ unreg_func(ctxt, name_utf, ns_utf)
279
+
280
+ @cython.final
281
+ cdef _find_cached_function(self, const_xmlChar* c_ns_uri, const_xmlChar* c_name):
282
+ """Lookup an extension function in the cache and return it.
283
+
284
+ Parameters: c_ns_uri may be NULL, c_name must not be NULL
285
+ """
286
+ cdef python.PyObject* c_dict
287
+ cdef python.PyObject* dict_result
288
+ c_dict = python.PyDict_GetItem(
289
+ self._function_cache, None if c_ns_uri is NULL else c_ns_uri)
290
+ if c_dict is not NULL:
291
+ dict_result = python.PyDict_GetItem(
292
+ <object>c_dict, <unsigned char*>c_name)
293
+ if dict_result is not NULL:
294
+ return <object>dict_result
295
+ return None
296
+
297
+ # Python access to the XPath context for extension functions
298
+
299
+ @property
300
+ def context_node(self):
301
+ cdef xmlNode* c_node
302
+ if self._xpathCtxt is NULL:
303
+ raise XPathError, \
304
+ "XPath context is only usable during the evaluation"
305
+ c_node = self._xpathCtxt.node
306
+ if c_node is NULL:
307
+ raise XPathError, "no context node"
308
+ if c_node.doc != self._xpathCtxt.doc:
309
+ raise XPathError, \
310
+ "document-external context nodes are not supported"
311
+ if self._doc is None:
312
+ raise XPathError, "document context is missing"
313
+ return _elementFactory(self._doc, c_node)
314
+
315
+ @property
316
+ def eval_context(self):
317
+ if self._eval_context_dict is None:
318
+ self._eval_context_dict = {}
319
+ return self._eval_context_dict
320
+
321
+ # Python reference keeping during XPath function evaluation
322
+
323
+ @cython.final
324
+ cdef _release_temp_refs(self):
325
+ "Free temporarily referenced objects from this context."
326
+ self._temp_refs.clear()
327
+ self._temp_documents.clear()
328
+
329
+ @cython.final
330
+ cdef _hold(self, obj):
331
+ """A way to temporarily hold references to nodes in the evaluator.
332
+
333
+ This is needed because otherwise nodes created in XPath extension
334
+ functions would be reference counted too soon, during the XPath
335
+ evaluation. This is most important in the case of exceptions.
336
+ """
337
+ cdef _Element element
338
+ if isinstance(obj, _Element):
339
+ self._temp_refs.add(obj)
340
+ self._temp_documents.add((<_Element>obj)._doc)
341
+ return
342
+ elif _isString(obj) or not python.PySequence_Check(obj):
343
+ return
344
+ for o in obj:
345
+ if isinstance(o, _Element):
346
+ #print "Holding element:", <int>element._c_node
347
+ self._temp_refs.add(o)
348
+ #print "Holding document:", <int>element._doc._c_doc
349
+ self._temp_documents.add((<_Element>o)._doc)
350
+
351
+ @cython.final
352
+ cdef _Document _findDocumentForNode(self, xmlNode* c_node):
353
+ """If an XPath expression returns an element from a different
354
+ document than the current context document, we call this to
355
+ see if it was possibly created by an extension and is a known
356
+ document instance.
357
+ """
358
+ cdef _Document doc
359
+ for doc in self._temp_documents:
360
+ if doc is not None and doc._c_doc is c_node.doc:
361
+ return doc
362
+ return None
363
+
364
+
365
+ # libxml2 keeps these error messages in a static array in its code
366
+ # and doesn't give us access to them ...
367
+
368
+ cdef tuple LIBXML2_XPATH_ERROR_MESSAGES = (
369
+ b"Ok",
370
+ b"Number encoding",
371
+ b"Unfinished literal",
372
+ b"Start of literal",
373
+ b"Expected $ for variable reference",
374
+ b"Undefined variable",
375
+ b"Invalid predicate",
376
+ b"Invalid expression",
377
+ b"Missing closing curly brace",
378
+ b"Unregistered function",
379
+ b"Invalid operand",
380
+ b"Invalid type",
381
+ b"Invalid number of arguments",
382
+ b"Invalid context size",
383
+ b"Invalid context position",
384
+ b"Memory allocation error",
385
+ b"Syntax error",
386
+ b"Resource error",
387
+ b"Sub resource error",
388
+ b"Undefined namespace prefix",
389
+ b"Encoding error",
390
+ b"Char out of XML range",
391
+ b"Invalid or incomplete context",
392
+ b"Stack usage error",
393
+ b"Forbidden variable\n",
394
+ b"?? Unknown error ??\n",
395
+ )
396
+
397
+ cdef void _forwardXPathError(void* c_ctxt, const xmlerror.xmlError* c_error) noexcept with gil:
398
+ cdef xmlerror.xmlError error
399
+ cdef int xpath_code
400
+ if c_error.message is not NULL:
401
+ error.message = c_error.message
402
+ else:
403
+ xpath_code = c_error.code - xmlerror.XML_XPATH_EXPRESSION_OK
404
+ if 0 <= xpath_code < len(LIBXML2_XPATH_ERROR_MESSAGES):
405
+ error.message = _cstr(LIBXML2_XPATH_ERROR_MESSAGES[xpath_code])
406
+ else:
407
+ error.message = b"unknown error"
408
+ error.domain = c_error.domain
409
+ error.code = c_error.code
410
+ error.level = c_error.level
411
+ error.line = c_error.line
412
+ error.int2 = c_error.int1 # column
413
+ error.file = c_error.file
414
+ error.node = NULL
415
+
416
+ (<_BaseContext>c_ctxt)._error_log._receive(&error)
417
+
418
+ cdef void _receiveXPathError(void* c_context, const xmlerror.xmlError* error) noexcept nogil:
419
+ if not __DEBUG:
420
+ return
421
+ if c_context is NULL:
422
+ _forwardError(NULL, error)
423
+ else:
424
+ _forwardXPathError(c_context, error)
425
+
426
+
427
+ def Extension(module, function_mapping=None, *, ns=None):
428
+ """Extension(module, function_mapping=None, ns=None)
429
+
430
+ Build a dictionary of extension functions from the functions
431
+ defined in a module or the methods of an object.
432
+
433
+ As second argument, you can pass an additional mapping of
434
+ attribute names to XPath function names, or a list of function
435
+ names that should be taken.
436
+
437
+ The ``ns`` keyword argument accepts a namespace URI for the XPath
438
+ functions.
439
+ """
440
+ cdef dict functions = {}
441
+ if isinstance(function_mapping, dict):
442
+ for function_name, xpath_name in function_mapping.items():
443
+ functions[(ns, xpath_name)] = getattr(module, function_name)
444
+ else:
445
+ if function_mapping is None:
446
+ function_mapping = [ name for name in dir(module)
447
+ if not name.startswith('_') ]
448
+ for function_name in function_mapping:
449
+ functions[(ns, function_name)] = getattr(module, function_name)
450
+ return functions
451
+
452
+ ################################################################################
453
+ # EXSLT regexp implementation
454
+
455
+ @cython.final
456
+ @cython.internal
457
+ cdef class _ExsltRegExp:
458
+ cdef dict _compile_map
459
+ def __cinit__(self):
460
+ self._compile_map = {}
461
+
462
+ cdef _make_string(self, value):
463
+ if _isString(value):
464
+ return value
465
+ elif isinstance(value, list):
466
+ # node set: take recursive text concatenation of first element
467
+ if python.PyList_GET_SIZE(value) == 0:
468
+ return ''
469
+ firstnode = value[0]
470
+ if _isString(firstnode):
471
+ return firstnode
472
+ elif isinstance(firstnode, _Element):
473
+ c_text = tree.xmlNodeGetContent((<_Element>firstnode)._c_node)
474
+ if c_text is NULL:
475
+ raise MemoryError()
476
+ try:
477
+ return funicode(c_text)
478
+ finally:
479
+ tree.xmlFree(c_text)
480
+ else:
481
+ return unicode(firstnode)
482
+ else:
483
+ return unicode(value)
484
+
485
+ cdef _compile(self, rexp, ignore_case):
486
+ cdef python.PyObject* c_result
487
+ rexp = self._make_string(rexp)
488
+ key = (rexp, ignore_case)
489
+ c_result = python.PyDict_GetItem(self._compile_map, key)
490
+ if c_result is not NULL:
491
+ return <object>c_result
492
+ py_flags = re.UNICODE
493
+ if ignore_case:
494
+ py_flags = py_flags | re.IGNORECASE
495
+ rexp_compiled = re.compile(rexp, py_flags)
496
+ self._compile_map[key] = rexp_compiled
497
+ return rexp_compiled
498
+
499
+ def test(self, ctxt, s, rexp, flags=''):
500
+ flags = self._make_string(flags)
501
+ s = self._make_string(s)
502
+ rexpc = self._compile(rexp, 'i' in flags)
503
+ if rexpc.search(s) is None:
504
+ return False
505
+ else:
506
+ return True
507
+
508
+ def match(self, ctxt, s, rexp, flags=''):
509
+ cdef list result_list
510
+ flags = self._make_string(flags)
511
+ s = self._make_string(s)
512
+ rexpc = self._compile(rexp, 'i' in flags)
513
+ if 'g' in flags:
514
+ results = rexpc.findall(s)
515
+ if not results:
516
+ return ()
517
+ else:
518
+ result = rexpc.search(s)
519
+ if not result:
520
+ return ()
521
+ results = [ result.group() ]
522
+ results.extend( result.groups('') )
523
+ result_list = []
524
+ root = Element('matches')
525
+ for s_match in results:
526
+ if python.PyTuple_CheckExact(s_match):
527
+ s_match = ''.join(s_match)
528
+ elem = SubElement(root, 'match')
529
+ elem.text = s_match
530
+ result_list.append(elem)
531
+ return result_list
532
+
533
+ def replace(self, ctxt, s, rexp, flags, replacement):
534
+ replacement = self._make_string(replacement)
535
+ flags = self._make_string(flags)
536
+ s = self._make_string(s)
537
+ rexpc = self._compile(rexp, 'i' in flags)
538
+ count: object = 0 if 'g' in flags else 1
539
+ return rexpc.sub(replacement, s, count)
540
+
541
+ cdef _register_in_context(self, _BaseContext context):
542
+ ns = b"http://exslt.org/regular-expressions"
543
+ context._addLocalExtensionFunction(ns, b"test", self.test)
544
+ context._addLocalExtensionFunction(ns, b"match", self.match)
545
+ context._addLocalExtensionFunction(ns, b"replace", self.replace)
546
+
547
+
548
+ ################################################################################
549
+ # helper functions
550
+
551
+ cdef xpath.xmlXPathObject* _wrapXPathObject(object obj, _Document doc,
552
+ _BaseContext context) except NULL:
553
+ cdef xpath.xmlNodeSet* resultSet
554
+ cdef _Element fake_node = None
555
+ cdef xmlNode* c_node
556
+
557
+ if isinstance(obj, unicode):
558
+ obj = _utf8(obj)
559
+ if isinstance(obj, bytes):
560
+ # libxml2 copies the string value
561
+ return xpath.xmlXPathNewCString(_cstr(obj))
562
+ if isinstance(obj, bool):
563
+ return xpath.xmlXPathNewBoolean(obj)
564
+ if python.PyNumber_Check(obj):
565
+ return xpath.xmlXPathNewFloat(obj)
566
+ if obj is None:
567
+ resultSet = xpath.xmlXPathNodeSetCreate(NULL)
568
+ elif isinstance(obj, _Element):
569
+ resultSet = xpath.xmlXPathNodeSetCreate((<_Element>obj)._c_node)
570
+ elif python.PySequence_Check(obj):
571
+ resultSet = xpath.xmlXPathNodeSetCreate(NULL)
572
+ try:
573
+ for value in obj:
574
+ if isinstance(value, _Element):
575
+ if context is not None:
576
+ context._hold(value)
577
+ xpath.xmlXPathNodeSetAdd(resultSet, (<_Element>value)._c_node)
578
+ else:
579
+ if context is None or doc is None:
580
+ raise XPathResultError, \
581
+ f"Non-Element values not supported at this point - got {value!r}"
582
+ # support strings by appending text nodes to an Element
583
+ if isinstance(value, unicode):
584
+ value = _utf8(value)
585
+ if isinstance(value, bytes):
586
+ if fake_node is None:
587
+ fake_node = _makeElement("text-root", NULL, doc, None,
588
+ None, None, None, None, None)
589
+ context._hold(fake_node)
590
+ else:
591
+ # append a comment node to keep the text nodes separate
592
+ c_node = tree.xmlNewDocComment(doc._c_doc, <unsigned char*>"")
593
+ if c_node is NULL:
594
+ raise MemoryError()
595
+ tree.xmlAddChild(fake_node._c_node, c_node)
596
+ context._hold(value)
597
+ c_node = tree.xmlNewDocText(doc._c_doc, _xcstr(value))
598
+ if c_node is NULL:
599
+ raise MemoryError()
600
+ tree.xmlAddChild(fake_node._c_node, c_node)
601
+ xpath.xmlXPathNodeSetAdd(resultSet, c_node)
602
+ else:
603
+ raise XPathResultError, \
604
+ f"This is not a supported node-set result: {value!r}"
605
+ except:
606
+ xpath.xmlXPathFreeNodeSet(resultSet)
607
+ raise
608
+ else:
609
+ raise XPathResultError, f"Unknown return type: {python._fqtypename(obj).decode('utf8')}"
610
+ return xpath.xmlXPathWrapNodeSet(resultSet)
611
+
612
+ cdef object _unwrapXPathObject(xpath.xmlXPathObject* xpathObj,
613
+ _Document doc, _BaseContext context):
614
+ if xpathObj.type == xpath.XPATH_UNDEFINED:
615
+ raise XPathResultError, "Undefined xpath result"
616
+ elif xpathObj.type == xpath.XPATH_NODESET:
617
+ return _createNodeSetResult(xpathObj, doc, context)
618
+ elif xpathObj.type == xpath.XPATH_BOOLEAN:
619
+ return xpathObj.boolval
620
+ elif xpathObj.type == xpath.XPATH_NUMBER:
621
+ return xpathObj.floatval
622
+ elif xpathObj.type == xpath.XPATH_STRING:
623
+ stringval = funicode(xpathObj.stringval)
624
+ if context._build_smart_strings:
625
+ stringval = _elementStringResultFactory(
626
+ stringval, None, None, False)
627
+ return stringval
628
+ elif xpathObj.type == xpath.XPATH_POINT:
629
+ raise NotImplementedError, "XPATH_POINT"
630
+ elif xpathObj.type == xpath.XPATH_RANGE:
631
+ raise NotImplementedError, "XPATH_RANGE"
632
+ elif xpathObj.type == xpath.XPATH_LOCATIONSET:
633
+ raise NotImplementedError, "XPATH_LOCATIONSET"
634
+ elif xpathObj.type == xpath.XPATH_USERS:
635
+ raise NotImplementedError, "XPATH_USERS"
636
+ elif xpathObj.type == xpath.XPATH_XSLT_TREE:
637
+ return _createNodeSetResult(xpathObj, doc, context)
638
+ else:
639
+ raise XPathResultError, f"Unknown xpath result {xpathObj.type}"
640
+
641
+ cdef object _createNodeSetResult(xpath.xmlXPathObject* xpathObj, _Document doc,
642
+ _BaseContext context):
643
+ cdef xmlNode* c_node
644
+ cdef int i
645
+ cdef list result
646
+ result = []
647
+ if xpathObj.nodesetval is NULL:
648
+ return result
649
+ for i in range(xpathObj.nodesetval.nodeNr):
650
+ c_node = xpathObj.nodesetval.nodeTab[i]
651
+ _unpackNodeSetEntry(result, c_node, doc, context,
652
+ xpathObj.type == xpath.XPATH_XSLT_TREE)
653
+ return result
654
+
655
+ cdef _unpackNodeSetEntry(list results, xmlNode* c_node, _Document doc,
656
+ _BaseContext context, bint is_fragment):
657
+ cdef xmlNode* c_child
658
+ if _isElement(c_node):
659
+ if c_node.doc != doc._c_doc and c_node.doc._private is NULL:
660
+ # XXX: works, but maybe not always the right thing to do?
661
+ # XPath: only runs when extensions create or copy trees
662
+ # -> we store Python refs to these, so that is OK
663
+ # XSLT: can it leak when merging trees from multiple sources?
664
+ c_node = tree.xmlDocCopyNode(c_node, doc._c_doc, 1)
665
+ # FIXME: call _instantiateElementFromXPath() instead?
666
+ results.append(
667
+ _fakeDocElementFactory(doc, c_node))
668
+ elif c_node.type == tree.XML_TEXT_NODE or \
669
+ c_node.type == tree.XML_CDATA_SECTION_NODE or \
670
+ c_node.type == tree.XML_ATTRIBUTE_NODE:
671
+ results.append(
672
+ _buildElementStringResult(doc, c_node, context))
673
+ elif c_node.type == tree.XML_NAMESPACE_DECL:
674
+ results.append( (funicodeOrNone((<xmlNs*>c_node).prefix),
675
+ funicodeOrNone((<xmlNs*>c_node).href)) )
676
+ elif c_node.type == tree.XML_DOCUMENT_NODE or \
677
+ c_node.type == tree.XML_HTML_DOCUMENT_NODE:
678
+ # ignored for everything but result tree fragments
679
+ if is_fragment:
680
+ c_child = c_node.children
681
+ while c_child is not NULL:
682
+ _unpackNodeSetEntry(results, c_child, doc, context, 0)
683
+ c_child = c_child.next
684
+ elif c_node.type == tree.XML_XINCLUDE_START or \
685
+ c_node.type == tree.XML_XINCLUDE_END:
686
+ pass
687
+ else:
688
+ raise NotImplementedError, \
689
+ f"Not yet implemented result node type: {c_node.type}"
690
+
691
+ cdef void _freeXPathObject(xpath.xmlXPathObject* xpathObj) noexcept:
692
+ """Free the XPath object, but *never* free the *content* of node sets.
693
+ Python dealloc will do that for us.
694
+ """
695
+ if xpathObj.nodesetval is not NULL:
696
+ xpath.xmlXPathFreeNodeSet(xpathObj.nodesetval)
697
+ xpathObj.nodesetval = NULL
698
+ xpath.xmlXPathFreeObject(xpathObj)
699
+
700
+ cdef _Element _instantiateElementFromXPath(xmlNode* c_node, _Document doc,
701
+ _BaseContext context):
702
+ # NOTE: this may copy the element - only call this when it can't leak
703
+ if c_node.doc != doc._c_doc and c_node.doc._private is NULL:
704
+ # not from the context document and not from a fake document
705
+ # either => may still be from a known document, e.g. one
706
+ # created by an extension function
707
+ node_doc = context._findDocumentForNode(c_node)
708
+ if node_doc is None:
709
+ # not from a known document at all! => can only make a
710
+ # safety copy here
711
+ c_node = tree.xmlDocCopyNode(c_node, doc._c_doc, 1)
712
+ else:
713
+ doc = node_doc
714
+ return _fakeDocElementFactory(doc, c_node)
715
+
716
+ ################################################################################
717
+ # special str/unicode subclasses
718
+
719
+ @cython.final
720
+ cdef class _ElementUnicodeResult(unicode):
721
+ cdef _Element _parent
722
+ cdef readonly object attrname
723
+ cdef readonly bint is_tail
724
+
725
+ def getparent(self):
726
+ return self._parent
727
+
728
+ @property
729
+ def is_text(self):
730
+ return self._parent is not None and not (self.is_tail or self.attrname is not None)
731
+
732
+ @property
733
+ def is_attribute(self):
734
+ return self.attrname is not None
735
+
736
+ cdef object _elementStringResultFactory(string_value, _Element parent,
737
+ attrname, bint is_tail):
738
+ result = _ElementUnicodeResult(string_value)
739
+ result._parent = parent
740
+ result.is_tail = is_tail
741
+ result.attrname = attrname
742
+ return result
743
+
744
+ cdef object _buildElementStringResult(_Document doc, xmlNode* c_node,
745
+ _BaseContext context):
746
+ cdef _Element parent = None
747
+ cdef object attrname = None
748
+ cdef xmlNode* c_element
749
+ cdef bint is_tail
750
+
751
+ if c_node.type == tree.XML_ATTRIBUTE_NODE:
752
+ attrname = _namespacedName(c_node)
753
+ is_tail = 0
754
+ s = tree.xmlNodeGetContent(c_node)
755
+ try:
756
+ value = funicode(s)
757
+ finally:
758
+ tree.xmlFree(s)
759
+ c_element = NULL
760
+ else:
761
+ #assert c_node.type == tree.XML_TEXT_NODE or c_node.type == tree.XML_CDATA_SECTION_NODE, "invalid node type"
762
+ # may be tail text or normal text
763
+ value = funicode(c_node.content)
764
+ c_element = _previousElement(c_node)
765
+ is_tail = c_element is not NULL
766
+
767
+ if not context._build_smart_strings:
768
+ return value
769
+
770
+ if c_element is NULL:
771
+ # non-tail text or attribute text
772
+ c_element = c_node.parent
773
+ while c_element is not NULL and not _isElement(c_element):
774
+ c_element = c_element.parent
775
+
776
+ if c_element is not NULL:
777
+ parent = _instantiateElementFromXPath(c_element, doc, context)
778
+
779
+ return _elementStringResultFactory(
780
+ value, parent, attrname, is_tail)
781
+
782
+ ################################################################################
783
+ # callbacks for XPath/XSLT extension functions
784
+
785
+ cdef void _extension_function_call(_BaseContext context, function,
786
+ xpath.xmlXPathParserContext* ctxt, int nargs) noexcept:
787
+ cdef _Document doc
788
+ cdef xpath.xmlXPathObject* obj
789
+ cdef list args
790
+ cdef int i
791
+ doc = context._doc
792
+ try:
793
+ args = []
794
+ for i in range(nargs):
795
+ obj = xpath.valuePop(ctxt)
796
+ o = _unwrapXPathObject(obj, doc, context)
797
+ _freeXPathObject(obj)
798
+ args.append(o)
799
+ args.reverse()
800
+
801
+ res = function(context, *args)
802
+ # wrap result for XPath consumption
803
+ obj = _wrapXPathObject(res, doc, context)
804
+ # prevent Python from deallocating elements handed to libxml2
805
+ context._hold(res)
806
+ xpath.valuePush(ctxt, obj)
807
+ except:
808
+ xpath.xmlXPathErr(ctxt, xpath.XPATH_EXPR_ERROR)
809
+ context._exc._store_raised()
810
+ finally:
811
+ return # swallow any further exceptions
812
+
813
+ # lookup the function by name and call it
814
+
815
+ cdef void _xpath_function_call(xpath.xmlXPathParserContext* ctxt,
816
+ int nargs) noexcept with gil:
817
+ cdef _BaseContext context
818
+ cdef xpath.xmlXPathContext* rctxt = ctxt.context
819
+ context = <_BaseContext> rctxt.userData
820
+ try:
821
+ function = context._find_cached_function(rctxt.functionURI, rctxt.function)
822
+ if function is not None:
823
+ _extension_function_call(context, function, ctxt, nargs)
824
+ else:
825
+ xpath.xmlXPathErr(ctxt, xpath.XPATH_UNKNOWN_FUNC_ERROR)
826
+ context._exc._store_exception(XPathFunctionError(
827
+ f"XPath function '{_namespacedNameFromNsName(rctxt.functionURI, rctxt.function)}' not found"))
828
+ except:
829
+ # may not be the right error, but we need to tell libxml2 *something*
830
+ xpath.xmlXPathErr(ctxt, xpath.XPATH_UNKNOWN_FUNC_ERROR)
831
+ context._exc._store_raised()
832
+ finally:
833
+ return # swallow any further exceptions