Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- env-llmeval/lib/python3.10/site-packages/lxml/ElementInclude.py +244 -0
- env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/lxml/_elementpath.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/lxml/_elementpath.py +341 -0
- env-llmeval/lib/python3.10/site-packages/lxml/apihelpers.pxi +1793 -0
- env-llmeval/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/lxml/builder.py +232 -0
- env-llmeval/lib/python3.10/site-packages/lxml/classlookup.pxi +580 -0
- env-llmeval/lib/python3.10/site-packages/lxml/cleanup.pxi +215 -0
- env-llmeval/lib/python3.10/site-packages/lxml/cssselect.py +101 -0
- env-llmeval/lib/python3.10/site-packages/lxml/debug.pxi +90 -0
- env-llmeval/lib/python3.10/site-packages/lxml/docloader.pxi +178 -0
- env-llmeval/lib/python3.10/site-packages/lxml/doctestcompare.py +488 -0
- env-llmeval/lib/python3.10/site-packages/lxml/etree.pyx +0 -0
- env-llmeval/lib/python3.10/site-packages/lxml/etree_api.h +195 -0
- env-llmeval/lib/python3.10/site-packages/lxml/extensions.pxi +833 -0
- env-llmeval/lib/python3.10/site-packages/lxml/iterparse.pxi +438 -0
- env-llmeval/lib/python3.10/site-packages/lxml/lxml.etree.h +248 -0
- env-llmeval/lib/python3.10/site-packages/lxml/lxml.etree_api.h +195 -0
- env-llmeval/lib/python3.10/site-packages/lxml/nsclasses.pxi +281 -0
- env-llmeval/lib/python3.10/site-packages/lxml/objectify.pyx +2145 -0
- env-llmeval/lib/python3.10/site-packages/lxml/objectpath.pxi +332 -0
- env-llmeval/lib/python3.10/site-packages/lxml/parser.pxi +1994 -0
- env-llmeval/lib/python3.10/site-packages/lxml/parsertarget.pxi +180 -0
- env-llmeval/lib/python3.10/site-packages/lxml/proxy.pxi +619 -0
- env-llmeval/lib/python3.10/site-packages/lxml/readonlytree.pxi +565 -0
- env-llmeval/lib/python3.10/site-packages/lxml/relaxng.pxi +165 -0
- env-llmeval/lib/python3.10/site-packages/lxml/sax.cpython-310-x86_64-linux-gnu.so +0 -0
- env-llmeval/lib/python3.10/site-packages/lxml/sax.py +275 -0
- env-llmeval/lib/python3.10/site-packages/lxml/serializer.pxi +1871 -0
- env-llmeval/lib/python3.10/site-packages/lxml/xinclude.pxi +67 -0
- env-llmeval/lib/python3.10/site-packages/lxml/xmlerror.pxi +1654 -0
- env-llmeval/lib/python3.10/site-packages/lxml/xmlid.pxi +179 -0
- env-llmeval/lib/python3.10/site-packages/lxml/xmlschema.pxi +215 -0
- env-llmeval/lib/python3.10/site-packages/lxml/xpath.pxi +487 -0
- env-llmeval/lib/python3.10/site-packages/lxml/xslt.pxi +950 -0
- env-llmeval/lib/python3.10/site-packages/lxml/xsltext.pxi +242 -0
- env-llmeval/lib/python3.10/site-packages/triton/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/__init__.py +218 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/core.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/math.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/random.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/semantic.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/standard.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/core.py +1884 -0
- env-llmeval/lib/python3.10/site-packages/triton/language/extra/__init__.py +3 -0
.gitattributes
CHANGED
@@ -122,3 +122,4 @@ llmeval-env/lib/python3.10/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs di
|
|
122 |
llmeval-env/lib/python3.10/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
123 |
env-llmeval/lib/python3.10/site-packages/numpy/core/_simd.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
124 |
env-llmeval/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
122 |
llmeval-env/lib/python3.10/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
123 |
env-llmeval/lib/python3.10/site-packages/numpy/core/_simd.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
124 |
env-llmeval/lib/python3.10/site-packages/numpy/core/_multiarray_umath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
125 |
+
env-llmeval/lib/python3.10/site-packages/triton/third_party/cuda/bin/nvdisasm filter=lfs diff=lfs merge=lfs -text
|
env-llmeval/lib/python3.10/site-packages/lxml/ElementInclude.py
ADDED
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#
|
2 |
+
# ElementTree
|
3 |
+
# $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $
|
4 |
+
#
|
5 |
+
# limited xinclude support for element trees
|
6 |
+
#
|
7 |
+
# history:
|
8 |
+
# 2003-08-15 fl created
|
9 |
+
# 2003-11-14 fl fixed default loader
|
10 |
+
#
|
11 |
+
# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
|
12 |
+
#
|
13 | |
14 |
+
# http://www.pythonware.com
|
15 |
+
#
|
16 |
+
# --------------------------------------------------------------------
|
17 |
+
# The ElementTree toolkit is
|
18 |
+
#
|
19 |
+
# Copyright (c) 1999-2004 by Fredrik Lundh
|
20 |
+
#
|
21 |
+
# By obtaining, using, and/or copying this software and/or its
|
22 |
+
# associated documentation, you agree that you have read, understood,
|
23 |
+
# and will comply with the following terms and conditions:
|
24 |
+
#
|
25 |
+
# Permission to use, copy, modify, and distribute this software and
|
26 |
+
# its associated documentation for any purpose and without fee is
|
27 |
+
# hereby granted, provided that the above copyright notice appears in
|
28 |
+
# all copies, and that both that copyright notice and this permission
|
29 |
+
# notice appear in supporting documentation, and that the name of
|
30 |
+
# Secret Labs AB or the author not be used in advertising or publicity
|
31 |
+
# pertaining to distribution of the software without specific, written
|
32 |
+
# prior permission.
|
33 |
+
#
|
34 |
+
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
|
35 |
+
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
|
36 |
+
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
|
37 |
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
|
38 |
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
39 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
40 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
41 |
+
# OF THIS SOFTWARE.
|
42 |
+
# --------------------------------------------------------------------
|
43 |
+
|
44 |
+
"""
|
45 |
+
Limited XInclude support for the ElementTree package.
|
46 |
+
|
47 |
+
While lxml.etree has full support for XInclude (see
|
48 |
+
`etree.ElementTree.xinclude()`), this module provides a simpler, pure
|
49 |
+
Python, ElementTree compatible implementation that supports a simple
|
50 |
+
form of custom URL resolvers.
|
51 |
+
"""
|
52 |
+
|
53 |
+
from lxml import etree
|
54 |
+
try:
|
55 |
+
from urlparse import urljoin
|
56 |
+
from urllib2 import urlopen
|
57 |
+
except ImportError:
|
58 |
+
# Python 3
|
59 |
+
from urllib.parse import urljoin
|
60 |
+
from urllib.request import urlopen
|
61 |
+
|
62 |
+
XINCLUDE = "{http://www.w3.org/2001/XInclude}"
|
63 |
+
|
64 |
+
XINCLUDE_INCLUDE = XINCLUDE + "include"
|
65 |
+
XINCLUDE_FALLBACK = XINCLUDE + "fallback"
|
66 |
+
XINCLUDE_ITER_TAG = XINCLUDE + "*"
|
67 |
+
|
68 |
+
# For security reasons, the inclusion depth is limited to this read-only value by default.
|
69 |
+
DEFAULT_MAX_INCLUSION_DEPTH = 6
|
70 |
+
|
71 |
+
|
72 |
+
##
|
73 |
+
# Fatal include error.
|
74 |
+
|
75 |
+
class FatalIncludeError(etree.LxmlSyntaxError):
|
76 |
+
pass
|
77 |
+
|
78 |
+
|
79 |
+
class LimitedRecursiveIncludeError(FatalIncludeError):
|
80 |
+
pass
|
81 |
+
|
82 |
+
|
83 |
+
##
|
84 |
+
# ET compatible default loader.
|
85 |
+
# This loader reads an included resource from disk.
|
86 |
+
#
|
87 |
+
# @param href Resource reference.
|
88 |
+
# @param parse Parse mode. Either "xml" or "text".
|
89 |
+
# @param encoding Optional text encoding.
|
90 |
+
# @return The expanded resource. If the parse mode is "xml", this
|
91 |
+
# is an ElementTree instance. If the parse mode is "text", this
|
92 |
+
# is a Unicode string. If the loader fails, it can return None
|
93 |
+
# or raise an IOError exception.
|
94 |
+
# @throws IOError If the loader fails to load the resource.
|
95 |
+
|
96 |
+
def default_loader(href, parse, encoding=None):
|
97 |
+
file = open(href, 'rb')
|
98 |
+
if parse == "xml":
|
99 |
+
data = etree.parse(file).getroot()
|
100 |
+
else:
|
101 |
+
data = file.read()
|
102 |
+
if not encoding:
|
103 |
+
encoding = 'utf-8'
|
104 |
+
data = data.decode(encoding)
|
105 |
+
file.close()
|
106 |
+
return data
|
107 |
+
|
108 |
+
|
109 |
+
##
|
110 |
+
# Default loader used by lxml.etree - handles custom resolvers properly
|
111 |
+
#
|
112 |
+
|
113 |
+
def _lxml_default_loader(href, parse, encoding=None, parser=None):
|
114 |
+
if parse == "xml":
|
115 |
+
data = etree.parse(href, parser).getroot()
|
116 |
+
else:
|
117 |
+
if "://" in href:
|
118 |
+
f = urlopen(href)
|
119 |
+
else:
|
120 |
+
f = open(href, 'rb')
|
121 |
+
data = f.read()
|
122 |
+
f.close()
|
123 |
+
if not encoding:
|
124 |
+
encoding = 'utf-8'
|
125 |
+
data = data.decode(encoding)
|
126 |
+
return data
|
127 |
+
|
128 |
+
|
129 |
+
##
|
130 |
+
# Wrapper for ET compatibility - drops the parser
|
131 |
+
|
132 |
+
def _wrap_et_loader(loader):
|
133 |
+
def load(href, parse, encoding=None, parser=None):
|
134 |
+
return loader(href, parse, encoding)
|
135 |
+
return load
|
136 |
+
|
137 |
+
|
138 |
+
##
|
139 |
+
# Expand XInclude directives.
|
140 |
+
#
|
141 |
+
# @param elem Root element.
|
142 |
+
# @param loader Optional resource loader. If omitted, it defaults
|
143 |
+
# to {@link default_loader}. If given, it should be a callable
|
144 |
+
# that implements the same interface as <b>default_loader</b>.
|
145 |
+
# @param base_url The base URL of the original file, to resolve
|
146 |
+
# relative include file references.
|
147 |
+
# @param max_depth The maximum number of recursive inclusions.
|
148 |
+
# Limited to reduce the risk of malicious content explosion.
|
149 |
+
# Pass None to disable the limitation.
|
150 |
+
# @throws LimitedRecursiveIncludeError If the {@link max_depth} was exceeded.
|
151 |
+
# @throws FatalIncludeError If the function fails to include a given
|
152 |
+
# resource, or if the tree contains malformed XInclude elements.
|
153 |
+
# @throws IOError If the function fails to load a given resource.
|
154 |
+
# @returns the node or its replacement if it was an XInclude node
|
155 |
+
|
156 |
+
def include(elem, loader=None, base_url=None,
|
157 |
+
max_depth=DEFAULT_MAX_INCLUSION_DEPTH):
|
158 |
+
if max_depth is None:
|
159 |
+
max_depth = -1
|
160 |
+
elif max_depth < 0:
|
161 |
+
raise ValueError("expected non-negative depth or None for 'max_depth', got %r" % max_depth)
|
162 |
+
|
163 |
+
if base_url is None:
|
164 |
+
if hasattr(elem, 'getroot'):
|
165 |
+
tree = elem
|
166 |
+
elem = elem.getroot()
|
167 |
+
else:
|
168 |
+
tree = elem.getroottree()
|
169 |
+
if hasattr(tree, 'docinfo'):
|
170 |
+
base_url = tree.docinfo.URL
|
171 |
+
elif hasattr(elem, 'getroot'):
|
172 |
+
elem = elem.getroot()
|
173 |
+
_include(elem, loader, base_url, max_depth)
|
174 |
+
|
175 |
+
|
176 |
+
def _include(elem, loader=None, base_url=None,
|
177 |
+
max_depth=DEFAULT_MAX_INCLUSION_DEPTH, _parent_hrefs=None):
|
178 |
+
if loader is not None:
|
179 |
+
load_include = _wrap_et_loader(loader)
|
180 |
+
else:
|
181 |
+
load_include = _lxml_default_loader
|
182 |
+
|
183 |
+
if _parent_hrefs is None:
|
184 |
+
_parent_hrefs = set()
|
185 |
+
|
186 |
+
parser = elem.getroottree().parser
|
187 |
+
|
188 |
+
include_elements = list(
|
189 |
+
elem.iter(XINCLUDE_ITER_TAG))
|
190 |
+
|
191 |
+
for e in include_elements:
|
192 |
+
if e.tag == XINCLUDE_INCLUDE:
|
193 |
+
# process xinclude directive
|
194 |
+
href = urljoin(base_url, e.get("href"))
|
195 |
+
parse = e.get("parse", "xml")
|
196 |
+
parent = e.getparent()
|
197 |
+
if parse == "xml":
|
198 |
+
if href in _parent_hrefs:
|
199 |
+
raise FatalIncludeError(
|
200 |
+
"recursive include of %r detected" % href
|
201 |
+
)
|
202 |
+
if max_depth == 0:
|
203 |
+
raise LimitedRecursiveIncludeError(
|
204 |
+
"maximum xinclude depth reached when including file %s" % href)
|
205 |
+
node = load_include(href, parse, parser=parser)
|
206 |
+
if node is None:
|
207 |
+
raise FatalIncludeError(
|
208 |
+
"cannot load %r as %r" % (href, parse)
|
209 |
+
)
|
210 |
+
node = _include(node, loader, href, max_depth - 1, {href} | _parent_hrefs)
|
211 |
+
if e.tail:
|
212 |
+
node.tail = (node.tail or "") + e.tail
|
213 |
+
if parent is None:
|
214 |
+
return node # replaced the root node!
|
215 |
+
parent.replace(e, node)
|
216 |
+
elif parse == "text":
|
217 |
+
text = load_include(href, parse, encoding=e.get("encoding"))
|
218 |
+
if text is None:
|
219 |
+
raise FatalIncludeError(
|
220 |
+
"cannot load %r as %r" % (href, parse)
|
221 |
+
)
|
222 |
+
predecessor = e.getprevious()
|
223 |
+
if predecessor is not None:
|
224 |
+
predecessor.tail = (predecessor.tail or "") + text
|
225 |
+
elif parent is None:
|
226 |
+
return text # replaced the root node!
|
227 |
+
else:
|
228 |
+
parent.text = (parent.text or "") + text + (e.tail or "")
|
229 |
+
parent.remove(e)
|
230 |
+
else:
|
231 |
+
raise FatalIncludeError(
|
232 |
+
"unknown parse type in xi:include tag (%r)" % parse
|
233 |
+
)
|
234 |
+
elif e.tag == XINCLUDE_FALLBACK:
|
235 |
+
parent = e.getparent()
|
236 |
+
if parent is not None and parent.tag != XINCLUDE_INCLUDE:
|
237 |
+
raise FatalIncludeError(
|
238 |
+
"xi:fallback tag must be child of xi:include (%r)" % e.tag
|
239 |
+
)
|
240 |
+
else:
|
241 |
+
raise FatalIncludeError(
|
242 |
+
"Invalid element found in XInclude namespace (%r)" % e.tag
|
243 |
+
)
|
244 |
+
return elem
|
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc
ADDED
Binary file (6.38 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc
ADDED
Binary file (233 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/lxml/_elementpath.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (209 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/lxml/_elementpath.py
ADDED
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: language_level=2
|
2 |
+
|
3 |
+
#
|
4 |
+
# ElementTree
|
5 |
+
# $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
|
6 |
+
#
|
7 |
+
# limited xpath support for element trees
|
8 |
+
#
|
9 |
+
# history:
|
10 |
+
# 2003-05-23 fl created
|
11 |
+
# 2003-05-28 fl added support for // etc
|
12 |
+
# 2003-08-27 fl fixed parsing of periods in element names
|
13 |
+
# 2007-09-10 fl new selection engine
|
14 |
+
# 2007-09-12 fl fixed parent selector
|
15 |
+
# 2007-09-13 fl added iterfind; changed findall to return a list
|
16 |
+
# 2007-11-30 fl added namespaces support
|
17 |
+
# 2009-10-30 fl added child element value filter
|
18 |
+
#
|
19 |
+
# Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved.
|
20 |
+
#
|
21 | |
22 |
+
# http://www.pythonware.com
|
23 |
+
#
|
24 |
+
# --------------------------------------------------------------------
|
25 |
+
# The ElementTree toolkit is
|
26 |
+
#
|
27 |
+
# Copyright (c) 1999-2009 by Fredrik Lundh
|
28 |
+
#
|
29 |
+
# By obtaining, using, and/or copying this software and/or its
|
30 |
+
# associated documentation, you agree that you have read, understood,
|
31 |
+
# and will comply with the following terms and conditions:
|
32 |
+
#
|
33 |
+
# Permission to use, copy, modify, and distribute this software and
|
34 |
+
# its associated documentation for any purpose and without fee is
|
35 |
+
# hereby granted, provided that the above copyright notice appears in
|
36 |
+
# all copies, and that both that copyright notice and this permission
|
37 |
+
# notice appear in supporting documentation, and that the name of
|
38 |
+
# Secret Labs AB or the author not be used in advertising or publicity
|
39 |
+
# pertaining to distribution of the software without specific, written
|
40 |
+
# prior permission.
|
41 |
+
#
|
42 |
+
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
|
43 |
+
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
|
44 |
+
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
|
45 |
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
|
46 |
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
47 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
48 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
49 |
+
# OF THIS SOFTWARE.
|
50 |
+
# --------------------------------------------------------------------
|
51 |
+
|
52 |
+
##
|
53 |
+
# Implementation module for XPath support. There's usually no reason
|
54 |
+
# to import this module directly; the <b>ElementTree</b> does this for
|
55 |
+
# you, if needed.
|
56 |
+
##
|
57 |
+
|
58 |
+
|
59 |
+
import re
|
60 |
+
|
61 |
+
xpath_tokenizer_re = re.compile(
|
62 |
+
"("
|
63 |
+
"'[^']*'|\"[^\"]*\"|"
|
64 |
+
"::|"
|
65 |
+
"//?|"
|
66 |
+
r"\.\.|"
|
67 |
+
r"\(\)|"
|
68 |
+
r"[/.*:\[\]\(\)@=])|"
|
69 |
+
r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
|
70 |
+
r"\s+"
|
71 |
+
)
|
72 |
+
|
73 |
+
def xpath_tokenizer(pattern, namespaces=None, with_prefixes=True):
|
74 |
+
# ElementTree uses '', lxml used None originally.
|
75 |
+
default_namespace = (namespaces.get(None) or namespaces.get('')) if namespaces else None
|
76 |
+
parsing_attribute = False
|
77 |
+
for token in xpath_tokenizer_re.findall(pattern):
|
78 |
+
ttype, tag = token
|
79 |
+
if tag and tag[0] != "{":
|
80 |
+
if ":" in tag and with_prefixes:
|
81 |
+
prefix, uri = tag.split(":", 1)
|
82 |
+
try:
|
83 |
+
if not namespaces:
|
84 |
+
raise KeyError
|
85 |
+
yield ttype, "{%s}%s" % (namespaces[prefix], uri)
|
86 |
+
except KeyError:
|
87 |
+
raise SyntaxError("prefix %r not found in prefix map" % prefix)
|
88 |
+
elif default_namespace and not parsing_attribute:
|
89 |
+
yield ttype, "{%s}%s" % (default_namespace, tag)
|
90 |
+
else:
|
91 |
+
yield token
|
92 |
+
parsing_attribute = False
|
93 |
+
else:
|
94 |
+
yield token
|
95 |
+
parsing_attribute = ttype == '@'
|
96 |
+
|
97 |
+
|
98 |
+
def prepare_child(next, token):
|
99 |
+
tag = token[1]
|
100 |
+
def select(result):
|
101 |
+
for elem in result:
|
102 |
+
yield from elem.iterchildren(tag)
|
103 |
+
return select
|
104 |
+
|
105 |
+
def prepare_star(next, token):
|
106 |
+
def select(result):
|
107 |
+
for elem in result:
|
108 |
+
yield from elem.iterchildren('*')
|
109 |
+
return select
|
110 |
+
|
111 |
+
def prepare_self(next, token):
|
112 |
+
def select(result):
|
113 |
+
return result
|
114 |
+
return select
|
115 |
+
|
116 |
+
def prepare_descendant(next, token):
|
117 |
+
token = next()
|
118 |
+
if token[0] == "*":
|
119 |
+
tag = "*"
|
120 |
+
elif not token[0]:
|
121 |
+
tag = token[1]
|
122 |
+
else:
|
123 |
+
raise SyntaxError("invalid descendant")
|
124 |
+
def select(result):
|
125 |
+
for elem in result:
|
126 |
+
yield from elem.iterdescendants(tag)
|
127 |
+
return select
|
128 |
+
|
129 |
+
def prepare_parent(next, token):
|
130 |
+
def select(result):
|
131 |
+
for elem in result:
|
132 |
+
parent = elem.getparent()
|
133 |
+
if parent is not None:
|
134 |
+
yield parent
|
135 |
+
return select
|
136 |
+
|
137 |
+
def prepare_predicate(next, token):
|
138 |
+
# FIXME: replace with real parser!!! refs:
|
139 |
+
# http://effbot.org/zone/simple-iterator-parser.htm
|
140 |
+
# http://javascript.crockford.com/tdop/tdop.html
|
141 |
+
signature = ''
|
142 |
+
predicate = []
|
143 |
+
while 1:
|
144 |
+
token = next()
|
145 |
+
if token[0] == "]":
|
146 |
+
break
|
147 |
+
if token == ('', ''):
|
148 |
+
# ignore whitespace
|
149 |
+
continue
|
150 |
+
if token[0] and token[0][:1] in "'\"":
|
151 |
+
token = "'", token[0][1:-1]
|
152 |
+
signature += token[0] or "-"
|
153 |
+
predicate.append(token[1])
|
154 |
+
|
155 |
+
# use signature to determine predicate type
|
156 |
+
if signature == "@-":
|
157 |
+
# [@attribute] predicate
|
158 |
+
key = predicate[1]
|
159 |
+
def select(result):
|
160 |
+
for elem in result:
|
161 |
+
if elem.get(key) is not None:
|
162 |
+
yield elem
|
163 |
+
return select
|
164 |
+
if signature == "@-='":
|
165 |
+
# [@attribute='value']
|
166 |
+
key = predicate[1]
|
167 |
+
value = predicate[-1]
|
168 |
+
def select(result):
|
169 |
+
for elem in result:
|
170 |
+
if elem.get(key) == value:
|
171 |
+
yield elem
|
172 |
+
return select
|
173 |
+
if signature == "-" and not re.match(r"-?\d+$", predicate[0]):
|
174 |
+
# [tag]
|
175 |
+
tag = predicate[0]
|
176 |
+
def select(result):
|
177 |
+
for elem in result:
|
178 |
+
for _ in elem.iterchildren(tag):
|
179 |
+
yield elem
|
180 |
+
break
|
181 |
+
return select
|
182 |
+
if signature == ".='" or (signature == "-='" and not re.match(r"-?\d+$", predicate[0])):
|
183 |
+
# [.='value'] or [tag='value']
|
184 |
+
tag = predicate[0]
|
185 |
+
value = predicate[-1]
|
186 |
+
if tag:
|
187 |
+
def select(result):
|
188 |
+
for elem in result:
|
189 |
+
for e in elem.iterchildren(tag):
|
190 |
+
if "".join(e.itertext()) == value:
|
191 |
+
yield elem
|
192 |
+
break
|
193 |
+
else:
|
194 |
+
def select(result):
|
195 |
+
for elem in result:
|
196 |
+
if "".join(elem.itertext()) == value:
|
197 |
+
yield elem
|
198 |
+
return select
|
199 |
+
if signature == "-" or signature == "-()" or signature == "-()-":
|
200 |
+
# [index] or [last()] or [last()-index]
|
201 |
+
if signature == "-":
|
202 |
+
# [index]
|
203 |
+
index = int(predicate[0]) - 1
|
204 |
+
if index < 0:
|
205 |
+
if index == -1:
|
206 |
+
raise SyntaxError(
|
207 |
+
"indices in path predicates are 1-based, not 0-based")
|
208 |
+
else:
|
209 |
+
raise SyntaxError("path index >= 1 expected")
|
210 |
+
else:
|
211 |
+
if predicate[0] != "last":
|
212 |
+
raise SyntaxError("unsupported function")
|
213 |
+
if signature == "-()-":
|
214 |
+
try:
|
215 |
+
index = int(predicate[2]) - 1
|
216 |
+
except ValueError:
|
217 |
+
raise SyntaxError("unsupported expression")
|
218 |
+
else:
|
219 |
+
index = -1
|
220 |
+
def select(result):
|
221 |
+
for elem in result:
|
222 |
+
parent = elem.getparent()
|
223 |
+
if parent is None:
|
224 |
+
continue
|
225 |
+
try:
|
226 |
+
# FIXME: what if the selector is "*" ?
|
227 |
+
elems = list(parent.iterchildren(elem.tag))
|
228 |
+
if elems[index] is elem:
|
229 |
+
yield elem
|
230 |
+
except IndexError:
|
231 |
+
pass
|
232 |
+
return select
|
233 |
+
raise SyntaxError("invalid predicate")
|
234 |
+
|
235 |
+
ops = {
|
236 |
+
"": prepare_child,
|
237 |
+
"*": prepare_star,
|
238 |
+
".": prepare_self,
|
239 |
+
"..": prepare_parent,
|
240 |
+
"//": prepare_descendant,
|
241 |
+
"[": prepare_predicate,
|
242 |
+
}
|
243 |
+
|
244 |
+
|
245 |
+
# --------------------------------------------------------------------
|
246 |
+
|
247 |
+
_cache = {}
|
248 |
+
|
249 |
+
|
250 |
+
def _build_path_iterator(path, namespaces, with_prefixes=True):
|
251 |
+
"""compile selector pattern"""
|
252 |
+
if path[-1:] == "/":
|
253 |
+
path += "*" # implicit all (FIXME: keep this?)
|
254 |
+
|
255 |
+
cache_key = (path,)
|
256 |
+
if namespaces:
|
257 |
+
# lxml originally used None for the default namespace but ElementTree uses the
|
258 |
+
# more convenient (all-strings-dict) empty string, so we support both here,
|
259 |
+
# preferring the more convenient '', as long as they aren't ambiguous.
|
260 |
+
if None in namespaces:
|
261 |
+
if '' in namespaces and namespaces[None] != namespaces['']:
|
262 |
+
raise ValueError("Ambiguous default namespace provided: %r versus %r" % (
|
263 |
+
namespaces[None], namespaces['']))
|
264 |
+
cache_key += (namespaces[None],) + tuple(sorted(
|
265 |
+
item for item in namespaces.items() if item[0] is not None))
|
266 |
+
else:
|
267 |
+
cache_key += tuple(sorted(namespaces.items()))
|
268 |
+
|
269 |
+
try:
|
270 |
+
return _cache[cache_key]
|
271 |
+
except KeyError:
|
272 |
+
pass
|
273 |
+
if len(_cache) > 100:
|
274 |
+
_cache.clear()
|
275 |
+
|
276 |
+
if path[:1] == "/":
|
277 |
+
raise SyntaxError("cannot use absolute path on element")
|
278 |
+
stream = iter(xpath_tokenizer(path, namespaces, with_prefixes=with_prefixes))
|
279 |
+
try:
|
280 |
+
_next = stream.next
|
281 |
+
except AttributeError:
|
282 |
+
# Python 3
|
283 |
+
_next = stream.__next__
|
284 |
+
try:
|
285 |
+
token = _next()
|
286 |
+
except StopIteration:
|
287 |
+
raise SyntaxError("empty path expression")
|
288 |
+
selector = []
|
289 |
+
while 1:
|
290 |
+
try:
|
291 |
+
selector.append(ops[token[0]](_next, token))
|
292 |
+
except StopIteration:
|
293 |
+
raise SyntaxError("invalid path")
|
294 |
+
try:
|
295 |
+
token = _next()
|
296 |
+
if token[0] == "/":
|
297 |
+
token = _next()
|
298 |
+
except StopIteration:
|
299 |
+
break
|
300 |
+
_cache[cache_key] = selector
|
301 |
+
return selector
|
302 |
+
|
303 |
+
|
304 |
+
##
|
305 |
+
# Iterate over the matching nodes
|
306 |
+
|
307 |
+
def iterfind(elem, path, namespaces=None, with_prefixes=True):
|
308 |
+
selector = _build_path_iterator(path, namespaces, with_prefixes=with_prefixes)
|
309 |
+
result = iter((elem,))
|
310 |
+
for select in selector:
|
311 |
+
result = select(result)
|
312 |
+
return result
|
313 |
+
|
314 |
+
|
315 |
+
##
|
316 |
+
# Find first matching object.
|
317 |
+
|
318 |
+
def find(elem, path, namespaces=None, with_prefixes=True):
|
319 |
+
it = iterfind(elem, path, namespaces, with_prefixes=with_prefixes)
|
320 |
+
try:
|
321 |
+
return next(it)
|
322 |
+
except StopIteration:
|
323 |
+
return None
|
324 |
+
|
325 |
+
|
326 |
+
##
|
327 |
+
# Find all matching objects.
|
328 |
+
|
329 |
+
def findall(elem, path, namespaces=None, with_prefixes=True):
|
330 |
+
return list(iterfind(elem, path, namespaces))
|
331 |
+
|
332 |
+
|
333 |
+
##
|
334 |
+
# Find text for first matching object.
|
335 |
+
|
336 |
+
def findtext(elem, path, default=None, namespaces=None, with_prefixes=True):
|
337 |
+
el = find(elem, path, namespaces, with_prefixes=with_prefixes)
|
338 |
+
if el is None:
|
339 |
+
return default
|
340 |
+
else:
|
341 |
+
return el.text or ''
|
env-llmeval/lib/python3.10/site-packages/lxml/apihelpers.pxi
ADDED
@@ -0,0 +1,1793 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Private/public helper functions for API functions
|
2 |
+
|
3 |
+
from lxml.includes cimport uri
|
4 |
+
|
5 |
+
|
6 |
+
cdef void displayNode(xmlNode* c_node, indent) noexcept:
|
7 |
+
# to help with debugging
|
8 |
+
cdef xmlNode* c_child
|
9 |
+
try:
|
10 |
+
print(indent * ' ', <long>c_node)
|
11 |
+
c_child = c_node.children
|
12 |
+
while c_child is not NULL:
|
13 |
+
displayNode(c_child, indent + 1)
|
14 |
+
c_child = c_child.next
|
15 |
+
finally:
|
16 |
+
return # swallow any exceptions
|
17 |
+
|
18 |
+
cdef inline bint _isHtmlDocument(_Element element) except -1:
|
19 |
+
cdef xmlNode* c_node = element._c_node
|
20 |
+
return (
|
21 |
+
c_node is not NULL and c_node.doc is not NULL and
|
22 |
+
c_node.doc.properties & tree.XML_DOC_HTML != 0
|
23 |
+
)
|
24 |
+
|
25 |
+
cdef inline int _assertValidNode(_Element element) except -1:
|
26 |
+
assert element._c_node is not NULL, "invalid Element proxy at %s" % id(element)
|
27 |
+
|
28 |
+
cdef inline int _assertValidDoc(_Document doc) except -1:
|
29 |
+
assert doc._c_doc is not NULL, "invalid Document proxy at %s" % id(doc)
|
30 |
+
|
31 |
+
cdef _Document _documentOrRaise(object input):
|
32 |
+
"""Call this to get the document of a _Document, _ElementTree or _Element
|
33 |
+
object, or to raise an exception if it can't be determined.
|
34 |
+
|
35 |
+
Should be used in all API functions for consistency.
|
36 |
+
"""
|
37 |
+
cdef _Document doc
|
38 |
+
if isinstance(input, _ElementTree):
|
39 |
+
if (<_ElementTree>input)._context_node is not None:
|
40 |
+
doc = (<_ElementTree>input)._context_node._doc
|
41 |
+
else:
|
42 |
+
doc = None
|
43 |
+
elif isinstance(input, _Element):
|
44 |
+
doc = (<_Element>input)._doc
|
45 |
+
elif isinstance(input, _Document):
|
46 |
+
doc = <_Document>input
|
47 |
+
else:
|
48 |
+
raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}"
|
49 |
+
if doc is None:
|
50 |
+
raise ValueError, f"Input object has no document: {python._fqtypename(input).decode('utf8')}"
|
51 |
+
_assertValidDoc(doc)
|
52 |
+
return doc
|
53 |
+
|
54 |
+
cdef _Element _rootNodeOrRaise(object input):
|
55 |
+
"""Call this to get the root node of a _Document, _ElementTree or
|
56 |
+
_Element object, or to raise an exception if it can't be determined.
|
57 |
+
|
58 |
+
Should be used in all API functions for consistency.
|
59 |
+
"""
|
60 |
+
cdef _Element node
|
61 |
+
if isinstance(input, _ElementTree):
|
62 |
+
node = (<_ElementTree>input)._context_node
|
63 |
+
elif isinstance(input, _Element):
|
64 |
+
node = <_Element>input
|
65 |
+
elif isinstance(input, _Document):
|
66 |
+
node = (<_Document>input).getroot()
|
67 |
+
else:
|
68 |
+
raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}"
|
69 |
+
if (node is None or not node._c_node or
|
70 |
+
node._c_node.type != tree.XML_ELEMENT_NODE):
|
71 |
+
raise ValueError, f"Input object is not an XML element: {python._fqtypename(input).decode('utf8')}"
|
72 |
+
_assertValidNode(node)
|
73 |
+
return node
|
74 |
+
|
75 |
+
cdef bint _isAncestorOrSame(xmlNode* c_ancestor, xmlNode* c_node) noexcept:
|
76 |
+
while c_node:
|
77 |
+
if c_node is c_ancestor:
|
78 |
+
return True
|
79 |
+
c_node = c_node.parent
|
80 |
+
return False
|
81 |
+
|
82 |
+
cdef _Element _makeElement(tag, xmlDoc* c_doc, _Document doc,
|
83 |
+
_BaseParser parser, text, tail, attrib, nsmap,
|
84 |
+
dict extra_attrs):
|
85 |
+
"""Create a new element and initialize text content, namespaces and
|
86 |
+
attributes.
|
87 |
+
|
88 |
+
This helper function will reuse as much of the existing document as
|
89 |
+
possible:
|
90 |
+
|
91 |
+
If 'parser' is None, the parser will be inherited from 'doc' or the
|
92 |
+
default parser will be used.
|
93 |
+
|
94 |
+
If 'doc' is None, 'c_doc' is used to create a new _Document and the new
|
95 |
+
element is made its root node.
|
96 |
+
|
97 |
+
If 'c_doc' is also NULL, a new xmlDoc will be created.
|
98 |
+
"""
|
99 |
+
cdef xmlNode* c_node
|
100 |
+
if doc is not None:
|
101 |
+
c_doc = doc._c_doc
|
102 |
+
ns_utf, name_utf = _getNsTag(tag)
|
103 |
+
if parser is not None and parser._for_html:
|
104 |
+
_htmlTagValidOrRaise(name_utf)
|
105 |
+
if c_doc is NULL:
|
106 |
+
c_doc = _newHTMLDoc()
|
107 |
+
else:
|
108 |
+
_tagValidOrRaise(name_utf)
|
109 |
+
if c_doc is NULL:
|
110 |
+
c_doc = _newXMLDoc()
|
111 |
+
c_node = _createElement(c_doc, name_utf)
|
112 |
+
if c_node is NULL:
|
113 |
+
if doc is None and c_doc is not NULL:
|
114 |
+
tree.xmlFreeDoc(c_doc)
|
115 |
+
raise MemoryError()
|
116 |
+
try:
|
117 |
+
if doc is None:
|
118 |
+
tree.xmlDocSetRootElement(c_doc, c_node)
|
119 |
+
doc = _documentFactory(c_doc, parser)
|
120 |
+
if text is not None:
|
121 |
+
_setNodeText(c_node, text)
|
122 |
+
if tail is not None:
|
123 |
+
_setTailText(c_node, tail)
|
124 |
+
# add namespaces to node if necessary
|
125 |
+
_setNodeNamespaces(c_node, doc, ns_utf, nsmap)
|
126 |
+
_initNodeAttributes(c_node, doc, attrib, extra_attrs)
|
127 |
+
return _elementFactory(doc, c_node)
|
128 |
+
except:
|
129 |
+
# free allocated c_node/c_doc unless Python does it for us
|
130 |
+
if c_node.doc is not c_doc:
|
131 |
+
# node not yet in document => will not be freed by document
|
132 |
+
if tail is not None:
|
133 |
+
_removeText(c_node.next) # tail
|
134 |
+
tree.xmlFreeNode(c_node)
|
135 |
+
if doc is None:
|
136 |
+
# c_doc will not be freed by doc
|
137 |
+
tree.xmlFreeDoc(c_doc)
|
138 |
+
raise
|
139 |
+
|
140 |
+
cdef int _initNewElement(_Element element, bint is_html, name_utf, ns_utf,
|
141 |
+
_BaseParser parser, attrib, nsmap, dict extra_attrs) except -1:
|
142 |
+
"""Initialise a new Element object.
|
143 |
+
|
144 |
+
This is used when users instantiate a Python Element subclass
|
145 |
+
directly, without it being mapped to an existing XML node.
|
146 |
+
"""
|
147 |
+
cdef xmlDoc* c_doc
|
148 |
+
cdef xmlNode* c_node
|
149 |
+
cdef _Document doc
|
150 |
+
if is_html:
|
151 |
+
_htmlTagValidOrRaise(name_utf)
|
152 |
+
c_doc = _newHTMLDoc()
|
153 |
+
else:
|
154 |
+
_tagValidOrRaise(name_utf)
|
155 |
+
c_doc = _newXMLDoc()
|
156 |
+
c_node = _createElement(c_doc, name_utf)
|
157 |
+
if c_node is NULL:
|
158 |
+
if c_doc is not NULL:
|
159 |
+
tree.xmlFreeDoc(c_doc)
|
160 |
+
raise MemoryError()
|
161 |
+
tree.xmlDocSetRootElement(c_doc, c_node)
|
162 |
+
doc = _documentFactory(c_doc, parser)
|
163 |
+
# add namespaces to node if necessary
|
164 |
+
_setNodeNamespaces(c_node, doc, ns_utf, nsmap)
|
165 |
+
_initNodeAttributes(c_node, doc, attrib, extra_attrs)
|
166 |
+
_registerProxy(element, doc, c_node)
|
167 |
+
element._init()
|
168 |
+
return 0
|
169 |
+
|
170 |
+
cdef _Element _makeSubElement(_Element parent, tag, text, tail,
|
171 |
+
attrib, nsmap, dict extra_attrs):
|
172 |
+
"""Create a new child element and initialize text content, namespaces and
|
173 |
+
attributes.
|
174 |
+
"""
|
175 |
+
cdef xmlNode* c_node
|
176 |
+
cdef xmlDoc* c_doc
|
177 |
+
if parent is None or parent._doc is None:
|
178 |
+
return None
|
179 |
+
_assertValidNode(parent)
|
180 |
+
ns_utf, name_utf = _getNsTag(tag)
|
181 |
+
c_doc = parent._doc._c_doc
|
182 |
+
|
183 |
+
if parent._doc._parser is not None and parent._doc._parser._for_html:
|
184 |
+
_htmlTagValidOrRaise(name_utf)
|
185 |
+
else:
|
186 |
+
_tagValidOrRaise(name_utf)
|
187 |
+
|
188 |
+
c_node = _createElement(c_doc, name_utf)
|
189 |
+
if c_node is NULL:
|
190 |
+
raise MemoryError()
|
191 |
+
tree.xmlAddChild(parent._c_node, c_node)
|
192 |
+
|
193 |
+
try:
|
194 |
+
if text is not None:
|
195 |
+
_setNodeText(c_node, text)
|
196 |
+
if tail is not None:
|
197 |
+
_setTailText(c_node, tail)
|
198 |
+
|
199 |
+
# add namespaces to node if necessary
|
200 |
+
_setNodeNamespaces(c_node, parent._doc, ns_utf, nsmap)
|
201 |
+
_initNodeAttributes(c_node, parent._doc, attrib, extra_attrs)
|
202 |
+
return _elementFactory(parent._doc, c_node)
|
203 |
+
except:
|
204 |
+
# make sure we clean up in case of an error
|
205 |
+
_removeNode(parent._doc, c_node)
|
206 |
+
raise
|
207 |
+
|
208 |
+
|
209 |
+
cdef int _setNodeNamespaces(xmlNode* c_node, _Document doc,
|
210 |
+
object node_ns_utf, object nsmap) except -1:
|
211 |
+
"""Lookup current namespace prefixes, then set namespace structure for
|
212 |
+
node (if 'node_ns_utf' was provided) and register new ns-prefix mappings.
|
213 |
+
|
214 |
+
'node_ns_utf' should only be passed for a newly created node.
|
215 |
+
"""
|
216 |
+
cdef xmlNs* c_ns
|
217 |
+
cdef list nsdefs
|
218 |
+
|
219 |
+
if nsmap:
|
220 |
+
for prefix, href in _iter_nsmap(nsmap):
|
221 |
+
href_utf = _utf8(href)
|
222 |
+
_uriValidOrRaise(href_utf)
|
223 |
+
c_href = _xcstr(href_utf)
|
224 |
+
if prefix is not None:
|
225 |
+
prefix_utf = _utf8(prefix)
|
226 |
+
_prefixValidOrRaise(prefix_utf)
|
227 |
+
c_prefix = _xcstr(prefix_utf)
|
228 |
+
else:
|
229 |
+
c_prefix = <const_xmlChar*>NULL
|
230 |
+
# add namespace with prefix if it is not already known
|
231 |
+
c_ns = tree.xmlSearchNs(doc._c_doc, c_node, c_prefix)
|
232 |
+
if c_ns is NULL or \
|
233 |
+
c_ns.href is NULL or \
|
234 |
+
tree.xmlStrcmp(c_ns.href, c_href) != 0:
|
235 |
+
c_ns = tree.xmlNewNs(c_node, c_href, c_prefix)
|
236 |
+
if href_utf == node_ns_utf:
|
237 |
+
tree.xmlSetNs(c_node, c_ns)
|
238 |
+
node_ns_utf = None
|
239 |
+
|
240 |
+
if node_ns_utf is not None:
|
241 |
+
_uriValidOrRaise(node_ns_utf)
|
242 |
+
doc._setNodeNs(c_node, _xcstr(node_ns_utf))
|
243 |
+
return 0
|
244 |
+
|
245 |
+
|
246 |
+
cdef dict _build_nsmap(xmlNode* c_node):
|
247 |
+
"""
|
248 |
+
Namespace prefix->URI mapping known in the context of this Element.
|
249 |
+
This includes all namespace declarations of the parents.
|
250 |
+
"""
|
251 |
+
cdef xmlNs* c_ns
|
252 |
+
nsmap = {}
|
253 |
+
while c_node is not NULL and c_node.type == tree.XML_ELEMENT_NODE:
|
254 |
+
c_ns = c_node.nsDef
|
255 |
+
while c_ns is not NULL:
|
256 |
+
if c_ns.prefix or c_ns.href:
|
257 |
+
prefix = funicodeOrNone(c_ns.prefix)
|
258 |
+
if prefix not in nsmap:
|
259 |
+
nsmap[prefix] = funicodeOrNone(c_ns.href)
|
260 |
+
c_ns = c_ns.next
|
261 |
+
c_node = c_node.parent
|
262 |
+
return nsmap
|
263 |
+
|
264 |
+
|
265 |
+
cdef _iter_nsmap(nsmap):
|
266 |
+
"""
|
267 |
+
Create a reproducibly ordered iterable from an nsmap mapping.
|
268 |
+
Tries to preserve an existing order and sorts if it assumes no order.
|
269 |
+
|
270 |
+
The difference to _iter_attrib() is that None doesn't sort with strings
|
271 |
+
in Py3.x.
|
272 |
+
"""
|
273 |
+
if isinstance(nsmap, dict):
|
274 |
+
# dicts are insertion-ordered in Py3.6+ => keep the user provided order.
|
275 |
+
return nsmap.items()
|
276 |
+
if len(nsmap) <= 1:
|
277 |
+
return nsmap.items()
|
278 |
+
# nsmap will usually be a plain unordered dict => avoid type checking overhead
|
279 |
+
if type(nsmap) is not dict and isinstance(nsmap, OrderedDict):
|
280 |
+
return nsmap.items() # keep existing order
|
281 |
+
if None not in nsmap:
|
282 |
+
return sorted(nsmap.items())
|
283 |
+
|
284 |
+
# Move the default namespace to the end. This makes sure libxml2
|
285 |
+
# prefers a prefix if the ns is defined redundantly on the same
|
286 |
+
# element. That way, users can work around a problem themselves
|
287 |
+
# where default namespace attributes on non-default namespaced
|
288 |
+
# elements serialise without prefix (i.e. into the non-default
|
289 |
+
# namespace).
|
290 |
+
default_ns = nsmap[None]
|
291 |
+
nsdefs = [(k, v) for k, v in nsmap.items() if k is not None]
|
292 |
+
nsdefs.sort()
|
293 |
+
nsdefs.append((None, default_ns))
|
294 |
+
return nsdefs
|
295 |
+
|
296 |
+
|
297 |
+
cdef _iter_attrib(attrib):
|
298 |
+
"""
|
299 |
+
Create a reproducibly ordered iterable from an attrib mapping.
|
300 |
+
Tries to preserve an existing order and sorts if it assumes no order.
|
301 |
+
"""
|
302 |
+
# dicts are insertion-ordered in Py3.6+ => keep the user provided order.
|
303 |
+
if isinstance(attrib, (dict, _Attrib, OrderedDict)):
|
304 |
+
return attrib.items()
|
305 |
+
# assume it's an unordered mapping of some kind
|
306 |
+
return sorted(attrib.items())
|
307 |
+
|
308 |
+
|
309 |
+
cdef _initNodeAttributes(xmlNode* c_node, _Document doc, attrib, dict extra):
|
310 |
+
"""Initialise the attributes of an element node.
|
311 |
+
"""
|
312 |
+
cdef bint is_html
|
313 |
+
cdef xmlNs* c_ns
|
314 |
+
if attrib is not None and not hasattr(attrib, 'items'):
|
315 |
+
raise TypeError, f"Invalid attribute dictionary: {python._fqtypename(attrib).decode('utf8')}"
|
316 |
+
if not attrib and not extra:
|
317 |
+
return # nothing to do
|
318 |
+
is_html = doc._parser._for_html
|
319 |
+
seen = set()
|
320 |
+
if extra:
|
321 |
+
for name, value in extra.items():
|
322 |
+
_addAttributeToNode(c_node, doc, is_html, name, value, seen)
|
323 |
+
if attrib:
|
324 |
+
for name, value in _iter_attrib(attrib):
|
325 |
+
_addAttributeToNode(c_node, doc, is_html, name, value, seen)
|
326 |
+
|
327 |
+
|
328 |
+
cdef int _addAttributeToNode(xmlNode* c_node, _Document doc, bint is_html,
|
329 |
+
name, value, set seen_tags) except -1:
|
330 |
+
ns_utf, name_utf = tag = _getNsTag(name)
|
331 |
+
if tag in seen_tags:
|
332 |
+
return 0
|
333 |
+
seen_tags.add(tag)
|
334 |
+
if not is_html:
|
335 |
+
_attributeValidOrRaise(name_utf)
|
336 |
+
value_utf = _utf8(value)
|
337 |
+
if ns_utf is None:
|
338 |
+
tree.xmlNewProp(c_node, _xcstr(name_utf), _xcstr(value_utf))
|
339 |
+
else:
|
340 |
+
_uriValidOrRaise(ns_utf)
|
341 |
+
c_ns = doc._findOrBuildNodeNs(c_node, _xcstr(ns_utf), NULL, 1)
|
342 |
+
tree.xmlNewNsProp(c_node, c_ns,
|
343 |
+
_xcstr(name_utf), _xcstr(value_utf))
|
344 |
+
return 0
|
345 |
+
|
346 |
+
|
347 |
+
ctypedef struct _ns_node_ref:
|
348 |
+
xmlNs* ns
|
349 |
+
xmlNode* node
|
350 |
+
|
351 |
+
|
352 |
+
cdef int _collectNsDefs(xmlNode* c_element, _ns_node_ref **_c_ns_list,
|
353 |
+
size_t *_c_ns_list_len, size_t *_c_ns_list_size) except -1:
|
354 |
+
c_ns_list = _c_ns_list[0]
|
355 |
+
cdef size_t c_ns_list_len = _c_ns_list_len[0]
|
356 |
+
cdef size_t c_ns_list_size = _c_ns_list_size[0]
|
357 |
+
|
358 |
+
c_nsdef = c_element.nsDef
|
359 |
+
while c_nsdef is not NULL:
|
360 |
+
if c_ns_list_len >= c_ns_list_size:
|
361 |
+
if c_ns_list is NULL:
|
362 |
+
c_ns_list_size = 20
|
363 |
+
else:
|
364 |
+
c_ns_list_size *= 2
|
365 |
+
c_nsref_ptr = <_ns_node_ref*> python.lxml_realloc(
|
366 |
+
c_ns_list, c_ns_list_size, sizeof(_ns_node_ref))
|
367 |
+
if c_nsref_ptr is NULL:
|
368 |
+
if c_ns_list is not NULL:
|
369 |
+
python.lxml_free(c_ns_list)
|
370 |
+
_c_ns_list[0] = NULL
|
371 |
+
raise MemoryError()
|
372 |
+
c_ns_list = c_nsref_ptr
|
373 |
+
|
374 |
+
c_ns_list[c_ns_list_len] = _ns_node_ref(c_nsdef, c_element)
|
375 |
+
c_ns_list_len += 1
|
376 |
+
c_nsdef = c_nsdef.next
|
377 |
+
|
378 |
+
_c_ns_list_size[0] = c_ns_list_size
|
379 |
+
_c_ns_list_len[0] = c_ns_list_len
|
380 |
+
_c_ns_list[0] = c_ns_list
|
381 |
+
|
382 |
+
|
383 |
+
cdef int _removeUnusedNamespaceDeclarations(xmlNode* c_element, set prefixes_to_keep) except -1:
|
384 |
+
"""Remove any namespace declarations from a subtree that are not used by
|
385 |
+
any of its elements (or attributes).
|
386 |
+
|
387 |
+
If a 'prefixes_to_keep' is provided, it must be a set of prefixes.
|
388 |
+
Any corresponding namespace mappings will not be removed as part of the cleanup.
|
389 |
+
"""
|
390 |
+
cdef xmlNode* c_node
|
391 |
+
cdef _ns_node_ref* c_ns_list = NULL
|
392 |
+
cdef size_t c_ns_list_size = 0
|
393 |
+
cdef size_t c_ns_list_len = 0
|
394 |
+
cdef size_t i
|
395 |
+
|
396 |
+
if c_element.parent and c_element.parent.type == tree.XML_DOCUMENT_NODE:
|
397 |
+
# include declarations on the document node
|
398 |
+
_collectNsDefs(c_element.parent, &c_ns_list, &c_ns_list_len, &c_ns_list_size)
|
399 |
+
|
400 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_element, c_element, 1)
|
401 |
+
# collect all new namespace declarations into the ns list
|
402 |
+
if c_element.nsDef:
|
403 |
+
_collectNsDefs(c_element, &c_ns_list, &c_ns_list_len, &c_ns_list_size)
|
404 |
+
|
405 |
+
# remove all namespace declarations from the list that are referenced
|
406 |
+
if c_ns_list_len and c_element.type == tree.XML_ELEMENT_NODE:
|
407 |
+
c_node = c_element
|
408 |
+
while c_node and c_ns_list_len:
|
409 |
+
if c_node.ns:
|
410 |
+
for i in range(c_ns_list_len):
|
411 |
+
if c_node.ns is c_ns_list[i].ns:
|
412 |
+
c_ns_list_len -= 1
|
413 |
+
c_ns_list[i] = c_ns_list[c_ns_list_len]
|
414 |
+
#c_ns_list[c_ns_list_len] = _ns_node_ref(NULL, NULL)
|
415 |
+
break
|
416 |
+
if c_node is c_element:
|
417 |
+
# continue with attributes
|
418 |
+
c_node = <xmlNode*>c_element.properties
|
419 |
+
else:
|
420 |
+
c_node = c_node.next
|
421 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_element)
|
422 |
+
|
423 |
+
if c_ns_list is NULL:
|
424 |
+
return 0
|
425 |
+
|
426 |
+
# free all namespace declarations that remained in the list,
|
427 |
+
# except for those we should keep explicitly
|
428 |
+
cdef xmlNs* c_nsdef
|
429 |
+
for i in range(c_ns_list_len):
|
430 |
+
if prefixes_to_keep is not None:
|
431 |
+
if c_ns_list[i].ns.prefix and c_ns_list[i].ns.prefix in prefixes_to_keep:
|
432 |
+
continue
|
433 |
+
c_node = c_ns_list[i].node
|
434 |
+
c_nsdef = c_node.nsDef
|
435 |
+
if c_nsdef is c_ns_list[i].ns:
|
436 |
+
c_node.nsDef = c_node.nsDef.next
|
437 |
+
else:
|
438 |
+
while c_nsdef.next is not c_ns_list[i].ns:
|
439 |
+
c_nsdef = c_nsdef.next
|
440 |
+
c_nsdef.next = c_nsdef.next.next
|
441 |
+
tree.xmlFreeNs(c_ns_list[i].ns)
|
442 |
+
|
443 |
+
if c_ns_list is not NULL:
|
444 |
+
python.lxml_free(c_ns_list)
|
445 |
+
return 0
|
446 |
+
|
447 |
+
cdef xmlNs* _searchNsByHref(xmlNode* c_node, const_xmlChar* c_href, bint is_attribute) noexcept:
|
448 |
+
"""Search a namespace declaration that covers a node (element or
|
449 |
+
attribute).
|
450 |
+
|
451 |
+
For attributes, try to find a prefixed namespace declaration
|
452 |
+
instead of the default namespaces. This helps in supporting
|
453 |
+
round-trips for attributes on elements with a different namespace.
|
454 |
+
"""
|
455 |
+
cdef xmlNs* c_ns
|
456 |
+
cdef xmlNs* c_default_ns = NULL
|
457 |
+
cdef xmlNode* c_element
|
458 |
+
if c_href is NULL or c_node is NULL or c_node.type == tree.XML_ENTITY_REF_NODE:
|
459 |
+
return NULL
|
460 |
+
if tree.xmlStrcmp(c_href, tree.XML_XML_NAMESPACE) == 0:
|
461 |
+
# no special cases here, let libxml2 handle this
|
462 |
+
return tree.xmlSearchNsByHref(c_node.doc, c_node, c_href)
|
463 |
+
if c_node.type == tree.XML_ATTRIBUTE_NODE:
|
464 |
+
is_attribute = 1
|
465 |
+
while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE:
|
466 |
+
c_node = c_node.parent
|
467 |
+
c_element = c_node
|
468 |
+
while c_node is not NULL:
|
469 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
470 |
+
c_ns = c_node.nsDef
|
471 |
+
while c_ns is not NULL:
|
472 |
+
if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0:
|
473 |
+
if c_ns.prefix is NULL and is_attribute:
|
474 |
+
# for attributes, continue searching a named
|
475 |
+
# prefix, but keep the first default namespace
|
476 |
+
# declaration that we found
|
477 |
+
if c_default_ns is NULL:
|
478 |
+
c_default_ns = c_ns
|
479 |
+
elif tree.xmlSearchNs(
|
480 |
+
c_element.doc, c_element, c_ns.prefix) is c_ns:
|
481 |
+
# start node is in namespace scope => found!
|
482 |
+
return c_ns
|
483 |
+
c_ns = c_ns.next
|
484 |
+
if c_node is not c_element and c_node.ns is not NULL:
|
485 |
+
# optimise: the node may have the namespace itself
|
486 |
+
c_ns = c_node.ns
|
487 |
+
if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0:
|
488 |
+
if c_ns.prefix is NULL and is_attribute:
|
489 |
+
# for attributes, continue searching a named
|
490 |
+
# prefix, but keep the first default namespace
|
491 |
+
# declaration that we found
|
492 |
+
if c_default_ns is NULL:
|
493 |
+
c_default_ns = c_ns
|
494 |
+
elif tree.xmlSearchNs(
|
495 |
+
c_element.doc, c_element, c_ns.prefix) is c_ns:
|
496 |
+
# start node is in namespace scope => found!
|
497 |
+
return c_ns
|
498 |
+
c_node = c_node.parent
|
499 |
+
# nothing found => use a matching default namespace or fail
|
500 |
+
if c_default_ns is not NULL:
|
501 |
+
if tree.xmlSearchNs(c_element.doc, c_element, NULL) is c_default_ns:
|
502 |
+
return c_default_ns
|
503 |
+
return NULL
|
504 |
+
|
505 |
+
cdef int _replaceNodeByChildren(_Document doc, xmlNode* c_node) except -1:
|
506 |
+
# NOTE: this does not deallocate the node, just unlink it!
|
507 |
+
cdef xmlNode* c_parent
|
508 |
+
cdef xmlNode* c_child
|
509 |
+
if c_node.children is NULL:
|
510 |
+
tree.xmlUnlinkNode(c_node)
|
511 |
+
return 0
|
512 |
+
|
513 |
+
c_parent = c_node.parent
|
514 |
+
# fix parent links of children
|
515 |
+
c_child = c_node.children
|
516 |
+
while c_child is not NULL:
|
517 |
+
c_child.parent = c_parent
|
518 |
+
c_child = c_child.next
|
519 |
+
|
520 |
+
# fix namespace references of children if their parent's namespace
|
521 |
+
# declarations get lost
|
522 |
+
if c_node.nsDef is not NULL:
|
523 |
+
c_child = c_node.children
|
524 |
+
while c_child is not NULL:
|
525 |
+
moveNodeToDocument(doc, doc._c_doc, c_child)
|
526 |
+
c_child = c_child.next
|
527 |
+
|
528 |
+
# fix sibling links to/from child slice
|
529 |
+
if c_node.prev is NULL:
|
530 |
+
c_parent.children = c_node.children
|
531 |
+
else:
|
532 |
+
c_node.prev.next = c_node.children
|
533 |
+
c_node.children.prev = c_node.prev
|
534 |
+
if c_node.next is NULL:
|
535 |
+
c_parent.last = c_node.last
|
536 |
+
else:
|
537 |
+
c_node.next.prev = c_node.last
|
538 |
+
c_node.last.next = c_node.next
|
539 |
+
|
540 |
+
# unlink c_node
|
541 |
+
c_node.children = c_node.last = NULL
|
542 |
+
c_node.parent = c_node.next = c_node.prev = NULL
|
543 |
+
return 0
|
544 |
+
|
545 |
+
cdef unicode _attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node):
|
546 |
+
c_href = _getNs(<xmlNode*>c_attrib_node)
|
547 |
+
value = tree.xmlGetNsProp(c_element, c_attrib_node.name, c_href)
|
548 |
+
try:
|
549 |
+
result = funicode(value)
|
550 |
+
finally:
|
551 |
+
tree.xmlFree(value)
|
552 |
+
return result
|
553 |
+
|
554 |
+
cdef unicode _attributeValueFromNsName(xmlNode* c_element,
|
555 |
+
const_xmlChar* c_href, const_xmlChar* c_name):
|
556 |
+
c_result = tree.xmlGetNsProp(c_element, c_name, c_href)
|
557 |
+
if c_result is NULL:
|
558 |
+
return None
|
559 |
+
try:
|
560 |
+
result = funicode(c_result)
|
561 |
+
finally:
|
562 |
+
tree.xmlFree(c_result)
|
563 |
+
return result
|
564 |
+
|
565 |
+
cdef object _getNodeAttributeValue(xmlNode* c_node, key, default):
|
566 |
+
ns, tag = _getNsTag(key)
|
567 |
+
c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
|
568 |
+
c_result = tree.xmlGetNsProp(c_node, _xcstr(tag), c_href)
|
569 |
+
if c_result is NULL:
|
570 |
+
# XXX free namespace that is not in use..?
|
571 |
+
return default
|
572 |
+
try:
|
573 |
+
result = funicode(c_result)
|
574 |
+
finally:
|
575 |
+
tree.xmlFree(c_result)
|
576 |
+
return result
|
577 |
+
|
578 |
+
cdef inline object _getAttributeValue(_Element element, key, default):
|
579 |
+
return _getNodeAttributeValue(element._c_node, key, default)
|
580 |
+
|
581 |
+
cdef int _setAttributeValue(_Element element, key, value) except -1:
|
582 |
+
cdef const_xmlChar* c_value
|
583 |
+
cdef xmlNs* c_ns
|
584 |
+
ns, tag = _getNsTag(key)
|
585 |
+
is_html = element._doc._parser._for_html
|
586 |
+
if not is_html:
|
587 |
+
_attributeValidOrRaise(tag)
|
588 |
+
c_tag = _xcstr(tag)
|
589 |
+
if value is None and is_html:
|
590 |
+
c_value = NULL
|
591 |
+
else:
|
592 |
+
if isinstance(value, QName):
|
593 |
+
value = _resolveQNameText(element, value)
|
594 |
+
else:
|
595 |
+
value = _utf8(value)
|
596 |
+
c_value = _xcstr(value)
|
597 |
+
if ns is None:
|
598 |
+
c_ns = NULL
|
599 |
+
else:
|
600 |
+
c_ns = element._doc._findOrBuildNodeNs(element._c_node, _xcstr(ns), NULL, 1)
|
601 |
+
tree.xmlSetNsProp(element._c_node, c_ns, c_tag, c_value)
|
602 |
+
return 0
|
603 |
+
|
604 |
+
cdef int _delAttribute(_Element element, key) except -1:
|
605 |
+
ns, tag = _getNsTag(key)
|
606 |
+
c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
|
607 |
+
if _delAttributeFromNsName(element._c_node, c_href, _xcstr(tag)):
|
608 |
+
raise KeyError, key
|
609 |
+
return 0
|
610 |
+
|
611 |
+
cdef int _delAttributeFromNsName(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
|
612 |
+
c_attr = tree.xmlHasNsProp(c_node, c_name, c_href)
|
613 |
+
if c_attr is NULL:
|
614 |
+
# XXX free namespace that is not in use..?
|
615 |
+
return -1
|
616 |
+
tree.xmlRemoveProp(c_attr)
|
617 |
+
return 0
|
618 |
+
|
619 |
+
cdef list _collectAttributes(xmlNode* c_node, int collecttype):
|
620 |
+
"""Collect all attributes of a node in a list. Depending on collecttype,
|
621 |
+
it collects either the name (1), the value (2) or the name-value tuples.
|
622 |
+
"""
|
623 |
+
cdef Py_ssize_t count
|
624 |
+
c_attr = c_node.properties
|
625 |
+
count = 0
|
626 |
+
while c_attr is not NULL:
|
627 |
+
if c_attr.type == tree.XML_ATTRIBUTE_NODE:
|
628 |
+
count += 1
|
629 |
+
c_attr = c_attr.next
|
630 |
+
|
631 |
+
if not count:
|
632 |
+
return []
|
633 |
+
|
634 |
+
attributes = [None] * count
|
635 |
+
c_attr = c_node.properties
|
636 |
+
count = 0
|
637 |
+
while c_attr is not NULL:
|
638 |
+
if c_attr.type == tree.XML_ATTRIBUTE_NODE:
|
639 |
+
if collecttype == 1:
|
640 |
+
item = _namespacedName(<xmlNode*>c_attr)
|
641 |
+
elif collecttype == 2:
|
642 |
+
item = _attributeValue(c_node, c_attr)
|
643 |
+
else:
|
644 |
+
item = (_namespacedName(<xmlNode*>c_attr),
|
645 |
+
_attributeValue(c_node, c_attr))
|
646 |
+
attributes[count] = item
|
647 |
+
count += 1
|
648 |
+
c_attr = c_attr.next
|
649 |
+
return attributes
|
650 |
+
|
651 |
+
cdef object __RE_XML_ENCODING = re.compile(
|
652 |
+
r'^(<\?xml[^>]+)\s+encoding\s*=\s*["\'][^"\']*["\'](\s*\?>|)', re.U)
|
653 |
+
|
654 |
+
cdef object __REPLACE_XML_ENCODING = __RE_XML_ENCODING.sub
|
655 |
+
cdef object __HAS_XML_ENCODING = __RE_XML_ENCODING.match
|
656 |
+
|
657 |
+
cdef object _stripEncodingDeclaration(object xml_string):
|
658 |
+
# this is a hack to remove the XML encoding declaration from unicode
|
659 |
+
return __REPLACE_XML_ENCODING(r'\g<1>\g<2>', xml_string)
|
660 |
+
|
661 |
+
cdef bint _hasEncodingDeclaration(object xml_string) except -1:
|
662 |
+
# check if a (unicode) string has an XML encoding declaration
|
663 |
+
return __HAS_XML_ENCODING(xml_string) is not None
|
664 |
+
|
665 |
+
cdef inline bint _hasText(xmlNode* c_node) noexcept:
|
666 |
+
return c_node is not NULL and _textNodeOrSkip(c_node.children) is not NULL
|
667 |
+
|
668 |
+
cdef inline bint _hasTail(xmlNode* c_node) noexcept:
|
669 |
+
return c_node is not NULL and _textNodeOrSkip(c_node.next) is not NULL
|
670 |
+
|
671 |
+
cdef inline bint _hasNonWhitespaceTail(xmlNode* c_node) except -1:
|
672 |
+
return _hasNonWhitespaceText(c_node, tail=True)
|
673 |
+
|
674 |
+
cdef bint _hasNonWhitespaceText(xmlNode* c_node, bint tail=False) except -1:
|
675 |
+
c_text_node = c_node and _textNodeOrSkip(c_node.next if tail else c_node.children)
|
676 |
+
if c_text_node is NULL:
|
677 |
+
return False
|
678 |
+
while c_text_node is not NULL:
|
679 |
+
if c_text_node.content[0] != c'\0' and not _collectText(c_text_node).isspace():
|
680 |
+
return True
|
681 |
+
c_text_node = _textNodeOrSkip(c_text_node.next)
|
682 |
+
return False
|
683 |
+
|
684 |
+
cdef unicode _collectText(xmlNode* c_node):
|
685 |
+
"""Collect all text nodes and return them as a unicode string.
|
686 |
+
|
687 |
+
Start collecting at c_node.
|
688 |
+
|
689 |
+
If there was no text to collect, return None
|
690 |
+
"""
|
691 |
+
cdef Py_ssize_t scount
|
692 |
+
cdef xmlChar* c_text
|
693 |
+
cdef xmlNode* c_node_cur
|
694 |
+
# check for multiple text nodes
|
695 |
+
scount = 0
|
696 |
+
c_text = NULL
|
697 |
+
c_node_cur = c_node = _textNodeOrSkip(c_node)
|
698 |
+
while c_node_cur is not NULL:
|
699 |
+
if c_node_cur.content[0] != c'\0':
|
700 |
+
c_text = c_node_cur.content
|
701 |
+
scount += 1
|
702 |
+
c_node_cur = _textNodeOrSkip(c_node_cur.next)
|
703 |
+
|
704 |
+
# handle two most common cases first
|
705 |
+
if c_text is NULL:
|
706 |
+
return '' if scount > 0 else None
|
707 |
+
if scount == 1:
|
708 |
+
return funicode(c_text)
|
709 |
+
|
710 |
+
# the rest is not performance critical anymore
|
711 |
+
result = b''
|
712 |
+
while c_node is not NULL:
|
713 |
+
result += <unsigned char*>c_node.content
|
714 |
+
c_node = _textNodeOrSkip(c_node.next)
|
715 |
+
return funicode(<const_xmlChar*><unsigned char*>result)
|
716 |
+
|
717 |
+
cdef void _removeText(xmlNode* c_node) noexcept:
|
718 |
+
"""Remove all text nodes.
|
719 |
+
|
720 |
+
Start removing at c_node.
|
721 |
+
"""
|
722 |
+
cdef xmlNode* c_next
|
723 |
+
c_node = _textNodeOrSkip(c_node)
|
724 |
+
while c_node is not NULL:
|
725 |
+
c_next = _textNodeOrSkip(c_node.next)
|
726 |
+
tree.xmlUnlinkNode(c_node)
|
727 |
+
tree.xmlFreeNode(c_node)
|
728 |
+
c_node = c_next
|
729 |
+
|
730 |
+
cdef xmlNode* _createTextNode(xmlDoc* doc, value) except NULL:
|
731 |
+
cdef xmlNode* c_text_node
|
732 |
+
if isinstance(value, CDATA):
|
733 |
+
c_text_node = tree.xmlNewCDataBlock(
|
734 |
+
doc, _xcstr((<CDATA>value)._utf8_data),
|
735 |
+
python.PyBytes_GET_SIZE((<CDATA>value)._utf8_data))
|
736 |
+
else:
|
737 |
+
text = _utf8(value)
|
738 |
+
c_text_node = tree.xmlNewDocText(doc, _xcstr(text))
|
739 |
+
if not c_text_node:
|
740 |
+
raise MemoryError()
|
741 |
+
return c_text_node
|
742 |
+
|
743 |
+
cdef int _setNodeText(xmlNode* c_node, value) except -1:
|
744 |
+
# remove all text nodes at the start first
|
745 |
+
_removeText(c_node.children)
|
746 |
+
if value is None:
|
747 |
+
return 0
|
748 |
+
# now add new text node with value at start
|
749 |
+
c_text_node = _createTextNode(c_node.doc, value)
|
750 |
+
if c_node.children is NULL:
|
751 |
+
tree.xmlAddChild(c_node, c_text_node)
|
752 |
+
else:
|
753 |
+
tree.xmlAddPrevSibling(c_node.children, c_text_node)
|
754 |
+
return 0
|
755 |
+
|
756 |
+
cdef int _setTailText(xmlNode* c_node, value) except -1:
|
757 |
+
# remove all text nodes at the start first
|
758 |
+
_removeText(c_node.next)
|
759 |
+
if value is None:
|
760 |
+
return 0
|
761 |
+
# now append new text node with value
|
762 |
+
c_text_node = _createTextNode(c_node.doc, value)
|
763 |
+
tree.xmlAddNextSibling(c_node, c_text_node)
|
764 |
+
return 0
|
765 |
+
|
766 |
+
cdef bytes _resolveQNameText(_Element element, value):
|
767 |
+
cdef xmlNs* c_ns
|
768 |
+
ns, tag = _getNsTag(value)
|
769 |
+
if ns is None:
|
770 |
+
return tag
|
771 |
+
else:
|
772 |
+
c_ns = element._doc._findOrBuildNodeNs(
|
773 |
+
element._c_node, _xcstr(ns), NULL, 0)
|
774 |
+
return python.PyBytes_FromFormat('%s:%s', c_ns.prefix, _cstr(tag))
|
775 |
+
|
776 |
+
cdef inline bint _hasChild(xmlNode* c_node) noexcept:
|
777 |
+
return c_node is not NULL and _findChildForwards(c_node, 0) is not NULL
|
778 |
+
|
779 |
+
cdef inline Py_ssize_t _countElements(xmlNode* c_node) noexcept:
|
780 |
+
"Counts the elements within the following siblings and the node itself."
|
781 |
+
cdef Py_ssize_t count
|
782 |
+
count = 0
|
783 |
+
while c_node is not NULL:
|
784 |
+
if _isElement(c_node):
|
785 |
+
count += 1
|
786 |
+
c_node = c_node.next
|
787 |
+
return count
|
788 |
+
|
789 |
+
cdef int _findChildSlice(
|
790 |
+
slice sliceobject, xmlNode* c_parent,
|
791 |
+
xmlNode** c_start_node, Py_ssize_t* c_step, Py_ssize_t* c_length) except -1:
|
792 |
+
"""Resolve a children slice.
|
793 |
+
|
794 |
+
Returns the start node, step size and the slice length in the
|
795 |
+
pointer arguments.
|
796 |
+
"""
|
797 |
+
cdef Py_ssize_t start = 0, stop = 0, childcount
|
798 |
+
childcount = _countElements(c_parent.children)
|
799 |
+
if childcount == 0:
|
800 |
+
c_start_node[0] = NULL
|
801 |
+
c_length[0] = 0
|
802 |
+
if sliceobject.step is None:
|
803 |
+
c_step[0] = 1
|
804 |
+
else:
|
805 |
+
python._PyEval_SliceIndex(sliceobject.step, c_step)
|
806 |
+
return 0
|
807 |
+
python.PySlice_GetIndicesEx(
|
808 |
+
sliceobject, childcount, &start, &stop, c_step, c_length)
|
809 |
+
if start > childcount // 2:
|
810 |
+
c_start_node[0] = _findChildBackwards(c_parent, childcount - start - 1)
|
811 |
+
else:
|
812 |
+
c_start_node[0] = _findChild(c_parent, start)
|
813 |
+
return 0
|
814 |
+
|
815 |
+
cdef bint _isFullSlice(slice sliceobject) except -1:
|
816 |
+
"""Conservative guess if this slice is a full slice as in ``s[:]``.
|
817 |
+
"""
|
818 |
+
cdef Py_ssize_t step = 0
|
819 |
+
if sliceobject is None:
|
820 |
+
return 0
|
821 |
+
if sliceobject.start is None and \
|
822 |
+
sliceobject.stop is None:
|
823 |
+
if sliceobject.step is None:
|
824 |
+
return 1
|
825 |
+
python._PyEval_SliceIndex(sliceobject.step, &step)
|
826 |
+
if step == 1:
|
827 |
+
return 1
|
828 |
+
return 0
|
829 |
+
return 0
|
830 |
+
|
831 |
+
cdef _collectChildren(_Element element):
|
832 |
+
cdef xmlNode* c_node
|
833 |
+
cdef list result = []
|
834 |
+
c_node = element._c_node.children
|
835 |
+
if c_node is not NULL:
|
836 |
+
if not _isElement(c_node):
|
837 |
+
c_node = _nextElement(c_node)
|
838 |
+
while c_node is not NULL:
|
839 |
+
result.append(_elementFactory(element._doc, c_node))
|
840 |
+
c_node = _nextElement(c_node)
|
841 |
+
return result
|
842 |
+
|
843 |
+
cdef inline xmlNode* _findChild(xmlNode* c_node, Py_ssize_t index) noexcept:
|
844 |
+
if index < 0:
|
845 |
+
return _findChildBackwards(c_node, -index - 1)
|
846 |
+
else:
|
847 |
+
return _findChildForwards(c_node, index)
|
848 |
+
|
849 |
+
cdef inline xmlNode* _findChildForwards(xmlNode* c_node, Py_ssize_t index) noexcept:
|
850 |
+
"""Return child element of c_node with index, or return NULL if not found.
|
851 |
+
"""
|
852 |
+
cdef xmlNode* c_child
|
853 |
+
cdef Py_ssize_t c
|
854 |
+
c_child = c_node.children
|
855 |
+
c = 0
|
856 |
+
while c_child is not NULL:
|
857 |
+
if _isElement(c_child):
|
858 |
+
if c == index:
|
859 |
+
return c_child
|
860 |
+
c += 1
|
861 |
+
c_child = c_child.next
|
862 |
+
return NULL
|
863 |
+
|
864 |
+
cdef inline xmlNode* _findChildBackwards(xmlNode* c_node, Py_ssize_t index) noexcept:
|
865 |
+
"""Return child element of c_node with index, or return NULL if not found.
|
866 |
+
Search from the end.
|
867 |
+
"""
|
868 |
+
cdef xmlNode* c_child
|
869 |
+
cdef Py_ssize_t c
|
870 |
+
c_child = c_node.last
|
871 |
+
c = 0
|
872 |
+
while c_child is not NULL:
|
873 |
+
if _isElement(c_child):
|
874 |
+
if c == index:
|
875 |
+
return c_child
|
876 |
+
c += 1
|
877 |
+
c_child = c_child.prev
|
878 |
+
return NULL
|
879 |
+
|
880 |
+
cdef inline xmlNode* _textNodeOrSkip(xmlNode* c_node) noexcept nogil:
|
881 |
+
"""Return the node if it's a text node. Skip over ignorable nodes in a
|
882 |
+
series of text nodes. Return NULL if a non-ignorable node is found.
|
883 |
+
|
884 |
+
This is used to skip over XInclude nodes when collecting adjacent text
|
885 |
+
nodes.
|
886 |
+
"""
|
887 |
+
while c_node is not NULL:
|
888 |
+
if c_node.type == tree.XML_TEXT_NODE or \
|
889 |
+
c_node.type == tree.XML_CDATA_SECTION_NODE:
|
890 |
+
return c_node
|
891 |
+
elif c_node.type == tree.XML_XINCLUDE_START or \
|
892 |
+
c_node.type == tree.XML_XINCLUDE_END:
|
893 |
+
c_node = c_node.next
|
894 |
+
else:
|
895 |
+
return NULL
|
896 |
+
return NULL
|
897 |
+
|
898 |
+
cdef inline xmlNode* _nextElement(xmlNode* c_node) noexcept:
|
899 |
+
"""Given a node, find the next sibling that is an element.
|
900 |
+
"""
|
901 |
+
if c_node is NULL:
|
902 |
+
return NULL
|
903 |
+
c_node = c_node.next
|
904 |
+
while c_node is not NULL:
|
905 |
+
if _isElement(c_node):
|
906 |
+
return c_node
|
907 |
+
c_node = c_node.next
|
908 |
+
return NULL
|
909 |
+
|
910 |
+
cdef inline xmlNode* _previousElement(xmlNode* c_node) noexcept:
|
911 |
+
"""Given a node, find the next sibling that is an element.
|
912 |
+
"""
|
913 |
+
if c_node is NULL:
|
914 |
+
return NULL
|
915 |
+
c_node = c_node.prev
|
916 |
+
while c_node is not NULL:
|
917 |
+
if _isElement(c_node):
|
918 |
+
return c_node
|
919 |
+
c_node = c_node.prev
|
920 |
+
return NULL
|
921 |
+
|
922 |
+
cdef inline xmlNode* _parentElement(xmlNode* c_node) noexcept:
|
923 |
+
"Given a node, find the parent element."
|
924 |
+
if c_node is NULL or not _isElement(c_node):
|
925 |
+
return NULL
|
926 |
+
c_node = c_node.parent
|
927 |
+
if c_node is NULL or not _isElement(c_node):
|
928 |
+
return NULL
|
929 |
+
return c_node
|
930 |
+
|
931 |
+
cdef inline bint _tagMatches(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
|
932 |
+
"""Tests if the node matches namespace URI and tag name.
|
933 |
+
|
934 |
+
A node matches if it matches both c_href and c_name.
|
935 |
+
|
936 |
+
A node matches c_href if any of the following is true:
|
937 |
+
* c_href is NULL
|
938 |
+
* its namespace is NULL and c_href is the empty string
|
939 |
+
* its namespace string equals the c_href string
|
940 |
+
|
941 |
+
A node matches c_name if any of the following is true:
|
942 |
+
* c_name is NULL
|
943 |
+
* its name string equals the c_name string
|
944 |
+
"""
|
945 |
+
if c_node is NULL:
|
946 |
+
return 0
|
947 |
+
if c_node.type != tree.XML_ELEMENT_NODE:
|
948 |
+
# not an element, only succeed if we match everything
|
949 |
+
return c_name is NULL and c_href is NULL
|
950 |
+
if c_name is NULL:
|
951 |
+
if c_href is NULL:
|
952 |
+
# always match
|
953 |
+
return 1
|
954 |
+
else:
|
955 |
+
c_node_href = _getNs(c_node)
|
956 |
+
if c_node_href is NULL:
|
957 |
+
return c_href[0] == c'\0'
|
958 |
+
else:
|
959 |
+
return tree.xmlStrcmp(c_node_href, c_href) == 0
|
960 |
+
elif c_href is NULL:
|
961 |
+
if _getNs(c_node) is not NULL:
|
962 |
+
return 0
|
963 |
+
return c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0
|
964 |
+
elif c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0:
|
965 |
+
c_node_href = _getNs(c_node)
|
966 |
+
if c_node_href is NULL:
|
967 |
+
return c_href[0] == c'\0'
|
968 |
+
else:
|
969 |
+
return tree.xmlStrcmp(c_node_href, c_href) == 0
|
970 |
+
else:
|
971 |
+
return 0
|
972 |
+
|
973 |
+
cdef inline bint _tagMatchesExactly(xmlNode* c_node, qname* c_qname) noexcept:
|
974 |
+
"""Tests if the node matches namespace URI and tag name.
|
975 |
+
|
976 |
+
This differs from _tagMatches() in that it does not consider a
|
977 |
+
NULL value in qname.href a wildcard, and that it expects the c_name
|
978 |
+
to be taken from the doc dict, i.e. it only compares the names by
|
979 |
+
address.
|
980 |
+
|
981 |
+
A node matches if it matches both href and c_name of the qname.
|
982 |
+
|
983 |
+
A node matches c_href if any of the following is true:
|
984 |
+
* its namespace is NULL and c_href is the empty string
|
985 |
+
* its namespace string equals the c_href string
|
986 |
+
|
987 |
+
A node matches c_name if any of the following is true:
|
988 |
+
* c_name is NULL
|
989 |
+
* its name string points to the same address (!) as c_name
|
990 |
+
"""
|
991 |
+
return _nsTagMatchesExactly(_getNs(c_node), c_node.name, c_qname)
|
992 |
+
|
993 |
+
cdef inline bint _nsTagMatchesExactly(const_xmlChar* c_node_href,
|
994 |
+
const_xmlChar* c_node_name,
|
995 |
+
qname* c_qname) noexcept:
|
996 |
+
"""Tests if name and namespace URI match those of c_qname.
|
997 |
+
|
998 |
+
This differs from _tagMatches() in that it does not consider a
|
999 |
+
NULL value in qname.href a wildcard, and that it expects the c_name
|
1000 |
+
to be taken from the doc dict, i.e. it only compares the names by
|
1001 |
+
address.
|
1002 |
+
|
1003 |
+
A node matches if it matches both href and c_name of the qname.
|
1004 |
+
|
1005 |
+
A node matches c_href if any of the following is true:
|
1006 |
+
* its namespace is NULL and c_href is the empty string
|
1007 |
+
* its namespace string equals the c_href string
|
1008 |
+
|
1009 |
+
A node matches c_name if any of the following is true:
|
1010 |
+
* c_name is NULL
|
1011 |
+
* its name string points to the same address (!) as c_name
|
1012 |
+
"""
|
1013 |
+
cdef char* c_href
|
1014 |
+
if c_qname.c_name is not NULL and c_qname.c_name is not c_node_name:
|
1015 |
+
return 0
|
1016 |
+
if c_qname.href is NULL:
|
1017 |
+
return 1
|
1018 |
+
c_href = python.__cstr(c_qname.href)
|
1019 |
+
if c_href[0] == b'\0':
|
1020 |
+
return c_node_href is NULL or c_node_href[0] == b'\0'
|
1021 |
+
elif c_node_href is NULL:
|
1022 |
+
return 0
|
1023 |
+
else:
|
1024 |
+
return tree.xmlStrcmp(<const_xmlChar*>c_href, c_node_href) == 0
|
1025 |
+
|
1026 |
+
cdef Py_ssize_t _mapTagsToQnameMatchArray(xmlDoc* c_doc, list ns_tags,
|
1027 |
+
qname* c_ns_tags, bint force_into_dict) except -1:
|
1028 |
+
"""Map a sequence of (name, namespace) pairs to a qname array for efficient
|
1029 |
+
matching with _tagMatchesExactly() above.
|
1030 |
+
|
1031 |
+
Note that each qname struct in the array owns its href byte string object
|
1032 |
+
if it is not NULL.
|
1033 |
+
"""
|
1034 |
+
cdef Py_ssize_t count = 0, i
|
1035 |
+
cdef bytes ns, tag
|
1036 |
+
for ns, tag in ns_tags:
|
1037 |
+
if tag is None:
|
1038 |
+
c_tag = <const_xmlChar*>NULL
|
1039 |
+
elif force_into_dict:
|
1040 |
+
c_tag = tree.xmlDictLookup(c_doc.dict, _xcstr(tag), len(tag))
|
1041 |
+
if c_tag is NULL:
|
1042 |
+
# clean up before raising the error
|
1043 |
+
for i in xrange(count):
|
1044 |
+
cpython.ref.Py_XDECREF(c_ns_tags[i].href)
|
1045 |
+
raise MemoryError()
|
1046 |
+
else:
|
1047 |
+
c_tag = tree.xmlDictExists(c_doc.dict, _xcstr(tag), len(tag))
|
1048 |
+
if c_tag is NULL:
|
1049 |
+
# not in the dict => not in the document
|
1050 |
+
continue
|
1051 |
+
c_ns_tags[count].c_name = c_tag
|
1052 |
+
if ns is None:
|
1053 |
+
c_ns_tags[count].href = NULL
|
1054 |
+
else:
|
1055 |
+
cpython.ref.Py_INCREF(ns) # keep an owned reference!
|
1056 |
+
c_ns_tags[count].href = <python.PyObject*>ns
|
1057 |
+
count += 1
|
1058 |
+
return count
|
1059 |
+
|
1060 |
+
cdef int _removeNode(_Document doc, xmlNode* c_node) except -1:
|
1061 |
+
"""Unlink and free a node and subnodes if possible. Otherwise, make sure
|
1062 |
+
it's self-contained.
|
1063 |
+
"""
|
1064 |
+
cdef xmlNode* c_next
|
1065 |
+
c_next = c_node.next
|
1066 |
+
tree.xmlUnlinkNode(c_node)
|
1067 |
+
_moveTail(c_next, c_node)
|
1068 |
+
if not attemptDeallocation(c_node):
|
1069 |
+
# make namespaces absolute
|
1070 |
+
moveNodeToDocument(doc, c_node.doc, c_node)
|
1071 |
+
return 0
|
1072 |
+
|
1073 |
+
cdef int _removeSiblings(xmlNode* c_element, tree.xmlElementType node_type, bint with_tail) except -1:
|
1074 |
+
cdef xmlNode* c_node
|
1075 |
+
cdef xmlNode* c_next
|
1076 |
+
c_node = c_element.next
|
1077 |
+
while c_node is not NULL:
|
1078 |
+
c_next = _nextElement(c_node)
|
1079 |
+
if c_node.type == node_type:
|
1080 |
+
if with_tail:
|
1081 |
+
_removeText(c_node.next)
|
1082 |
+
tree.xmlUnlinkNode(c_node)
|
1083 |
+
attemptDeallocation(c_node)
|
1084 |
+
c_node = c_next
|
1085 |
+
c_node = c_element.prev
|
1086 |
+
while c_node is not NULL:
|
1087 |
+
c_next = _previousElement(c_node)
|
1088 |
+
if c_node.type == node_type:
|
1089 |
+
if with_tail:
|
1090 |
+
_removeText(c_node.next)
|
1091 |
+
tree.xmlUnlinkNode(c_node)
|
1092 |
+
attemptDeallocation(c_node)
|
1093 |
+
c_node = c_next
|
1094 |
+
return 0
|
1095 |
+
|
1096 |
+
cdef void _moveTail(xmlNode* c_tail, xmlNode* c_target) noexcept:
|
1097 |
+
cdef xmlNode* c_next
|
1098 |
+
# tail support: look for any text nodes trailing this node and
|
1099 |
+
# move them too
|
1100 |
+
c_tail = _textNodeOrSkip(c_tail)
|
1101 |
+
while c_tail is not NULL:
|
1102 |
+
c_next = _textNodeOrSkip(c_tail.next)
|
1103 |
+
c_target = tree.xmlAddNextSibling(c_target, c_tail)
|
1104 |
+
c_tail = c_next
|
1105 |
+
|
1106 |
+
cdef int _copyTail(xmlNode* c_tail, xmlNode* c_target) except -1:
|
1107 |
+
cdef xmlNode* c_new_tail
|
1108 |
+
# tail copying support: look for any text nodes trailing this node and
|
1109 |
+
# copy it to the target node
|
1110 |
+
c_tail = _textNodeOrSkip(c_tail)
|
1111 |
+
while c_tail is not NULL:
|
1112 |
+
if c_target.doc is not c_tail.doc:
|
1113 |
+
c_new_tail = tree.xmlDocCopyNode(c_tail, c_target.doc, 0)
|
1114 |
+
else:
|
1115 |
+
c_new_tail = tree.xmlCopyNode(c_tail, 0)
|
1116 |
+
if c_new_tail is NULL:
|
1117 |
+
raise MemoryError()
|
1118 |
+
c_target = tree.xmlAddNextSibling(c_target, c_new_tail)
|
1119 |
+
c_tail = _textNodeOrSkip(c_tail.next)
|
1120 |
+
return 0
|
1121 |
+
|
1122 |
+
cdef int _copyNonElementSiblings(xmlNode* c_node, xmlNode* c_target) except -1:
|
1123 |
+
cdef xmlNode* c_copy
|
1124 |
+
cdef xmlNode* c_sibling = c_node
|
1125 |
+
while c_sibling.prev != NULL and \
|
1126 |
+
(c_sibling.prev.type == tree.XML_PI_NODE or
|
1127 |
+
c_sibling.prev.type == tree.XML_COMMENT_NODE or
|
1128 |
+
c_sibling.prev.type == tree.XML_DTD_NODE):
|
1129 |
+
c_sibling = c_sibling.prev
|
1130 |
+
while c_sibling != c_node:
|
1131 |
+
if c_sibling.type == tree.XML_DTD_NODE:
|
1132 |
+
c_copy = <xmlNode*>_copyDtd(<tree.xmlDtd*>c_sibling)
|
1133 |
+
if c_sibling == <xmlNode*>c_node.doc.intSubset:
|
1134 |
+
c_target.doc.intSubset = <tree.xmlDtd*>c_copy
|
1135 |
+
else: # c_sibling == c_node.doc.extSubset
|
1136 |
+
c_target.doc.extSubset = <tree.xmlDtd*>c_copy
|
1137 |
+
else:
|
1138 |
+
c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1)
|
1139 |
+
if c_copy is NULL:
|
1140 |
+
raise MemoryError()
|
1141 |
+
tree.xmlAddPrevSibling(c_target, c_copy)
|
1142 |
+
c_sibling = c_sibling.next
|
1143 |
+
while c_sibling.next != NULL and \
|
1144 |
+
(c_sibling.next.type == tree.XML_PI_NODE or
|
1145 |
+
c_sibling.next.type == tree.XML_COMMENT_NODE):
|
1146 |
+
c_sibling = c_sibling.next
|
1147 |
+
c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1)
|
1148 |
+
if c_copy is NULL:
|
1149 |
+
raise MemoryError()
|
1150 |
+
tree.xmlAddNextSibling(c_target, c_copy)
|
1151 |
+
|
1152 |
+
cdef int _deleteSlice(_Document doc, xmlNode* c_node,
|
1153 |
+
Py_ssize_t count, Py_ssize_t step) except -1:
|
1154 |
+
"""Delete slice, ``count`` items starting with ``c_node`` with a step
|
1155 |
+
width of ``step``.
|
1156 |
+
"""
|
1157 |
+
cdef xmlNode* c_next
|
1158 |
+
cdef Py_ssize_t c, i
|
1159 |
+
cdef _node_to_node_function next_element
|
1160 |
+
if c_node is NULL:
|
1161 |
+
return 0
|
1162 |
+
if step > 0:
|
1163 |
+
next_element = _nextElement
|
1164 |
+
else:
|
1165 |
+
step = -step
|
1166 |
+
next_element = _previousElement
|
1167 |
+
# now start deleting nodes
|
1168 |
+
c = 0
|
1169 |
+
c_next = c_node
|
1170 |
+
while c_node is not NULL and c < count:
|
1171 |
+
for i in range(step):
|
1172 |
+
c_next = next_element(c_next)
|
1173 |
+
if c_next is NULL:
|
1174 |
+
break
|
1175 |
+
_removeNode(doc, c_node)
|
1176 |
+
c += 1
|
1177 |
+
c_node = c_next
|
1178 |
+
return 0
|
1179 |
+
|
1180 |
+
cdef int _replaceSlice(_Element parent, xmlNode* c_node,
|
1181 |
+
Py_ssize_t slicelength, Py_ssize_t step,
|
1182 |
+
bint left_to_right, elements) except -1:
|
1183 |
+
"""Replace the slice of ``count`` elements starting at ``c_node`` with
|
1184 |
+
positive step width ``step`` by the Elements in ``elements``. The
|
1185 |
+
direction is given by the boolean argument ``left_to_right``.
|
1186 |
+
|
1187 |
+
``c_node`` may be NULL to indicate the end of the children list.
|
1188 |
+
"""
|
1189 |
+
cdef xmlNode* c_orig_neighbour
|
1190 |
+
cdef xmlNode* c_next
|
1191 |
+
cdef xmlDoc* c_source_doc
|
1192 |
+
cdef _Element element
|
1193 |
+
cdef Py_ssize_t seqlength, i, c
|
1194 |
+
cdef _node_to_node_function next_element
|
1195 |
+
assert step > 0
|
1196 |
+
if left_to_right:
|
1197 |
+
next_element = _nextElement
|
1198 |
+
else:
|
1199 |
+
next_element = _previousElement
|
1200 |
+
|
1201 |
+
if not isinstance(elements, (list, tuple)):
|
1202 |
+
elements = list(elements)
|
1203 |
+
|
1204 |
+
if step != 1 or not left_to_right:
|
1205 |
+
# *replacing* children stepwise with list => check size!
|
1206 |
+
seqlength = len(elements)
|
1207 |
+
if seqlength != slicelength:
|
1208 |
+
raise ValueError, f"attempt to assign sequence of size {seqlength} " \
|
1209 |
+
f"to extended slice of size {slicelength}"
|
1210 |
+
|
1211 |
+
if c_node is NULL:
|
1212 |
+
# no children yet => add all elements straight away
|
1213 |
+
if left_to_right:
|
1214 |
+
for element in elements:
|
1215 |
+
assert element is not None, "Node must not be None"
|
1216 |
+
_appendChild(parent, element)
|
1217 |
+
else:
|
1218 |
+
for element in elements:
|
1219 |
+
assert element is not None, "Node must not be None"
|
1220 |
+
_prependChild(parent, element)
|
1221 |
+
return 0
|
1222 |
+
|
1223 |
+
# remove the elements first as some might be re-added
|
1224 |
+
if left_to_right:
|
1225 |
+
# L->R, remember left neighbour
|
1226 |
+
c_orig_neighbour = _previousElement(c_node)
|
1227 |
+
else:
|
1228 |
+
# R->L, remember right neighbour
|
1229 |
+
c_orig_neighbour = _nextElement(c_node)
|
1230 |
+
|
1231 |
+
# We remove the original slice elements one by one. Since we hold
|
1232 |
+
# a Python reference to all elements that we will insert, it is
|
1233 |
+
# safe to let _removeNode() try (and fail) to free them even if
|
1234 |
+
# the element itself or one of its descendents will be reinserted.
|
1235 |
+
c = 0
|
1236 |
+
c_next = c_node
|
1237 |
+
while c_node is not NULL and c < slicelength:
|
1238 |
+
for i in range(step):
|
1239 |
+
c_next = next_element(c_next)
|
1240 |
+
if c_next is NULL:
|
1241 |
+
break
|
1242 |
+
_removeNode(parent._doc, c_node)
|
1243 |
+
c += 1
|
1244 |
+
c_node = c_next
|
1245 |
+
|
1246 |
+
# make sure each element is inserted only once
|
1247 |
+
elements = iter(elements)
|
1248 |
+
|
1249 |
+
# find the first node right of the new insertion point
|
1250 |
+
if left_to_right:
|
1251 |
+
if c_orig_neighbour is not NULL:
|
1252 |
+
c_node = next_element(c_orig_neighbour)
|
1253 |
+
else:
|
1254 |
+
# before the first element
|
1255 |
+
c_node = _findChildForwards(parent._c_node, 0)
|
1256 |
+
elif c_orig_neighbour is NULL:
|
1257 |
+
# at the end, but reversed stepping
|
1258 |
+
# append one element and go to the next insertion point
|
1259 |
+
for element in elements:
|
1260 |
+
assert element is not None, "Node must not be None"
|
1261 |
+
_appendChild(parent, element)
|
1262 |
+
c_node = element._c_node
|
1263 |
+
if slicelength > 0:
|
1264 |
+
slicelength -= 1
|
1265 |
+
for i in range(1, step):
|
1266 |
+
c_node = next_element(c_node)
|
1267 |
+
if c_node is NULL:
|
1268 |
+
break
|
1269 |
+
break
|
1270 |
+
else:
|
1271 |
+
c_node = c_orig_neighbour
|
1272 |
+
|
1273 |
+
if left_to_right:
|
1274 |
+
# adjust step size after removing slice as we are not stepping
|
1275 |
+
# over the newly inserted elements
|
1276 |
+
step -= 1
|
1277 |
+
|
1278 |
+
# now insert elements where we removed them
|
1279 |
+
if c_node is not NULL:
|
1280 |
+
for element in elements:
|
1281 |
+
assert element is not None, "Node must not be None"
|
1282 |
+
_assertValidNode(element)
|
1283 |
+
# move element and tail over
|
1284 |
+
c_source_doc = element._c_node.doc
|
1285 |
+
c_next = element._c_node.next
|
1286 |
+
tree.xmlAddPrevSibling(c_node, element._c_node)
|
1287 |
+
_moveTail(c_next, element._c_node)
|
1288 |
+
|
1289 |
+
# integrate element into new document
|
1290 |
+
moveNodeToDocument(parent._doc, c_source_doc, element._c_node)
|
1291 |
+
|
1292 |
+
# stop at the end of the slice
|
1293 |
+
if slicelength > 0:
|
1294 |
+
slicelength -= 1
|
1295 |
+
for i in range(step):
|
1296 |
+
c_node = next_element(c_node)
|
1297 |
+
if c_node is NULL:
|
1298 |
+
break
|
1299 |
+
if c_node is NULL:
|
1300 |
+
break
|
1301 |
+
else:
|
1302 |
+
# everything inserted
|
1303 |
+
return 0
|
1304 |
+
|
1305 |
+
# append the remaining elements at the respective end
|
1306 |
+
if left_to_right:
|
1307 |
+
for element in elements:
|
1308 |
+
assert element is not None, "Node must not be None"
|
1309 |
+
_assertValidNode(element)
|
1310 |
+
_appendChild(parent, element)
|
1311 |
+
else:
|
1312 |
+
for element in elements:
|
1313 |
+
assert element is not None, "Node must not be None"
|
1314 |
+
_assertValidNode(element)
|
1315 |
+
_prependChild(parent, element)
|
1316 |
+
|
1317 |
+
return 0
|
1318 |
+
|
1319 |
+
|
1320 |
+
cdef int _linkChild(xmlNode* c_parent, xmlNode* c_node) except -1:
|
1321 |
+
"""Adaptation of 'xmlAddChild()' that deep-fix the document links iteratively.
|
1322 |
+
"""
|
1323 |
+
assert _isElement(c_node)
|
1324 |
+
c_node.parent = c_parent
|
1325 |
+
if c_parent.children is NULL:
|
1326 |
+
c_parent.children = c_parent.last = c_node
|
1327 |
+
else:
|
1328 |
+
c_node.prev = c_parent.last
|
1329 |
+
c_parent.last.next = c_node
|
1330 |
+
c_parent.last = c_node
|
1331 |
+
|
1332 |
+
_setTreeDoc(c_node, c_parent.doc)
|
1333 |
+
return 0
|
1334 |
+
|
1335 |
+
|
1336 |
+
cdef int _appendChild(_Element parent, _Element child) except -1:
|
1337 |
+
"""Append a new child to a parent element.
|
1338 |
+
"""
|
1339 |
+
c_node = child._c_node
|
1340 |
+
c_source_doc = c_node.doc
|
1341 |
+
# prevent cycles
|
1342 |
+
if _isAncestorOrSame(c_node, parent._c_node):
|
1343 |
+
raise ValueError("cannot append parent to itself")
|
1344 |
+
# store possible text node
|
1345 |
+
c_next = c_node.next
|
1346 |
+
# move node itself
|
1347 |
+
tree.xmlUnlinkNode(c_node)
|
1348 |
+
# do not call xmlAddChild() here since it would deep-traverse the tree
|
1349 |
+
_linkChild(parent._c_node, c_node)
|
1350 |
+
_moveTail(c_next, c_node)
|
1351 |
+
# uh oh, elements may be pointing to different doc when
|
1352 |
+
# parent element has moved; change them too..
|
1353 |
+
moveNodeToDocument(parent._doc, c_source_doc, c_node)
|
1354 |
+
return 0
|
1355 |
+
|
1356 |
+
cdef int _prependChild(_Element parent, _Element child) except -1:
|
1357 |
+
"""Prepend a new child to a parent element.
|
1358 |
+
"""
|
1359 |
+
c_node = child._c_node
|
1360 |
+
c_source_doc = c_node.doc
|
1361 |
+
# prevent cycles
|
1362 |
+
if _isAncestorOrSame(c_node, parent._c_node):
|
1363 |
+
raise ValueError("cannot append parent to itself")
|
1364 |
+
# store possible text node
|
1365 |
+
c_next = c_node.next
|
1366 |
+
# move node itself
|
1367 |
+
c_child = _findChildForwards(parent._c_node, 0)
|
1368 |
+
if c_child is NULL:
|
1369 |
+
tree.xmlUnlinkNode(c_node)
|
1370 |
+
# do not call xmlAddChild() here since it would deep-traverse the tree
|
1371 |
+
_linkChild(parent._c_node, c_node)
|
1372 |
+
else:
|
1373 |
+
tree.xmlAddPrevSibling(c_child, c_node)
|
1374 |
+
_moveTail(c_next, c_node)
|
1375 |
+
# uh oh, elements may be pointing to different doc when
|
1376 |
+
# parent element has moved; change them too..
|
1377 |
+
moveNodeToDocument(parent._doc, c_source_doc, c_node)
|
1378 |
+
return 0
|
1379 |
+
|
1380 |
+
cdef int _appendSibling(_Element element, _Element sibling) except -1:
|
1381 |
+
"""Add a new sibling behind an element.
|
1382 |
+
"""
|
1383 |
+
return _addSibling(element, sibling, as_next=True)
|
1384 |
+
|
1385 |
+
cdef int _prependSibling(_Element element, _Element sibling) except -1:
|
1386 |
+
"""Add a new sibling before an element.
|
1387 |
+
"""
|
1388 |
+
return _addSibling(element, sibling, as_next=False)
|
1389 |
+
|
1390 |
+
cdef int _addSibling(_Element element, _Element sibling, bint as_next) except -1:
|
1391 |
+
c_node = sibling._c_node
|
1392 |
+
c_source_doc = c_node.doc
|
1393 |
+
# prevent cycles
|
1394 |
+
if _isAncestorOrSame(c_node, element._c_node):
|
1395 |
+
if element._c_node is c_node:
|
1396 |
+
return 0 # nothing to do
|
1397 |
+
raise ValueError("cannot add ancestor as sibling, please break cycle first")
|
1398 |
+
# store possible text node
|
1399 |
+
c_next = c_node.next
|
1400 |
+
# move node itself
|
1401 |
+
if as_next:
|
1402 |
+
# must insert after any tail text
|
1403 |
+
c_next_node = _nextElement(element._c_node)
|
1404 |
+
if c_next_node is NULL:
|
1405 |
+
c_next_node = element._c_node
|
1406 |
+
while c_next_node.next:
|
1407 |
+
c_next_node = c_next_node.next
|
1408 |
+
tree.xmlAddNextSibling(c_next_node, c_node)
|
1409 |
+
else:
|
1410 |
+
tree.xmlAddPrevSibling(c_next_node, c_node)
|
1411 |
+
else:
|
1412 |
+
tree.xmlAddPrevSibling(element._c_node, c_node)
|
1413 |
+
_moveTail(c_next, c_node)
|
1414 |
+
# uh oh, elements may be pointing to different doc when
|
1415 |
+
# parent element has moved; change them too..
|
1416 |
+
moveNodeToDocument(element._doc, c_source_doc, c_node)
|
1417 |
+
return 0
|
1418 |
+
|
1419 |
+
cdef inline bint isutf8(const_xmlChar* s) noexcept:
|
1420 |
+
cdef xmlChar c = s[0]
|
1421 |
+
while c != c'\0':
|
1422 |
+
if c & 0x80:
|
1423 |
+
return True
|
1424 |
+
s += 1
|
1425 |
+
c = s[0]
|
1426 |
+
return False
|
1427 |
+
|
1428 |
+
cdef bint isutf8l(const_xmlChar* s, size_t length) noexcept:
|
1429 |
+
"""
|
1430 |
+
Search for non-ASCII characters in the string, knowing its length in advance.
|
1431 |
+
"""
|
1432 |
+
cdef unsigned int i
|
1433 |
+
cdef unsigned long non_ascii_mask
|
1434 |
+
cdef const unsigned long *lptr = <const unsigned long*> s
|
1435 |
+
|
1436 |
+
cdef const unsigned long *end = lptr + length // sizeof(unsigned long)
|
1437 |
+
if length >= sizeof(non_ascii_mask):
|
1438 |
+
# Build constant 0x80808080... mask (and let the C compiler fold it).
|
1439 |
+
non_ascii_mask = 0
|
1440 |
+
for i in range(sizeof(non_ascii_mask) // 2):
|
1441 |
+
non_ascii_mask = (non_ascii_mask << 16) | 0x8080
|
1442 |
+
|
1443 |
+
# Advance to long-aligned character before we start reading longs.
|
1444 |
+
while (<size_t>s) % sizeof(unsigned long) and s < <const_xmlChar *>end:
|
1445 |
+
if s[0] & 0x80:
|
1446 |
+
return True
|
1447 |
+
s += 1
|
1448 |
+
|
1449 |
+
# Read one long at a time
|
1450 |
+
lptr = <const unsigned long*> s
|
1451 |
+
while lptr < end:
|
1452 |
+
if lptr[0] & non_ascii_mask:
|
1453 |
+
return True
|
1454 |
+
lptr += 1
|
1455 |
+
s = <const_xmlChar *>lptr
|
1456 |
+
|
1457 |
+
while s < (<const_xmlChar *>end + length % sizeof(unsigned long)):
|
1458 |
+
if s[0] & 0x80:
|
1459 |
+
return True
|
1460 |
+
s += 1
|
1461 |
+
|
1462 |
+
return False
|
1463 |
+
|
1464 |
+
cdef int _is_valid_xml_ascii(bytes pystring) except -1:
|
1465 |
+
"""Check if a string is XML ascii content."""
|
1466 |
+
cdef signed char ch
|
1467 |
+
# When ch is a *signed* char, non-ascii characters are negative integers
|
1468 |
+
# and xmlIsChar_ch does not accept them.
|
1469 |
+
for ch in pystring:
|
1470 |
+
if not tree.xmlIsChar_ch(ch):
|
1471 |
+
return 0
|
1472 |
+
return 1
|
1473 |
+
|
1474 |
+
cdef bint _is_valid_xml_utf8(bytes pystring) except -1:
|
1475 |
+
"""Check if a string is like valid UTF-8 XML content."""
|
1476 |
+
cdef const_xmlChar* s = _xcstr(pystring)
|
1477 |
+
cdef const_xmlChar* c_end = s + len(pystring)
|
1478 |
+
cdef unsigned long next3 = 0
|
1479 |
+
if s < c_end - 2:
|
1480 |
+
next3 = (s[0] << 8) | (s[1])
|
1481 |
+
|
1482 |
+
while s < c_end - 2:
|
1483 |
+
next3 = 0x00ffffff & ((next3 << 8) | s[2])
|
1484 |
+
if s[0] & 0x80:
|
1485 |
+
# 0xefbfbe and 0xefbfbf are utf-8 encodings of
|
1486 |
+
# forbidden characters \ufffe and \uffff
|
1487 |
+
if next3 == 0x00efbfbe or next3 == 0x00efbfbf:
|
1488 |
+
return 0
|
1489 |
+
# 0xeda080 and 0xedbfbf are utf-8 encodings of
|
1490 |
+
# \ud800 and \udfff. Anything between them (inclusive)
|
1491 |
+
# is forbidden, because they are surrogate blocks in utf-16.
|
1492 |
+
if 0x00eda080 <= next3 <= 0x00edbfbf:
|
1493 |
+
return 0
|
1494 |
+
elif not tree.xmlIsChar_ch(s[0]):
|
1495 |
+
return 0 # invalid ascii char
|
1496 |
+
s += 1
|
1497 |
+
|
1498 |
+
while s < c_end:
|
1499 |
+
if not s[0] & 0x80 and not tree.xmlIsChar_ch(s[0]):
|
1500 |
+
return 0 # invalid ascii char
|
1501 |
+
s += 1
|
1502 |
+
|
1503 |
+
return 1
|
1504 |
+
|
1505 |
+
cdef inline unicode funicodeOrNone(const_xmlChar* s):
|
1506 |
+
return funicode(s) if s is not NULL else None
|
1507 |
+
|
1508 |
+
cdef inline unicode funicodeOrEmpty(const_xmlChar* s):
|
1509 |
+
return funicode(s) if s is not NULL else ''
|
1510 |
+
|
1511 |
+
cdef unicode funicode(const_xmlChar* s):
|
1512 |
+
return s.decode('UTF-8')
|
1513 |
+
|
1514 |
+
cdef bytes _utf8(object s):
|
1515 |
+
"""Test if a string is valid user input and encode it to UTF-8.
|
1516 |
+
Reject all bytes/unicode input that contains non-XML characters.
|
1517 |
+
Reject all bytes input that contains non-ASCII characters.
|
1518 |
+
"""
|
1519 |
+
cdef int valid
|
1520 |
+
cdef bytes utf8_string
|
1521 |
+
if isinstance(s, unicode):
|
1522 |
+
utf8_string = (<unicode>s).encode('utf8')
|
1523 |
+
valid = _is_valid_xml_utf8(utf8_string)
|
1524 |
+
elif isinstance(s, (bytes, bytearray)):
|
1525 |
+
utf8_string = s if type(s) is bytes else bytes(s)
|
1526 |
+
valid = _is_valid_xml_ascii(utf8_string)
|
1527 |
+
else:
|
1528 |
+
raise TypeError("Argument must be bytes or unicode, got '%.200s'" % type(s).__name__)
|
1529 |
+
if not valid:
|
1530 |
+
raise ValueError(
|
1531 |
+
"All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters")
|
1532 |
+
return utf8_string
|
1533 |
+
|
1534 |
+
|
1535 |
+
cdef bytes _utf8orNone(object s):
|
1536 |
+
return _utf8(s) if s is not None else None
|
1537 |
+
|
1538 |
+
|
1539 |
+
cdef enum:
|
1540 |
+
NO_FILE_PATH = 0
|
1541 |
+
ABS_UNIX_FILE_PATH = 1
|
1542 |
+
ABS_WIN_FILE_PATH = 2
|
1543 |
+
REL_FILE_PATH = 3
|
1544 |
+
|
1545 |
+
|
1546 |
+
cdef bint _isFilePath(const_xmlChar* c_path) noexcept:
|
1547 |
+
"simple heuristic to see if a path is a filename"
|
1548 |
+
cdef xmlChar c
|
1549 |
+
# test if it looks like an absolute Unix path or a Windows network path
|
1550 |
+
if c_path[0] == c'/':
|
1551 |
+
return ABS_UNIX_FILE_PATH
|
1552 |
+
|
1553 |
+
# test if it looks like an absolute Windows path or URL
|
1554 |
+
if c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z':
|
1555 |
+
c_path += 1
|
1556 |
+
if c_path[0] == c':' and c_path[1] in b'\0\\':
|
1557 |
+
return ABS_WIN_FILE_PATH # C: or C:\...
|
1558 |
+
|
1559 |
+
# test if it looks like a URL with scheme://
|
1560 |
+
while c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z':
|
1561 |
+
c_path += 1
|
1562 |
+
if c_path[0] == c':' and c_path[1] == c'/' and c_path[2] == c'/':
|
1563 |
+
return NO_FILE_PATH
|
1564 |
+
|
1565 |
+
# assume it's a relative path
|
1566 |
+
return REL_FILE_PATH
|
1567 |
+
|
1568 |
+
|
1569 |
+
cdef object _getFSPathOrObject(object obj):
|
1570 |
+
"""
|
1571 |
+
Get the __fspath__ attribute of an object if it exists.
|
1572 |
+
Otherwise, the original object is returned.
|
1573 |
+
"""
|
1574 |
+
if _isString(obj):
|
1575 |
+
return obj
|
1576 |
+
try:
|
1577 |
+
return python.PyOS_FSPath(obj)
|
1578 |
+
except TypeError:
|
1579 |
+
return obj
|
1580 |
+
|
1581 |
+
|
1582 |
+
cdef object _encodeFilename(object filename):
|
1583 |
+
"""Make sure a filename is 8-bit encoded (or None).
|
1584 |
+
"""
|
1585 |
+
if filename is None:
|
1586 |
+
return None
|
1587 |
+
elif isinstance(filename, bytes):
|
1588 |
+
return filename
|
1589 |
+
elif isinstance(filename, unicode):
|
1590 |
+
filename8 = (<unicode>filename).encode('utf8')
|
1591 |
+
if _isFilePath(<unsigned char*>filename8):
|
1592 |
+
try:
|
1593 |
+
return python.PyUnicode_AsEncodedString(
|
1594 |
+
filename, _C_FILENAME_ENCODING, NULL)
|
1595 |
+
except UnicodeEncodeError:
|
1596 |
+
pass
|
1597 |
+
return filename8
|
1598 |
+
else:
|
1599 |
+
raise TypeError("Argument must be string or unicode.")
|
1600 |
+
|
1601 |
+
cdef object _decodeFilename(const_xmlChar* c_path):
|
1602 |
+
"""Make the filename a unicode string if we are in Py3.
|
1603 |
+
"""
|
1604 |
+
return _decodeFilenameWithLength(c_path, tree.xmlStrlen(c_path))
|
1605 |
+
|
1606 |
+
cdef object _decodeFilenameWithLength(const_xmlChar* c_path, size_t c_len):
|
1607 |
+
"""Make the filename a unicode string if we are in Py3.
|
1608 |
+
"""
|
1609 |
+
if _isFilePath(c_path):
|
1610 |
+
try:
|
1611 |
+
return python.PyUnicode_Decode(
|
1612 |
+
<const_char*>c_path, c_len, _C_FILENAME_ENCODING, NULL)
|
1613 |
+
except UnicodeDecodeError:
|
1614 |
+
pass
|
1615 |
+
try:
|
1616 |
+
return (<unsigned char*>c_path)[:c_len].decode('UTF-8')
|
1617 |
+
except UnicodeDecodeError:
|
1618 |
+
# this is a stupid fallback, but it might still work...
|
1619 |
+
return (<unsigned char*>c_path)[:c_len].decode('latin-1', 'replace')
|
1620 |
+
|
1621 |
+
cdef object _encodeFilenameUTF8(object filename):
|
1622 |
+
"""Recode filename as UTF-8. Tries ASCII, local filesystem encoding and
|
1623 |
+
UTF-8 as source encoding.
|
1624 |
+
"""
|
1625 |
+
cdef char* c_filename
|
1626 |
+
if filename is None:
|
1627 |
+
return None
|
1628 |
+
elif isinstance(filename, bytes):
|
1629 |
+
if not isutf8l(<bytes>filename, len(<bytes>filename)):
|
1630 |
+
# plain ASCII!
|
1631 |
+
return filename
|
1632 |
+
c_filename = _cstr(<bytes>filename)
|
1633 |
+
try:
|
1634 |
+
# try to decode with default encoding
|
1635 |
+
filename = python.PyUnicode_Decode(
|
1636 |
+
c_filename, len(<bytes>filename),
|
1637 |
+
_C_FILENAME_ENCODING, NULL)
|
1638 |
+
except UnicodeDecodeError as decode_exc:
|
1639 |
+
try:
|
1640 |
+
# try if it's proper UTF-8
|
1641 |
+
(<bytes>filename).decode('utf8')
|
1642 |
+
return filename
|
1643 |
+
except UnicodeDecodeError:
|
1644 |
+
raise decode_exc # otherwise re-raise original exception
|
1645 |
+
if isinstance(filename, unicode):
|
1646 |
+
return (<unicode>filename).encode('utf8')
|
1647 |
+
else:
|
1648 |
+
raise TypeError("Argument must be string or unicode.")
|
1649 |
+
|
1650 |
+
cdef tuple _getNsTag(tag):
|
1651 |
+
"""Given a tag, find namespace URI and tag name.
|
1652 |
+
Return None for NS uri if no namespace URI provided.
|
1653 |
+
"""
|
1654 |
+
return __getNsTag(tag, 0)
|
1655 |
+
|
1656 |
+
cdef tuple _getNsTagWithEmptyNs(tag):
|
1657 |
+
"""Given a tag, find namespace URI and tag name. Return None for NS uri
|
1658 |
+
if no namespace URI provided, or the empty string if namespace
|
1659 |
+
part is '{}'.
|
1660 |
+
"""
|
1661 |
+
return __getNsTag(tag, 1)
|
1662 |
+
|
1663 |
+
cdef tuple __getNsTag(tag, bint empty_ns):
|
1664 |
+
cdef char* c_tag
|
1665 |
+
cdef char* c_ns_end
|
1666 |
+
cdef Py_ssize_t taglen
|
1667 |
+
cdef Py_ssize_t nslen
|
1668 |
+
cdef bytes ns = None
|
1669 |
+
# _isString() is much faster than isinstance()
|
1670 |
+
if not _isString(tag) and isinstance(tag, QName):
|
1671 |
+
tag = (<QName>tag).text
|
1672 |
+
tag = _utf8(tag)
|
1673 |
+
c_tag = _cstr(tag)
|
1674 |
+
if c_tag[0] == c'{':
|
1675 |
+
c_tag += 1
|
1676 |
+
c_ns_end = cstring_h.strchr(c_tag, c'}')
|
1677 |
+
if c_ns_end is NULL:
|
1678 |
+
raise ValueError, "Invalid tag name"
|
1679 |
+
nslen = c_ns_end - c_tag
|
1680 |
+
taglen = python.PyBytes_GET_SIZE(tag) - nslen - 2
|
1681 |
+
if taglen == 0:
|
1682 |
+
raise ValueError, "Empty tag name"
|
1683 |
+
if nslen > 0:
|
1684 |
+
ns = <bytes>c_tag[:nslen]
|
1685 |
+
elif empty_ns:
|
1686 |
+
ns = b''
|
1687 |
+
tag = <bytes>c_ns_end[1:taglen+1]
|
1688 |
+
elif python.PyBytes_GET_SIZE(tag) == 0:
|
1689 |
+
raise ValueError, "Empty tag name"
|
1690 |
+
return ns, tag
|
1691 |
+
|
1692 |
+
cdef inline int _pyXmlNameIsValid(name_utf8):
|
1693 |
+
return _xmlNameIsValid(_xcstr(name_utf8)) and b':' not in name_utf8
|
1694 |
+
|
1695 |
+
cdef inline int _pyHtmlNameIsValid(name_utf8):
|
1696 |
+
return _htmlNameIsValid(_xcstr(name_utf8))
|
1697 |
+
|
1698 |
+
cdef inline int _xmlNameIsValid(const_xmlChar* c_name) noexcept:
|
1699 |
+
return tree.xmlValidateNameValue(c_name)
|
1700 |
+
|
1701 |
+
cdef int _htmlNameIsValid(const_xmlChar* c_name) noexcept:
|
1702 |
+
if c_name is NULL or c_name[0] == c'\0':
|
1703 |
+
return 0
|
1704 |
+
while c_name[0] != c'\0':
|
1705 |
+
if c_name[0] in b'&<>/"\'\t\n\x0B\x0C\r ':
|
1706 |
+
return 0
|
1707 |
+
c_name += 1
|
1708 |
+
return 1
|
1709 |
+
|
1710 |
+
cdef bint _characterReferenceIsValid(const_xmlChar* c_name) noexcept:
|
1711 |
+
cdef bint is_hex
|
1712 |
+
if c_name[0] == c'x':
|
1713 |
+
c_name += 1
|
1714 |
+
is_hex = 1
|
1715 |
+
else:
|
1716 |
+
is_hex = 0
|
1717 |
+
if c_name[0] == c'\0':
|
1718 |
+
return 0
|
1719 |
+
while c_name[0] != c'\0':
|
1720 |
+
if c_name[0] < c'0' or c_name[0] > c'9':
|
1721 |
+
if not is_hex:
|
1722 |
+
return 0
|
1723 |
+
if not (c'a' <= c_name[0] <= c'f'):
|
1724 |
+
if not (c'A' <= c_name[0] <= c'F'):
|
1725 |
+
return 0
|
1726 |
+
c_name += 1
|
1727 |
+
return 1
|
1728 |
+
|
1729 |
+
cdef int _tagValidOrRaise(tag_utf) except -1:
|
1730 |
+
if not _pyXmlNameIsValid(tag_utf):
|
1731 |
+
raise ValueError(f"Invalid tag name {(<bytes>tag_utf).decode('utf8')!r}")
|
1732 |
+
return 0
|
1733 |
+
|
1734 |
+
cdef int _htmlTagValidOrRaise(tag_utf) except -1:
|
1735 |
+
if not _pyHtmlNameIsValid(tag_utf):
|
1736 |
+
raise ValueError(f"Invalid HTML tag name {(<bytes>tag_utf).decode('utf8')!r}")
|
1737 |
+
return 0
|
1738 |
+
|
1739 |
+
cdef int _attributeValidOrRaise(name_utf) except -1:
|
1740 |
+
if not _pyXmlNameIsValid(name_utf):
|
1741 |
+
raise ValueError(f"Invalid attribute name {(<bytes>name_utf).decode('utf8')!r}")
|
1742 |
+
return 0
|
1743 |
+
|
1744 |
+
cdef int _prefixValidOrRaise(tag_utf) except -1:
|
1745 |
+
if not _pyXmlNameIsValid(tag_utf):
|
1746 |
+
raise ValueError(f"Invalid namespace prefix {(<bytes>tag_utf).decode('utf8')!r}")
|
1747 |
+
return 0
|
1748 |
+
|
1749 |
+
cdef int _uriValidOrRaise(uri_utf) except -1:
|
1750 |
+
cdef uri.xmlURI* c_uri = uri.xmlParseURI(_cstr(uri_utf))
|
1751 |
+
if c_uri is NULL:
|
1752 |
+
raise ValueError(f"Invalid namespace URI {(<bytes>uri_utf).decode('utf8')!r}")
|
1753 |
+
uri.xmlFreeURI(c_uri)
|
1754 |
+
return 0
|
1755 |
+
|
1756 |
+
cdef inline unicode _namespacedName(xmlNode* c_node):
|
1757 |
+
return _namespacedNameFromNsName(_getNs(c_node), c_node.name)
|
1758 |
+
|
1759 |
+
|
1760 |
+
cdef unicode _namespacedNameFromNsName(const_xmlChar* c_href, const_xmlChar* c_name):
|
1761 |
+
name = funicode(c_name)
|
1762 |
+
if c_href is NULL:
|
1763 |
+
return name
|
1764 |
+
href = funicode(c_href)
|
1765 |
+
return f"{{{href}}}{name}"
|
1766 |
+
|
1767 |
+
|
1768 |
+
cdef _getFilenameForFile(source):
|
1769 |
+
"""Given a Python File or Gzip object, give filename back.
|
1770 |
+
|
1771 |
+
Returns None if not a file object.
|
1772 |
+
"""
|
1773 |
+
# urllib2 provides a geturl() method
|
1774 |
+
try:
|
1775 |
+
return source.geturl()
|
1776 |
+
except:
|
1777 |
+
pass
|
1778 |
+
# file instances have a name attribute
|
1779 |
+
try:
|
1780 |
+
filename = source.name
|
1781 |
+
if _isString(filename):
|
1782 |
+
return os_path_abspath(filename)
|
1783 |
+
except:
|
1784 |
+
pass
|
1785 |
+
# gzip file instances have a filename attribute (before Py3k)
|
1786 |
+
try:
|
1787 |
+
filename = source.filename
|
1788 |
+
if _isString(filename):
|
1789 |
+
return os_path_abspath(filename)
|
1790 |
+
except:
|
1791 |
+
pass
|
1792 |
+
# can't determine filename
|
1793 |
+
return None
|
env-llmeval/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (112 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/lxml/builder.py
ADDED
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: language_level=2
|
2 |
+
|
3 |
+
#
|
4 |
+
# Element generator factory by Fredrik Lundh.
|
5 |
+
#
|
6 |
+
# Source:
|
7 |
+
# http://online.effbot.org/2006_11_01_archive.htm#et-builder
|
8 |
+
# http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/builder.py
|
9 |
+
#
|
10 |
+
# --------------------------------------------------------------------
|
11 |
+
# The ElementTree toolkit is
|
12 |
+
#
|
13 |
+
# Copyright (c) 1999-2004 by Fredrik Lundh
|
14 |
+
#
|
15 |
+
# By obtaining, using, and/or copying this software and/or its
|
16 |
+
# associated documentation, you agree that you have read, understood,
|
17 |
+
# and will comply with the following terms and conditions:
|
18 |
+
#
|
19 |
+
# Permission to use, copy, modify, and distribute this software and
|
20 |
+
# its associated documentation for any purpose and without fee is
|
21 |
+
# hereby granted, provided that the above copyright notice appears in
|
22 |
+
# all copies, and that both that copyright notice and this permission
|
23 |
+
# notice appear in supporting documentation, and that the name of
|
24 |
+
# Secret Labs AB or the author not be used in advertising or publicity
|
25 |
+
# pertaining to distribution of the software without specific, written
|
26 |
+
# prior permission.
|
27 |
+
#
|
28 |
+
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
|
29 |
+
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
|
30 |
+
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
|
31 |
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
|
32 |
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
33 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
34 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
35 |
+
# OF THIS SOFTWARE.
|
36 |
+
# --------------------------------------------------------------------
|
37 |
+
|
38 |
+
"""
|
39 |
+
The ``E`` Element factory for generating XML documents.
|
40 |
+
"""
|
41 |
+
|
42 |
+
|
43 |
+
import lxml.etree as ET
|
44 |
+
_QName = ET.QName
|
45 |
+
|
46 |
+
from functools import partial
|
47 |
+
|
48 |
+
try:
|
49 |
+
basestring
|
50 |
+
except NameError:
|
51 |
+
basestring = str
|
52 |
+
|
53 |
+
try:
|
54 |
+
unicode
|
55 |
+
except NameError:
|
56 |
+
unicode = str
|
57 |
+
|
58 |
+
|
59 |
+
class ElementMaker:
|
60 |
+
"""Element generator factory.
|
61 |
+
|
62 |
+
Unlike the ordinary Element factory, the E factory allows you to pass in
|
63 |
+
more than just a tag and some optional attributes; you can also pass in
|
64 |
+
text and other elements. The text is added as either text or tail
|
65 |
+
attributes, and elements are inserted at the right spot. Some small
|
66 |
+
examples::
|
67 |
+
|
68 |
+
>>> from lxml import etree as ET
|
69 |
+
>>> from lxml.builder import E
|
70 |
+
|
71 |
+
>>> ET.tostring(E("tag"))
|
72 |
+
'<tag/>'
|
73 |
+
>>> ET.tostring(E("tag", "text"))
|
74 |
+
'<tag>text</tag>'
|
75 |
+
>>> ET.tostring(E("tag", "text", key="value"))
|
76 |
+
'<tag key="value">text</tag>'
|
77 |
+
>>> ET.tostring(E("tag", E("subtag", "text"), "tail"))
|
78 |
+
'<tag><subtag>text</subtag>tail</tag>'
|
79 |
+
|
80 |
+
For simple tags, the factory also allows you to write ``E.tag(...)`` instead
|
81 |
+
of ``E('tag', ...)``::
|
82 |
+
|
83 |
+
>>> ET.tostring(E.tag())
|
84 |
+
'<tag/>'
|
85 |
+
>>> ET.tostring(E.tag("text"))
|
86 |
+
'<tag>text</tag>'
|
87 |
+
>>> ET.tostring(E.tag(E.subtag("text"), "tail"))
|
88 |
+
'<tag><subtag>text</subtag>tail</tag>'
|
89 |
+
|
90 |
+
Here's a somewhat larger example; this shows how to generate HTML
|
91 |
+
documents, using a mix of prepared factory functions for inline elements,
|
92 |
+
nested ``E.tag`` calls, and embedded XHTML fragments::
|
93 |
+
|
94 |
+
# some common inline elements
|
95 |
+
A = E.a
|
96 |
+
I = E.i
|
97 |
+
B = E.b
|
98 |
+
|
99 |
+
def CLASS(v):
|
100 |
+
# helper function, 'class' is a reserved word
|
101 |
+
return {'class': v}
|
102 |
+
|
103 |
+
page = (
|
104 |
+
E.html(
|
105 |
+
E.head(
|
106 |
+
E.title("This is a sample document")
|
107 |
+
),
|
108 |
+
E.body(
|
109 |
+
E.h1("Hello!", CLASS("title")),
|
110 |
+
E.p("This is a paragraph with ", B("bold"), " text in it!"),
|
111 |
+
E.p("This is another paragraph, with a ",
|
112 |
+
A("link", href="http://www.python.org"), "."),
|
113 |
+
E.p("Here are some reserved characters: <spam&egg>."),
|
114 |
+
ET.XML("<p>And finally, here is an embedded XHTML fragment.</p>"),
|
115 |
+
)
|
116 |
+
)
|
117 |
+
)
|
118 |
+
|
119 |
+
print ET.tostring(page)
|
120 |
+
|
121 |
+
Here's a prettyprinted version of the output from the above script::
|
122 |
+
|
123 |
+
<html>
|
124 |
+
<head>
|
125 |
+
<title>This is a sample document</title>
|
126 |
+
</head>
|
127 |
+
<body>
|
128 |
+
<h1 class="title">Hello!</h1>
|
129 |
+
<p>This is a paragraph with <b>bold</b> text in it!</p>
|
130 |
+
<p>This is another paragraph, with <a href="http://www.python.org">link</a>.</p>
|
131 |
+
<p>Here are some reserved characters: <spam&egg>.</p>
|
132 |
+
<p>And finally, here is an embedded XHTML fragment.</p>
|
133 |
+
</body>
|
134 |
+
</html>
|
135 |
+
|
136 |
+
For namespace support, you can pass a namespace map (``nsmap``)
|
137 |
+
and/or a specific target ``namespace`` to the ElementMaker class::
|
138 |
+
|
139 |
+
>>> E = ElementMaker(namespace="http://my.ns/")
|
140 |
+
>>> print(ET.tostring( E.test ))
|
141 |
+
<test xmlns="http://my.ns/"/>
|
142 |
+
|
143 |
+
>>> E = ElementMaker(namespace="http://my.ns/", nsmap={'p':'http://my.ns/'})
|
144 |
+
>>> print(ET.tostring( E.test ))
|
145 |
+
<p:test xmlns:p="http://my.ns/"/>
|
146 |
+
"""
|
147 |
+
|
148 |
+
def __init__(self, typemap=None,
|
149 |
+
namespace=None, nsmap=None, makeelement=None):
|
150 |
+
self._namespace = '{' + namespace + '}' if namespace is not None else None
|
151 |
+
self._nsmap = dict(nsmap) if nsmap else None
|
152 |
+
|
153 |
+
assert makeelement is None or callable(makeelement)
|
154 |
+
self._makeelement = makeelement if makeelement is not None else ET.Element
|
155 |
+
|
156 |
+
# initialize the default type map functions for this element factory
|
157 |
+
typemap = dict(typemap) if typemap else {}
|
158 |
+
|
159 |
+
def add_text(elem, item):
|
160 |
+
try:
|
161 |
+
last_child = elem[-1]
|
162 |
+
except IndexError:
|
163 |
+
elem.text = (elem.text or "") + item
|
164 |
+
else:
|
165 |
+
last_child.tail = (last_child.tail or "") + item
|
166 |
+
|
167 |
+
def add_cdata(elem, cdata):
|
168 |
+
if elem.text:
|
169 |
+
raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
|
170 |
+
elem.text = cdata
|
171 |
+
|
172 |
+
if str not in typemap:
|
173 |
+
typemap[str] = add_text
|
174 |
+
if unicode not in typemap:
|
175 |
+
typemap[unicode] = add_text
|
176 |
+
if ET.CDATA not in typemap:
|
177 |
+
typemap[ET.CDATA] = add_cdata
|
178 |
+
|
179 |
+
def add_dict(elem, item):
|
180 |
+
attrib = elem.attrib
|
181 |
+
for k, v in item.items():
|
182 |
+
if isinstance(v, basestring):
|
183 |
+
attrib[k] = v
|
184 |
+
else:
|
185 |
+
attrib[k] = typemap[type(v)](None, v)
|
186 |
+
|
187 |
+
if dict not in typemap:
|
188 |
+
typemap[dict] = add_dict
|
189 |
+
|
190 |
+
self._typemap = typemap
|
191 |
+
|
192 |
+
def __call__(self, tag, *children, **attrib):
|
193 |
+
typemap = self._typemap
|
194 |
+
|
195 |
+
# We'll usually get a 'str', and the compiled type check is very fast.
|
196 |
+
if not isinstance(tag, str) and isinstance(tag, _QName):
|
197 |
+
# A QName is explicitly qualified, do not look at self._namespace.
|
198 |
+
tag = tag.text
|
199 |
+
elif self._namespace is not None and tag[0] != '{':
|
200 |
+
tag = self._namespace + tag
|
201 |
+
elem = self._makeelement(tag, nsmap=self._nsmap)
|
202 |
+
if attrib:
|
203 |
+
typemap[dict](elem, attrib)
|
204 |
+
|
205 |
+
for item in children:
|
206 |
+
if callable(item):
|
207 |
+
item = item()
|
208 |
+
t = typemap.get(type(item))
|
209 |
+
if t is None:
|
210 |
+
if ET.iselement(item):
|
211 |
+
elem.append(item)
|
212 |
+
continue
|
213 |
+
for basetype in type(item).__mro__:
|
214 |
+
# See if the typemap knows of any of this type's bases.
|
215 |
+
t = typemap.get(basetype)
|
216 |
+
if t is not None:
|
217 |
+
break
|
218 |
+
else:
|
219 |
+
raise TypeError("bad argument type: %s(%r)" %
|
220 |
+
(type(item).__name__, item))
|
221 |
+
v = t(elem, item)
|
222 |
+
if v:
|
223 |
+
typemap.get(type(v))(elem, v)
|
224 |
+
|
225 |
+
return elem
|
226 |
+
|
227 |
+
def __getattr__(self, tag):
|
228 |
+
return partial(self, tag)
|
229 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Configurable Element class lookup
|
2 |
+
|
3 |
+
################################################################################
|
4 |
+
# Custom Element classes
|
5 |
+
|
6 |
+
cdef public class ElementBase(_Element) [ type LxmlElementBaseType,
|
7 |
+
object LxmlElementBase ]:
|
8 |
+
"""ElementBase(*children, attrib=None, nsmap=None, **_extra)
|
9 |
+
|
10 |
+
The public Element class. All custom Element classes must inherit
|
11 |
+
from this one. To create an Element, use the `Element()` factory.
|
12 |
+
|
13 |
+
BIG FAT WARNING: Subclasses *must not* override __init__ or
|
14 |
+
__new__ as it is absolutely undefined when these objects will be
|
15 |
+
created or destroyed. All persistent state of Elements must be
|
16 |
+
stored in the underlying XML. If you really need to initialize
|
17 |
+
the object after creation, you can implement an ``_init(self)``
|
18 |
+
method that will be called directly after object creation.
|
19 |
+
|
20 |
+
Subclasses of this class can be instantiated to create a new
|
21 |
+
Element. By default, the tag name will be the class name and the
|
22 |
+
namespace will be empty. You can modify this with the following
|
23 |
+
class attributes:
|
24 |
+
|
25 |
+
* TAG - the tag name, possibly containing a namespace in Clark
|
26 |
+
notation
|
27 |
+
|
28 |
+
* NAMESPACE - the default namespace URI, unless provided as part
|
29 |
+
of the TAG attribute.
|
30 |
+
|
31 |
+
* HTML - flag if the class is an HTML tag, as opposed to an XML
|
32 |
+
tag. This only applies to un-namespaced tags and defaults to
|
33 |
+
false (i.e. XML).
|
34 |
+
|
35 |
+
* PARSER - the parser that provides the configuration for the
|
36 |
+
newly created document. Providing an HTML parser here will
|
37 |
+
default to creating an HTML element.
|
38 |
+
|
39 |
+
In user code, the latter three are commonly inherited in class
|
40 |
+
hierarchies that implement a common namespace.
|
41 |
+
"""
|
42 |
+
def __init__(self, *children, attrib=None, nsmap=None, **_extra):
|
43 |
+
"""ElementBase(*children, attrib=None, nsmap=None, **_extra)
|
44 |
+
"""
|
45 |
+
cdef bint is_html = 0
|
46 |
+
cdef _BaseParser parser
|
47 |
+
cdef _Element last_child
|
48 |
+
# don't use normal attribute access as it might be overridden
|
49 |
+
_getattr = object.__getattribute__
|
50 |
+
try:
|
51 |
+
namespace = _utf8(_getattr(self, 'NAMESPACE'))
|
52 |
+
except AttributeError:
|
53 |
+
namespace = None
|
54 |
+
try:
|
55 |
+
ns, tag = _getNsTag(_getattr(self, 'TAG'))
|
56 |
+
if ns is not None:
|
57 |
+
namespace = ns
|
58 |
+
except AttributeError:
|
59 |
+
tag = _utf8(_getattr(_getattr(self, '__class__'), '__name__'))
|
60 |
+
if b'.' in tag:
|
61 |
+
tag = tag.split(b'.')[-1]
|
62 |
+
try:
|
63 |
+
parser = _getattr(self, 'PARSER')
|
64 |
+
except AttributeError:
|
65 |
+
parser = None
|
66 |
+
for child in children:
|
67 |
+
if isinstance(child, _Element):
|
68 |
+
parser = (<_Element>child)._doc._parser
|
69 |
+
break
|
70 |
+
if isinstance(parser, HTMLParser):
|
71 |
+
is_html = 1
|
72 |
+
if namespace is None:
|
73 |
+
try:
|
74 |
+
is_html = _getattr(self, 'HTML')
|
75 |
+
except AttributeError:
|
76 |
+
pass
|
77 |
+
_initNewElement(self, is_html, tag, namespace, parser,
|
78 |
+
attrib, nsmap, _extra)
|
79 |
+
last_child = None
|
80 |
+
for child in children:
|
81 |
+
if _isString(child):
|
82 |
+
if last_child is None:
|
83 |
+
_setNodeText(self._c_node,
|
84 |
+
(_collectText(self._c_node.children) or '') + child)
|
85 |
+
else:
|
86 |
+
_setTailText(last_child._c_node,
|
87 |
+
(_collectText(last_child._c_node.next) or '') + child)
|
88 |
+
elif isinstance(child, _Element):
|
89 |
+
last_child = child
|
90 |
+
_appendChild(self, last_child)
|
91 |
+
elif isinstance(child, type) and issubclass(child, ElementBase):
|
92 |
+
last_child = child()
|
93 |
+
_appendChild(self, last_child)
|
94 |
+
else:
|
95 |
+
raise TypeError, f"Invalid child type: {type(child)!r}"
|
96 |
+
|
97 |
+
cdef class CommentBase(_Comment):
|
98 |
+
"""All custom Comment classes must inherit from this one.
|
99 |
+
|
100 |
+
To create an XML Comment instance, use the ``Comment()`` factory.
|
101 |
+
|
102 |
+
Subclasses *must not* override __init__ or __new__ as it is
|
103 |
+
absolutely undefined when these objects will be created or
|
104 |
+
destroyed. All persistent state of Comments must be stored in the
|
105 |
+
underlying XML. If you really need to initialize the object after
|
106 |
+
creation, you can implement an ``_init(self)`` method that will be
|
107 |
+
called after object creation.
|
108 |
+
"""
|
109 |
+
def __init__(self, text):
|
110 |
+
# copied from Comment() factory
|
111 |
+
cdef _Document doc
|
112 |
+
cdef xmlDoc* c_doc
|
113 |
+
if text is None:
|
114 |
+
text = b''
|
115 |
+
else:
|
116 |
+
text = _utf8(text)
|
117 |
+
c_doc = _newXMLDoc()
|
118 |
+
doc = _documentFactory(c_doc, None)
|
119 |
+
self._c_node = _createComment(c_doc, _xcstr(text))
|
120 |
+
if self._c_node is NULL:
|
121 |
+
raise MemoryError()
|
122 |
+
tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
|
123 |
+
_registerProxy(self, doc, self._c_node)
|
124 |
+
self._init()
|
125 |
+
|
126 |
+
cdef class PIBase(_ProcessingInstruction):
|
127 |
+
"""All custom Processing Instruction classes must inherit from this one.
|
128 |
+
|
129 |
+
To create an XML ProcessingInstruction instance, use the ``PI()``
|
130 |
+
factory.
|
131 |
+
|
132 |
+
Subclasses *must not* override __init__ or __new__ as it is
|
133 |
+
absolutely undefined when these objects will be created or
|
134 |
+
destroyed. All persistent state of PIs must be stored in the
|
135 |
+
underlying XML. If you really need to initialize the object after
|
136 |
+
creation, you can implement an ``_init(self)`` method that will be
|
137 |
+
called after object creation.
|
138 |
+
"""
|
139 |
+
def __init__(self, target, text=None):
|
140 |
+
# copied from PI() factory
|
141 |
+
cdef _Document doc
|
142 |
+
cdef xmlDoc* c_doc
|
143 |
+
target = _utf8(target)
|
144 |
+
if text is None:
|
145 |
+
text = b''
|
146 |
+
else:
|
147 |
+
text = _utf8(text)
|
148 |
+
c_doc = _newXMLDoc()
|
149 |
+
doc = _documentFactory(c_doc, None)
|
150 |
+
self._c_node = _createPI(c_doc, _xcstr(target), _xcstr(text))
|
151 |
+
if self._c_node is NULL:
|
152 |
+
raise MemoryError()
|
153 |
+
tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
|
154 |
+
_registerProxy(self, doc, self._c_node)
|
155 |
+
self._init()
|
156 |
+
|
157 |
+
cdef class EntityBase(_Entity):
|
158 |
+
"""All custom Entity classes must inherit from this one.
|
159 |
+
|
160 |
+
To create an XML Entity instance, use the ``Entity()`` factory.
|
161 |
+
|
162 |
+
Subclasses *must not* override __init__ or __new__ as it is
|
163 |
+
absolutely undefined when these objects will be created or
|
164 |
+
destroyed. All persistent state of Entities must be stored in the
|
165 |
+
underlying XML. If you really need to initialize the object after
|
166 |
+
creation, you can implement an ``_init(self)`` method that will be
|
167 |
+
called after object creation.
|
168 |
+
"""
|
169 |
+
def __init__(self, name):
|
170 |
+
cdef _Document doc
|
171 |
+
cdef xmlDoc* c_doc
|
172 |
+
name_utf = _utf8(name)
|
173 |
+
c_name = _xcstr(name_utf)
|
174 |
+
if c_name[0] == c'#':
|
175 |
+
if not _characterReferenceIsValid(c_name + 1):
|
176 |
+
raise ValueError, f"Invalid character reference: '{name}'"
|
177 |
+
elif not _xmlNameIsValid(c_name):
|
178 |
+
raise ValueError, f"Invalid entity reference: '{name}'"
|
179 |
+
c_doc = _newXMLDoc()
|
180 |
+
doc = _documentFactory(c_doc, None)
|
181 |
+
self._c_node = _createEntity(c_doc, c_name)
|
182 |
+
if self._c_node is NULL:
|
183 |
+
raise MemoryError()
|
184 |
+
tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
|
185 |
+
_registerProxy(self, doc, self._c_node)
|
186 |
+
self._init()
|
187 |
+
|
188 |
+
|
189 |
+
cdef int _validateNodeClass(xmlNode* c_node, cls) except -1:
|
190 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
191 |
+
expected = ElementBase
|
192 |
+
elif c_node.type == tree.XML_COMMENT_NODE:
|
193 |
+
expected = CommentBase
|
194 |
+
elif c_node.type == tree.XML_ENTITY_REF_NODE:
|
195 |
+
expected = EntityBase
|
196 |
+
elif c_node.type == tree.XML_PI_NODE:
|
197 |
+
expected = PIBase
|
198 |
+
else:
|
199 |
+
assert False, f"Unknown node type: {c_node.type}"
|
200 |
+
|
201 |
+
if not (isinstance(cls, type) and issubclass(cls, expected)):
|
202 |
+
raise TypeError(
|
203 |
+
f"result of class lookup must be subclass of {type(expected)}, got {type(cls)}")
|
204 |
+
return 0
|
205 |
+
|
206 |
+
|
207 |
+
################################################################################
|
208 |
+
# Element class lookup
|
209 |
+
|
210 |
+
ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*)
|
211 |
+
|
212 |
+
# class to store element class lookup functions
|
213 |
+
cdef public class ElementClassLookup [ type LxmlElementClassLookupType,
|
214 |
+
object LxmlElementClassLookup ]:
|
215 |
+
"""ElementClassLookup(self)
|
216 |
+
Superclass of Element class lookups.
|
217 |
+
"""
|
218 |
+
cdef _element_class_lookup_function _lookup_function
|
219 |
+
|
220 |
+
|
221 |
+
cdef public class FallbackElementClassLookup(ElementClassLookup) \
|
222 |
+
[ type LxmlFallbackElementClassLookupType,
|
223 |
+
object LxmlFallbackElementClassLookup ]:
|
224 |
+
"""FallbackElementClassLookup(self, fallback=None)
|
225 |
+
|
226 |
+
Superclass of Element class lookups with additional fallback.
|
227 |
+
"""
|
228 |
+
cdef readonly ElementClassLookup fallback
|
229 |
+
cdef _element_class_lookup_function _fallback_function
|
230 |
+
def __cinit__(self):
|
231 |
+
# fall back to default lookup
|
232 |
+
self._fallback_function = _lookupDefaultElementClass
|
233 |
+
|
234 |
+
def __init__(self, ElementClassLookup fallback=None):
|
235 |
+
if fallback is not None:
|
236 |
+
self._setFallback(fallback)
|
237 |
+
else:
|
238 |
+
self._fallback_function = _lookupDefaultElementClass
|
239 |
+
|
240 |
+
cdef void _setFallback(self, ElementClassLookup lookup):
|
241 |
+
"""Sets the fallback scheme for this lookup method.
|
242 |
+
"""
|
243 |
+
self.fallback = lookup
|
244 |
+
self._fallback_function = lookup._lookup_function
|
245 |
+
if self._fallback_function is NULL:
|
246 |
+
self._fallback_function = _lookupDefaultElementClass
|
247 |
+
|
248 |
+
def set_fallback(self, ElementClassLookup lookup not None):
|
249 |
+
"""set_fallback(self, lookup)
|
250 |
+
|
251 |
+
Sets the fallback scheme for this lookup method.
|
252 |
+
"""
|
253 |
+
self._setFallback(lookup)
|
254 |
+
|
255 |
+
cdef inline object _callLookupFallback(FallbackElementClassLookup lookup,
|
256 |
+
_Document doc, xmlNode* c_node):
|
257 |
+
return lookup._fallback_function(lookup.fallback, doc, c_node)
|
258 |
+
|
259 |
+
|
260 |
+
################################################################################
|
261 |
+
# default lookup scheme
|
262 |
+
|
263 |
+
cdef class ElementDefaultClassLookup(ElementClassLookup):
|
264 |
+
"""ElementDefaultClassLookup(self, element=None, comment=None, pi=None, entity=None)
|
265 |
+
Element class lookup scheme that always returns the default Element
|
266 |
+
class.
|
267 |
+
|
268 |
+
The keyword arguments ``element``, ``comment``, ``pi`` and ``entity``
|
269 |
+
accept the respective Element classes.
|
270 |
+
"""
|
271 |
+
cdef readonly object element_class
|
272 |
+
cdef readonly object comment_class
|
273 |
+
cdef readonly object pi_class
|
274 |
+
cdef readonly object entity_class
|
275 |
+
def __cinit__(self):
|
276 |
+
self._lookup_function = _lookupDefaultElementClass
|
277 |
+
|
278 |
+
def __init__(self, element=None, comment=None, pi=None, entity=None):
|
279 |
+
if element is None:
|
280 |
+
self.element_class = _Element
|
281 |
+
elif issubclass(element, ElementBase):
|
282 |
+
self.element_class = element
|
283 |
+
else:
|
284 |
+
raise TypeError, "element class must be subclass of ElementBase"
|
285 |
+
|
286 |
+
if comment is None:
|
287 |
+
self.comment_class = _Comment
|
288 |
+
elif issubclass(comment, CommentBase):
|
289 |
+
self.comment_class = comment
|
290 |
+
else:
|
291 |
+
raise TypeError, "comment class must be subclass of CommentBase"
|
292 |
+
|
293 |
+
if entity is None:
|
294 |
+
self.entity_class = _Entity
|
295 |
+
elif issubclass(entity, EntityBase):
|
296 |
+
self.entity_class = entity
|
297 |
+
else:
|
298 |
+
raise TypeError, "Entity class must be subclass of EntityBase"
|
299 |
+
|
300 |
+
if pi is None:
|
301 |
+
self.pi_class = None # special case, see below
|
302 |
+
elif issubclass(pi, PIBase):
|
303 |
+
self.pi_class = pi
|
304 |
+
else:
|
305 |
+
raise TypeError, "PI class must be subclass of PIBase"
|
306 |
+
|
307 |
+
cdef object _lookupDefaultElementClass(state, _Document _doc, xmlNode* c_node):
|
308 |
+
"Trivial class lookup function that always returns the default class."
|
309 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
310 |
+
if state is not None:
|
311 |
+
return (<ElementDefaultClassLookup>state).element_class
|
312 |
+
else:
|
313 |
+
return _Element
|
314 |
+
elif c_node.type == tree.XML_COMMENT_NODE:
|
315 |
+
if state is not None:
|
316 |
+
return (<ElementDefaultClassLookup>state).comment_class
|
317 |
+
else:
|
318 |
+
return _Comment
|
319 |
+
elif c_node.type == tree.XML_ENTITY_REF_NODE:
|
320 |
+
if state is not None:
|
321 |
+
return (<ElementDefaultClassLookup>state).entity_class
|
322 |
+
else:
|
323 |
+
return _Entity
|
324 |
+
elif c_node.type == tree.XML_PI_NODE:
|
325 |
+
if state is None or (<ElementDefaultClassLookup>state).pi_class is None:
|
326 |
+
# special case XSLT-PI
|
327 |
+
if c_node.name is not NULL and c_node.content is not NULL:
|
328 |
+
if tree.xmlStrcmp(c_node.name, <unsigned char*>"xml-stylesheet") == 0:
|
329 |
+
if tree.xmlStrstr(c_node.content, <unsigned char*>"text/xsl") is not NULL or \
|
330 |
+
tree.xmlStrstr(c_node.content, <unsigned char*>"text/xml") is not NULL:
|
331 |
+
return _XSLTProcessingInstruction
|
332 |
+
return _ProcessingInstruction
|
333 |
+
else:
|
334 |
+
return (<ElementDefaultClassLookup>state).pi_class
|
335 |
+
else:
|
336 |
+
assert False, f"Unknown node type: {c_node.type}"
|
337 |
+
|
338 |
+
|
339 |
+
################################################################################
|
340 |
+
# attribute based lookup scheme
|
341 |
+
|
342 |
+
cdef class AttributeBasedElementClassLookup(FallbackElementClassLookup):
|
343 |
+
"""AttributeBasedElementClassLookup(self, attribute_name, class_mapping, fallback=None)
|
344 |
+
Checks an attribute of an Element and looks up the value in a
|
345 |
+
class dictionary.
|
346 |
+
|
347 |
+
Arguments:
|
348 |
+
- attribute name - '{ns}name' style string
|
349 |
+
- class mapping - Python dict mapping attribute values to Element classes
|
350 |
+
- fallback - optional fallback lookup mechanism
|
351 |
+
|
352 |
+
A None key in the class mapping will be checked if the attribute is
|
353 |
+
missing.
|
354 |
+
"""
|
355 |
+
cdef object _class_mapping
|
356 |
+
cdef tuple _pytag
|
357 |
+
cdef const_xmlChar* _c_ns
|
358 |
+
cdef const_xmlChar* _c_name
|
359 |
+
def __cinit__(self):
|
360 |
+
self._lookup_function = _attribute_class_lookup
|
361 |
+
|
362 |
+
def __init__(self, attribute_name, class_mapping,
|
363 |
+
ElementClassLookup fallback=None):
|
364 |
+
self._pytag = _getNsTag(attribute_name)
|
365 |
+
ns, name = self._pytag
|
366 |
+
if ns is None:
|
367 |
+
self._c_ns = NULL
|
368 |
+
else:
|
369 |
+
self._c_ns = _xcstr(ns)
|
370 |
+
self._c_name = _xcstr(name)
|
371 |
+
self._class_mapping = dict(class_mapping)
|
372 |
+
|
373 |
+
FallbackElementClassLookup.__init__(self, fallback)
|
374 |
+
|
375 |
+
cdef object _attribute_class_lookup(state, _Document doc, xmlNode* c_node):
|
376 |
+
cdef AttributeBasedElementClassLookup lookup
|
377 |
+
cdef python.PyObject* dict_result
|
378 |
+
|
379 |
+
lookup = <AttributeBasedElementClassLookup>state
|
380 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
381 |
+
value = _attributeValueFromNsName(
|
382 |
+
c_node, lookup._c_ns, lookup._c_name)
|
383 |
+
dict_result = python.PyDict_GetItem(lookup._class_mapping, value)
|
384 |
+
if dict_result is not NULL:
|
385 |
+
cls = <object>dict_result
|
386 |
+
_validateNodeClass(c_node, cls)
|
387 |
+
return cls
|
388 |
+
return _callLookupFallback(lookup, doc, c_node)
|
389 |
+
|
390 |
+
|
391 |
+
################################################################################
|
392 |
+
# per-parser lookup scheme
|
393 |
+
|
394 |
+
cdef class ParserBasedElementClassLookup(FallbackElementClassLookup):
|
395 |
+
"""ParserBasedElementClassLookup(self, fallback=None)
|
396 |
+
Element class lookup based on the XML parser.
|
397 |
+
"""
|
398 |
+
def __cinit__(self):
|
399 |
+
self._lookup_function = _parser_class_lookup
|
400 |
+
|
401 |
+
cdef object _parser_class_lookup(state, _Document doc, xmlNode* c_node):
|
402 |
+
if doc._parser._class_lookup is not None:
|
403 |
+
return doc._parser._class_lookup._lookup_function(
|
404 |
+
doc._parser._class_lookup, doc, c_node)
|
405 |
+
return _callLookupFallback(<FallbackElementClassLookup>state, doc, c_node)
|
406 |
+
|
407 |
+
|
408 |
+
################################################################################
|
409 |
+
# custom class lookup based on node type, namespace, name
|
410 |
+
|
411 |
+
cdef class CustomElementClassLookup(FallbackElementClassLookup):
|
412 |
+
"""CustomElementClassLookup(self, fallback=None)
|
413 |
+
Element class lookup based on a subclass method.
|
414 |
+
|
415 |
+
You can inherit from this class and override the method::
|
416 |
+
|
417 |
+
lookup(self, type, doc, namespace, name)
|
418 |
+
|
419 |
+
to lookup the element class for a node. Arguments of the method:
|
420 |
+
* type: one of 'element', 'comment', 'PI', 'entity'
|
421 |
+
* doc: document that the node is in
|
422 |
+
* namespace: namespace URI of the node (or None for comments/PIs/entities)
|
423 |
+
* name: name of the element/entity, None for comments, target for PIs
|
424 |
+
|
425 |
+
If you return None from this method, the fallback will be called.
|
426 |
+
"""
|
427 |
+
def __cinit__(self):
|
428 |
+
self._lookup_function = _custom_class_lookup
|
429 |
+
|
430 |
+
def lookup(self, type, doc, namespace, name):
|
431 |
+
"lookup(self, type, doc, namespace, name)"
|
432 |
+
return None
|
433 |
+
|
434 |
+
cdef object _custom_class_lookup(state, _Document doc, xmlNode* c_node):
|
435 |
+
cdef CustomElementClassLookup lookup
|
436 |
+
|
437 |
+
lookup = <CustomElementClassLookup>state
|
438 |
+
|
439 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
440 |
+
element_type = "element"
|
441 |
+
elif c_node.type == tree.XML_COMMENT_NODE:
|
442 |
+
element_type = "comment"
|
443 |
+
elif c_node.type == tree.XML_PI_NODE:
|
444 |
+
element_type = "PI"
|
445 |
+
elif c_node.type == tree.XML_ENTITY_REF_NODE:
|
446 |
+
element_type = "entity"
|
447 |
+
else:
|
448 |
+
element_type = "element"
|
449 |
+
if c_node.name is NULL:
|
450 |
+
name = None
|
451 |
+
else:
|
452 |
+
name = funicode(c_node.name)
|
453 |
+
c_str = tree._getNs(c_node)
|
454 |
+
ns = funicode(c_str) if c_str is not NULL else None
|
455 |
+
|
456 |
+
cls = lookup.lookup(element_type, doc, ns, name)
|
457 |
+
if cls is not None:
|
458 |
+
_validateNodeClass(c_node, cls)
|
459 |
+
return cls
|
460 |
+
return _callLookupFallback(lookup, doc, c_node)
|
461 |
+
|
462 |
+
|
463 |
+
################################################################################
|
464 |
+
# read-only tree based class lookup
|
465 |
+
|
466 |
+
cdef class PythonElementClassLookup(FallbackElementClassLookup):
|
467 |
+
"""PythonElementClassLookup(self, fallback=None)
|
468 |
+
Element class lookup based on a subclass method.
|
469 |
+
|
470 |
+
This class lookup scheme allows access to the entire XML tree in
|
471 |
+
read-only mode. To use it, re-implement the ``lookup(self, doc,
|
472 |
+
root)`` method in a subclass::
|
473 |
+
|
474 |
+
from lxml import etree, pyclasslookup
|
475 |
+
|
476 |
+
class MyElementClass(etree.ElementBase):
|
477 |
+
honkey = True
|
478 |
+
|
479 |
+
class MyLookup(pyclasslookup.PythonElementClassLookup):
|
480 |
+
def lookup(self, doc, root):
|
481 |
+
if root.tag == "sometag":
|
482 |
+
return MyElementClass
|
483 |
+
else:
|
484 |
+
for child in root:
|
485 |
+
if child.tag == "someothertag":
|
486 |
+
return MyElementClass
|
487 |
+
# delegate to default
|
488 |
+
return None
|
489 |
+
|
490 |
+
If you return None from this method, the fallback will be called.
|
491 |
+
|
492 |
+
The first argument is the opaque document instance that contains
|
493 |
+
the Element. The second argument is a lightweight Element proxy
|
494 |
+
implementation that is only valid during the lookup. Do not try
|
495 |
+
to keep a reference to it. Once the lookup is done, the proxy
|
496 |
+
will be invalid.
|
497 |
+
|
498 |
+
Also, you cannot wrap such a read-only Element in an ElementTree,
|
499 |
+
and you must take care not to keep a reference to them outside of
|
500 |
+
the `lookup()` method.
|
501 |
+
|
502 |
+
Note that the API of the Element objects is not complete. It is
|
503 |
+
purely read-only and does not support all features of the normal
|
504 |
+
`lxml.etree` API (such as XPath, extended slicing or some
|
505 |
+
iteration methods).
|
506 |
+
|
507 |
+
See https://lxml.de/element_classes.html
|
508 |
+
"""
|
509 |
+
def __cinit__(self):
|
510 |
+
self._lookup_function = _python_class_lookup
|
511 |
+
|
512 |
+
def lookup(self, doc, element):
|
513 |
+
"""lookup(self, doc, element)
|
514 |
+
|
515 |
+
Override this method to implement your own lookup scheme.
|
516 |
+
"""
|
517 |
+
return None
|
518 |
+
|
519 |
+
cdef object _python_class_lookup(state, _Document doc, tree.xmlNode* c_node):
|
520 |
+
cdef PythonElementClassLookup lookup
|
521 |
+
cdef _ReadOnlyProxy proxy
|
522 |
+
lookup = <PythonElementClassLookup>state
|
523 |
+
|
524 |
+
proxy = _newReadOnlyProxy(None, c_node)
|
525 |
+
cls = lookup.lookup(doc, proxy)
|
526 |
+
_freeReadOnlyProxies(proxy)
|
527 |
+
|
528 |
+
if cls is not None:
|
529 |
+
_validateNodeClass(c_node, cls)
|
530 |
+
return cls
|
531 |
+
return _callLookupFallback(lookup, doc, c_node)
|
532 |
+
|
533 |
+
################################################################################
|
534 |
+
# Global setup
|
535 |
+
|
536 |
+
cdef _element_class_lookup_function LOOKUP_ELEMENT_CLASS
|
537 |
+
cdef object ELEMENT_CLASS_LOOKUP_STATE
|
538 |
+
|
539 |
+
cdef void _setElementClassLookupFunction(
|
540 |
+
_element_class_lookup_function function, object state):
|
541 |
+
global LOOKUP_ELEMENT_CLASS, ELEMENT_CLASS_LOOKUP_STATE
|
542 |
+
if function is NULL:
|
543 |
+
state = DEFAULT_ELEMENT_CLASS_LOOKUP
|
544 |
+
function = DEFAULT_ELEMENT_CLASS_LOOKUP._lookup_function
|
545 |
+
|
546 |
+
ELEMENT_CLASS_LOOKUP_STATE = state
|
547 |
+
LOOKUP_ELEMENT_CLASS = function
|
548 |
+
|
549 |
+
def set_element_class_lookup(ElementClassLookup lookup = None):
|
550 |
+
"""set_element_class_lookup(lookup = None)
|
551 |
+
|
552 |
+
Set the global element class lookup method.
|
553 |
+
|
554 |
+
This defines the main entry point for looking up element implementations.
|
555 |
+
The standard implementation uses the :class:`ParserBasedElementClassLookup`
|
556 |
+
to delegate to different lookup schemes for each parser.
|
557 |
+
|
558 |
+
.. warning::
|
559 |
+
|
560 |
+
This should only be changed by applications, not by library packages.
|
561 |
+
In most cases, parser specific lookups should be preferred,
|
562 |
+
which can be configured via
|
563 |
+
:meth:`~lxml.etree.XMLParser.set_element_class_lookup`
|
564 |
+
(and the same for HTML parsers).
|
565 |
+
|
566 |
+
Globally replacing the element class lookup by something other than a
|
567 |
+
:class:`ParserBasedElementClassLookup` will prevent parser specific lookup
|
568 |
+
schemes from working. Several tools rely on parser specific lookups,
|
569 |
+
including :mod:`lxml.html` and :mod:`lxml.objectify`.
|
570 |
+
"""
|
571 |
+
if lookup is None or lookup._lookup_function is NULL:
|
572 |
+
_setElementClassLookupFunction(NULL, None)
|
573 |
+
else:
|
574 |
+
_setElementClassLookupFunction(lookup._lookup_function, lookup)
|
575 |
+
|
576 |
+
# default setup: parser delegation
|
577 |
+
cdef ParserBasedElementClassLookup DEFAULT_ELEMENT_CLASS_LOOKUP
|
578 |
+
DEFAULT_ELEMENT_CLASS_LOOKUP = ParserBasedElementClassLookup()
|
579 |
+
|
580 |
+
set_element_class_lookup(DEFAULT_ELEMENT_CLASS_LOOKUP)
|
env-llmeval/lib/python3.10/site-packages/lxml/cleanup.pxi
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# functions for tree cleanup and removing elements from subtrees
|
2 |
+
|
3 |
+
def cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None):
|
4 |
+
"""cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None)
|
5 |
+
|
6 |
+
Remove all namespace declarations from a subtree that are not used
|
7 |
+
by any of the elements or attributes in that tree.
|
8 |
+
|
9 |
+
If a 'top_nsmap' is provided, it must be a mapping from prefixes
|
10 |
+
to namespace URIs. These namespaces will be declared on the top
|
11 |
+
element of the subtree before running the cleanup, which allows
|
12 |
+
moving namespace declarations to the top of the tree.
|
13 |
+
|
14 |
+
If a 'keep_ns_prefixes' is provided, it must be a list of prefixes.
|
15 |
+
These prefixes will not be removed as part of the cleanup.
|
16 |
+
"""
|
17 |
+
element = _rootNodeOrRaise(tree_or_element)
|
18 |
+
c_element = element._c_node
|
19 |
+
|
20 |
+
if top_nsmap:
|
21 |
+
doc = element._doc
|
22 |
+
# declare namespaces from nsmap, then apply them to the subtree
|
23 |
+
_setNodeNamespaces(c_element, doc, None, top_nsmap)
|
24 |
+
moveNodeToDocument(doc, c_element.doc, c_element)
|
25 |
+
|
26 |
+
keep_ns_prefixes = (
|
27 |
+
set([_utf8(prefix) for prefix in keep_ns_prefixes])
|
28 |
+
if keep_ns_prefixes else None)
|
29 |
+
|
30 |
+
_removeUnusedNamespaceDeclarations(c_element, keep_ns_prefixes)
|
31 |
+
|
32 |
+
|
33 |
+
def strip_attributes(tree_or_element, *attribute_names):
|
34 |
+
"""strip_attributes(tree_or_element, *attribute_names)
|
35 |
+
|
36 |
+
Delete all attributes with the provided attribute names from an
|
37 |
+
Element (or ElementTree) and its descendants.
|
38 |
+
|
39 |
+
Attribute names can contain wildcards as in `_Element.iter`.
|
40 |
+
|
41 |
+
Example usage::
|
42 |
+
|
43 |
+
strip_attributes(root_element,
|
44 |
+
'simpleattr',
|
45 |
+
'{http://some/ns}attrname',
|
46 |
+
'{http://other/ns}*')
|
47 |
+
"""
|
48 |
+
cdef _MultiTagMatcher matcher
|
49 |
+
element = _rootNodeOrRaise(tree_or_element)
|
50 |
+
if not attribute_names:
|
51 |
+
return
|
52 |
+
|
53 |
+
matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, attribute_names)
|
54 |
+
matcher.cacheTags(element._doc)
|
55 |
+
if matcher.rejectsAllAttributes():
|
56 |
+
return
|
57 |
+
_strip_attributes(element._c_node, matcher)
|
58 |
+
|
59 |
+
|
60 |
+
cdef _strip_attributes(xmlNode* c_node, _MultiTagMatcher matcher):
|
61 |
+
cdef xmlAttr* c_attr
|
62 |
+
cdef xmlAttr* c_next_attr
|
63 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
64 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
65 |
+
c_attr = c_node.properties
|
66 |
+
while c_attr is not NULL:
|
67 |
+
c_next_attr = c_attr.next
|
68 |
+
if matcher.matchesAttribute(c_attr):
|
69 |
+
tree.xmlRemoveProp(c_attr)
|
70 |
+
c_attr = c_next_attr
|
71 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
72 |
+
|
73 |
+
|
74 |
+
def strip_elements(tree_or_element, *tag_names, bint with_tail=True):
|
75 |
+
"""strip_elements(tree_or_element, *tag_names, with_tail=True)
|
76 |
+
|
77 |
+
Delete all elements with the provided tag names from a tree or
|
78 |
+
subtree. This will remove the elements and their entire subtree,
|
79 |
+
including all their attributes, text content and descendants. It
|
80 |
+
will also remove the tail text of the element unless you
|
81 |
+
explicitly set the ``with_tail`` keyword argument option to False.
|
82 |
+
|
83 |
+
Tag names can contain wildcards as in `_Element.iter`.
|
84 |
+
|
85 |
+
Note that this will not delete the element (or ElementTree root
|
86 |
+
element) that you passed even if it matches. It will only treat
|
87 |
+
its descendants. If you want to include the root element, check
|
88 |
+
its tag name directly before even calling this function.
|
89 |
+
|
90 |
+
Example usage::
|
91 |
+
|
92 |
+
strip_elements(some_element,
|
93 |
+
'simpletagname', # non-namespaced tag
|
94 |
+
'{http://some/ns}tagname', # namespaced tag
|
95 |
+
'{http://some/other/ns}*' # any tag from a namespace
|
96 |
+
lxml.etree.Comment # comments
|
97 |
+
)
|
98 |
+
"""
|
99 |
+
cdef _MultiTagMatcher matcher
|
100 |
+
doc = _documentOrRaise(tree_or_element)
|
101 |
+
element = _rootNodeOrRaise(tree_or_element)
|
102 |
+
if not tag_names:
|
103 |
+
return
|
104 |
+
|
105 |
+
matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names)
|
106 |
+
matcher.cacheTags(doc)
|
107 |
+
if matcher.rejectsAll():
|
108 |
+
return
|
109 |
+
|
110 |
+
if isinstance(tree_or_element, _ElementTree):
|
111 |
+
# include PIs and comments next to the root node
|
112 |
+
if matcher.matchesType(tree.XML_COMMENT_NODE):
|
113 |
+
_removeSiblings(element._c_node, tree.XML_COMMENT_NODE, with_tail)
|
114 |
+
if matcher.matchesType(tree.XML_PI_NODE):
|
115 |
+
_removeSiblings(element._c_node, tree.XML_PI_NODE, with_tail)
|
116 |
+
_strip_elements(doc, element._c_node, matcher, with_tail)
|
117 |
+
|
118 |
+
cdef _strip_elements(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher,
|
119 |
+
bint with_tail):
|
120 |
+
cdef xmlNode* c_child
|
121 |
+
cdef xmlNode* c_next
|
122 |
+
|
123 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
124 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
125 |
+
# we run through the children here to prevent any problems
|
126 |
+
# with the tree iteration which would occur if we unlinked the
|
127 |
+
# c_node itself
|
128 |
+
c_child = _findChildForwards(c_node, 0)
|
129 |
+
while c_child is not NULL:
|
130 |
+
c_next = _nextElement(c_child)
|
131 |
+
if matcher.matches(c_child):
|
132 |
+
if c_child.type == tree.XML_ELEMENT_NODE:
|
133 |
+
if not with_tail:
|
134 |
+
tree.xmlUnlinkNode(c_child)
|
135 |
+
_removeNode(doc, c_child)
|
136 |
+
else:
|
137 |
+
if with_tail:
|
138 |
+
_removeText(c_child.next)
|
139 |
+
tree.xmlUnlinkNode(c_child)
|
140 |
+
attemptDeallocation(c_child)
|
141 |
+
c_child = c_next
|
142 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
143 |
+
|
144 |
+
|
145 |
+
def strip_tags(tree_or_element, *tag_names):
|
146 |
+
"""strip_tags(tree_or_element, *tag_names)
|
147 |
+
|
148 |
+
Delete all elements with the provided tag names from a tree or
|
149 |
+
subtree. This will remove the elements and their attributes, but
|
150 |
+
*not* their text/tail content or descendants. Instead, it will
|
151 |
+
merge the text content and children of the element into its
|
152 |
+
parent.
|
153 |
+
|
154 |
+
Tag names can contain wildcards as in `_Element.iter`.
|
155 |
+
|
156 |
+
Note that this will not delete the element (or ElementTree root
|
157 |
+
element) that you passed even if it matches. It will only treat
|
158 |
+
its descendants.
|
159 |
+
|
160 |
+
Example usage::
|
161 |
+
|
162 |
+
strip_tags(some_element,
|
163 |
+
'simpletagname', # non-namespaced tag
|
164 |
+
'{http://some/ns}tagname', # namespaced tag
|
165 |
+
'{http://some/other/ns}*' # any tag from a namespace
|
166 |
+
Comment # comments (including their text!)
|
167 |
+
)
|
168 |
+
"""
|
169 |
+
cdef _MultiTagMatcher matcher
|
170 |
+
doc = _documentOrRaise(tree_or_element)
|
171 |
+
element = _rootNodeOrRaise(tree_or_element)
|
172 |
+
if not tag_names:
|
173 |
+
return
|
174 |
+
|
175 |
+
matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names)
|
176 |
+
matcher.cacheTags(doc)
|
177 |
+
if matcher.rejectsAll():
|
178 |
+
return
|
179 |
+
|
180 |
+
if isinstance(tree_or_element, _ElementTree):
|
181 |
+
# include PIs and comments next to the root node
|
182 |
+
if matcher.matchesType(tree.XML_COMMENT_NODE):
|
183 |
+
_removeSiblings(element._c_node, tree.XML_COMMENT_NODE, 0)
|
184 |
+
if matcher.matchesType(tree.XML_PI_NODE):
|
185 |
+
_removeSiblings(element._c_node, tree.XML_PI_NODE, 0)
|
186 |
+
_strip_tags(doc, element._c_node, matcher)
|
187 |
+
|
188 |
+
cdef _strip_tags(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher):
|
189 |
+
cdef xmlNode* c_child
|
190 |
+
cdef xmlNode* c_next
|
191 |
+
|
192 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
193 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
194 |
+
# we run through the children here to prevent any problems
|
195 |
+
# with the tree iteration which would occur if we unlinked the
|
196 |
+
# c_node itself
|
197 |
+
c_child = _findChildForwards(c_node, 0)
|
198 |
+
while c_child is not NULL:
|
199 |
+
if not matcher.matches(c_child):
|
200 |
+
c_child = _nextElement(c_child)
|
201 |
+
continue
|
202 |
+
if c_child.type == tree.XML_ELEMENT_NODE:
|
203 |
+
c_next = _findChildForwards(c_child, 0) or _nextElement(c_child)
|
204 |
+
_replaceNodeByChildren(doc, c_child)
|
205 |
+
if not attemptDeallocation(c_child):
|
206 |
+
if c_child.nsDef is not NULL:
|
207 |
+
# make namespaces absolute
|
208 |
+
moveNodeToDocument(doc, doc._c_doc, c_child)
|
209 |
+
c_child = c_next
|
210 |
+
else:
|
211 |
+
c_next = _nextElement(c_child)
|
212 |
+
tree.xmlUnlinkNode(c_child)
|
213 |
+
attemptDeallocation(c_child)
|
214 |
+
c_child = c_next
|
215 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
env-llmeval/lib/python3.10/site-packages/lxml/cssselect.py
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""CSS Selectors based on XPath.
|
2 |
+
|
3 |
+
This module supports selecting XML/HTML tags based on CSS selectors.
|
4 |
+
See the `CSSSelector` class for details.
|
5 |
+
|
6 |
+
This is a thin wrapper around cssselect 0.7 or later.
|
7 |
+
"""
|
8 |
+
|
9 |
+
|
10 |
+
from . import etree
|
11 |
+
try:
|
12 |
+
import cssselect as external_cssselect
|
13 |
+
except ImportError:
|
14 |
+
raise ImportError(
|
15 |
+
'cssselect does not seem to be installed. '
|
16 |
+
'See https://pypi.org/project/cssselect/')
|
17 |
+
|
18 |
+
|
19 |
+
SelectorSyntaxError = external_cssselect.SelectorSyntaxError
|
20 |
+
ExpressionError = external_cssselect.ExpressionError
|
21 |
+
SelectorError = external_cssselect.SelectorError
|
22 |
+
|
23 |
+
|
24 |
+
__all__ = ['SelectorSyntaxError', 'ExpressionError', 'SelectorError',
|
25 |
+
'CSSSelector']
|
26 |
+
|
27 |
+
|
28 |
+
class LxmlTranslator(external_cssselect.GenericTranslator):
|
29 |
+
"""
|
30 |
+
A custom CSS selector to XPath translator with lxml-specific extensions.
|
31 |
+
"""
|
32 |
+
def xpath_contains_function(self, xpath, function):
|
33 |
+
# Defined there, removed in later drafts:
|
34 |
+
# http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#content-selectors
|
35 |
+
if function.argument_types() not in (['STRING'], ['IDENT']):
|
36 |
+
raise ExpressionError(
|
37 |
+
"Expected a single string or ident for :contains(), got %r"
|
38 |
+
% function.arguments)
|
39 |
+
value = function.arguments[0].value
|
40 |
+
return xpath.add_condition(
|
41 |
+
'contains(__lxml_internal_css:lower-case(string(.)), %s)'
|
42 |
+
% self.xpath_literal(value.lower()))
|
43 |
+
|
44 |
+
|
45 |
+
class LxmlHTMLTranslator(LxmlTranslator, external_cssselect.HTMLTranslator):
|
46 |
+
"""
|
47 |
+
lxml extensions + HTML support.
|
48 |
+
"""
|
49 |
+
|
50 |
+
|
51 |
+
def _make_lower_case(context, s):
|
52 |
+
return s.lower()
|
53 |
+
|
54 |
+
ns = etree.FunctionNamespace('http://codespeak.net/lxml/css/')
|
55 |
+
ns.prefix = '__lxml_internal_css'
|
56 |
+
ns['lower-case'] = _make_lower_case
|
57 |
+
|
58 |
+
|
59 |
+
class CSSSelector(etree.XPath):
|
60 |
+
"""A CSS selector.
|
61 |
+
|
62 |
+
Usage::
|
63 |
+
|
64 |
+
>>> from lxml import etree, cssselect
|
65 |
+
>>> select = cssselect.CSSSelector("a tag > child")
|
66 |
+
|
67 |
+
>>> root = etree.XML("<a><b><c/><tag><child>TEXT</child></tag></b></a>")
|
68 |
+
>>> [ el.tag for el in select(root) ]
|
69 |
+
['child']
|
70 |
+
|
71 |
+
To use CSS namespaces, you need to pass a prefix-to-namespace
|
72 |
+
mapping as ``namespaces`` keyword argument::
|
73 |
+
|
74 |
+
>>> rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
|
75 |
+
>>> select_ns = cssselect.CSSSelector('root > rdf|Description',
|
76 |
+
... namespaces={'rdf': rdfns})
|
77 |
+
|
78 |
+
>>> rdf = etree.XML((
|
79 |
+
... '<root xmlns:rdf="%s">'
|
80 |
+
... '<rdf:Description>blah</rdf:Description>'
|
81 |
+
... '</root>') % rdfns)
|
82 |
+
>>> [(el.tag, el.text) for el in select_ns(rdf)]
|
83 |
+
[('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description', 'blah')]
|
84 |
+
|
85 |
+
"""
|
86 |
+
def __init__(self, css, namespaces=None, translator='xml'):
|
87 |
+
if translator == 'xml':
|
88 |
+
translator = LxmlTranslator()
|
89 |
+
elif translator == 'html':
|
90 |
+
translator = LxmlHTMLTranslator()
|
91 |
+
elif translator == 'xhtml':
|
92 |
+
translator = LxmlHTMLTranslator(xhtml=True)
|
93 |
+
path = translator.css_to_xpath(css)
|
94 |
+
super().__init__(path, namespaces=namespaces)
|
95 |
+
self.css = css
|
96 |
+
|
97 |
+
def __repr__(self):
|
98 |
+
return '<%s %x for %r>' % (
|
99 |
+
self.__class__.__name__,
|
100 |
+
abs(id(self)),
|
101 |
+
self.css)
|
env-llmeval/lib/python3.10/site-packages/lxml/debug.pxi
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@cython.final
|
2 |
+
@cython.internal
|
3 |
+
cdef class _MemDebug:
|
4 |
+
"""Debugging support for the memory allocation in libxml2.
|
5 |
+
"""
|
6 |
+
def bytes_used(self):
|
7 |
+
"""bytes_used(self)
|
8 |
+
|
9 |
+
Returns the total amount of memory (in bytes) currently used by libxml2.
|
10 |
+
Note that libxml2 constrains this value to a C int, which limits
|
11 |
+
the accuracy on 64 bit systems.
|
12 |
+
"""
|
13 |
+
return tree.xmlMemUsed()
|
14 |
+
|
15 |
+
def blocks_used(self):
|
16 |
+
"""blocks_used(self)
|
17 |
+
|
18 |
+
Returns the total number of memory blocks currently allocated by libxml2.
|
19 |
+
Note that libxml2 constrains this value to a C int, which limits
|
20 |
+
the accuracy on 64 bit systems.
|
21 |
+
"""
|
22 |
+
return tree.xmlMemBlocks()
|
23 |
+
|
24 |
+
def dict_size(self):
|
25 |
+
"""dict_size(self)
|
26 |
+
|
27 |
+
Returns the current size of the global name dictionary used by libxml2
|
28 |
+
for the current thread. Each thread has its own dictionary.
|
29 |
+
"""
|
30 |
+
c_dict = __GLOBAL_PARSER_CONTEXT._getThreadDict(NULL)
|
31 |
+
if c_dict is NULL:
|
32 |
+
raise MemoryError()
|
33 |
+
return tree.xmlDictSize(c_dict)
|
34 |
+
|
35 |
+
def dump(self, output_file=None, byte_count=None):
|
36 |
+
"""dump(self, output_file=None, byte_count=None)
|
37 |
+
|
38 |
+
Dumps the current memory blocks allocated by libxml2 to a file.
|
39 |
+
|
40 |
+
The optional parameter 'output_file' specifies the file path. It defaults
|
41 |
+
to the file ".memorylist" in the current directory.
|
42 |
+
|
43 |
+
The optional parameter 'byte_count' limits the number of bytes in the dump.
|
44 |
+
Note that this parameter is ignored when lxml is compiled against a libxml2
|
45 |
+
version before 2.7.0.
|
46 |
+
"""
|
47 |
+
cdef Py_ssize_t c_count
|
48 |
+
if output_file is None:
|
49 |
+
output_file = b'.memorylist'
|
50 |
+
elif isinstance(output_file, unicode):
|
51 |
+
output_file.encode(sys.getfilesystemencoding())
|
52 |
+
|
53 |
+
f = stdio.fopen(output_file, "w")
|
54 |
+
if f is NULL:
|
55 |
+
raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}")
|
56 |
+
try:
|
57 |
+
if byte_count is None:
|
58 |
+
tree.xmlMemDisplay(f)
|
59 |
+
else:
|
60 |
+
c_count = byte_count
|
61 |
+
tree.xmlMemDisplayLast(f, c_count)
|
62 |
+
finally:
|
63 |
+
stdio.fclose(f)
|
64 |
+
|
65 |
+
def show(self, output_file=None, block_count=None):
|
66 |
+
"""show(self, output_file=None, block_count=None)
|
67 |
+
|
68 |
+
Dumps the current memory blocks allocated by libxml2 to a file.
|
69 |
+
The output file format is suitable for line diffing.
|
70 |
+
|
71 |
+
The optional parameter 'output_file' specifies the file path. It defaults
|
72 |
+
to the file ".memorydump" in the current directory.
|
73 |
+
|
74 |
+
The optional parameter 'block_count' limits the number of blocks
|
75 |
+
in the dump.
|
76 |
+
"""
|
77 |
+
if output_file is None:
|
78 |
+
output_file = b'.memorydump'
|
79 |
+
elif isinstance(output_file, unicode):
|
80 |
+
output_file.encode(sys.getfilesystemencoding())
|
81 |
+
|
82 |
+
f = stdio.fopen(output_file, "w")
|
83 |
+
if f is NULL:
|
84 |
+
raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}")
|
85 |
+
try:
|
86 |
+
tree.xmlMemShow(f, block_count if block_count is not None else tree.xmlMemBlocks())
|
87 |
+
finally:
|
88 |
+
stdio.fclose(f)
|
89 |
+
|
90 |
+
memory_debugger = _MemDebug()
|
env-llmeval/lib/python3.10/site-packages/lxml/docloader.pxi
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Custom resolver API
|
2 |
+
|
3 |
+
ctypedef enum _InputDocumentDataType:
|
4 |
+
PARSER_DATA_INVALID
|
5 |
+
PARSER_DATA_EMPTY
|
6 |
+
PARSER_DATA_STRING
|
7 |
+
PARSER_DATA_FILENAME
|
8 |
+
PARSER_DATA_FILE
|
9 |
+
|
10 |
+
@cython.final
|
11 |
+
@cython.internal
|
12 |
+
cdef class _InputDocument:
|
13 |
+
cdef _InputDocumentDataType _type
|
14 |
+
cdef bytes _data_bytes
|
15 |
+
cdef object _filename
|
16 |
+
cdef object _file
|
17 |
+
cdef bint _close_file
|
18 |
+
|
19 |
+
def __cinit__(self):
|
20 |
+
self._type = PARSER_DATA_INVALID
|
21 |
+
|
22 |
+
|
23 |
+
cdef class Resolver:
|
24 |
+
"This is the base class of all resolvers."
|
25 |
+
def resolve(self, system_url, public_id, context):
|
26 |
+
"""resolve(self, system_url, public_id, context)
|
27 |
+
|
28 |
+
Override this method to resolve an external source by
|
29 |
+
``system_url`` and ``public_id``. The third argument is an
|
30 |
+
opaque context object.
|
31 |
+
|
32 |
+
Return the result of one of the ``resolve_*()`` methods.
|
33 |
+
"""
|
34 |
+
return None
|
35 |
+
|
36 |
+
def resolve_empty(self, context):
|
37 |
+
"""resolve_empty(self, context)
|
38 |
+
|
39 |
+
Return an empty input document.
|
40 |
+
|
41 |
+
Pass context as parameter.
|
42 |
+
"""
|
43 |
+
cdef _InputDocument doc_ref
|
44 |
+
doc_ref = _InputDocument()
|
45 |
+
doc_ref._type = PARSER_DATA_EMPTY
|
46 |
+
return doc_ref
|
47 |
+
|
48 |
+
def resolve_string(self, string, context, *, base_url=None):
|
49 |
+
"""resolve_string(self, string, context, base_url=None)
|
50 |
+
|
51 |
+
Return a parsable string as input document.
|
52 |
+
|
53 |
+
Pass data string and context as parameters. You can pass the
|
54 |
+
source URL or filename through the ``base_url`` keyword
|
55 |
+
argument.
|
56 |
+
"""
|
57 |
+
cdef _InputDocument doc_ref
|
58 |
+
if isinstance(string, unicode):
|
59 |
+
string = (<unicode>string).encode('utf8')
|
60 |
+
elif not isinstance(string, bytes):
|
61 |
+
raise TypeError, "argument must be a byte string or unicode string"
|
62 |
+
doc_ref = _InputDocument()
|
63 |
+
doc_ref._type = PARSER_DATA_STRING
|
64 |
+
doc_ref._data_bytes = string
|
65 |
+
if base_url is not None:
|
66 |
+
doc_ref._filename = _encodeFilename(base_url)
|
67 |
+
return doc_ref
|
68 |
+
|
69 |
+
def resolve_filename(self, filename, context):
|
70 |
+
"""resolve_filename(self, filename, context)
|
71 |
+
|
72 |
+
Return the name of a parsable file as input document.
|
73 |
+
|
74 |
+
Pass filename and context as parameters. You can also pass a
|
75 |
+
URL with an HTTP, FTP or file target.
|
76 |
+
"""
|
77 |
+
cdef _InputDocument doc_ref
|
78 |
+
doc_ref = _InputDocument()
|
79 |
+
doc_ref._type = PARSER_DATA_FILENAME
|
80 |
+
doc_ref._filename = _encodeFilename(filename)
|
81 |
+
return doc_ref
|
82 |
+
|
83 |
+
def resolve_file(self, f, context, *, base_url=None, bint close=True):
|
84 |
+
"""resolve_file(self, f, context, base_url=None, close=True)
|
85 |
+
|
86 |
+
Return an open file-like object as input document.
|
87 |
+
|
88 |
+
Pass open file and context as parameters. You can pass the
|
89 |
+
base URL or filename of the file through the ``base_url``
|
90 |
+
keyword argument. If the ``close`` flag is True (the
|
91 |
+
default), the file will be closed after reading.
|
92 |
+
|
93 |
+
Note that using ``.resolve_filename()`` is more efficient,
|
94 |
+
especially in threaded environments.
|
95 |
+
"""
|
96 |
+
cdef _InputDocument doc_ref
|
97 |
+
try:
|
98 |
+
f.read
|
99 |
+
except AttributeError:
|
100 |
+
raise TypeError, "Argument is not a file-like object"
|
101 |
+
doc_ref = _InputDocument()
|
102 |
+
doc_ref._type = PARSER_DATA_FILE
|
103 |
+
if base_url is not None:
|
104 |
+
doc_ref._filename = _encodeFilename(base_url)
|
105 |
+
else:
|
106 |
+
doc_ref._filename = _getFilenameForFile(f)
|
107 |
+
doc_ref._close_file = close
|
108 |
+
doc_ref._file = f
|
109 |
+
return doc_ref
|
110 |
+
|
111 |
+
@cython.final
|
112 |
+
@cython.internal
|
113 |
+
cdef class _ResolverRegistry:
|
114 |
+
cdef object _resolvers
|
115 |
+
cdef Resolver _default_resolver
|
116 |
+
def __cinit__(self, Resolver default_resolver=None):
|
117 |
+
self._resolvers = set()
|
118 |
+
self._default_resolver = default_resolver
|
119 |
+
|
120 |
+
def add(self, Resolver resolver not None):
|
121 |
+
"""add(self, resolver)
|
122 |
+
|
123 |
+
Register a resolver.
|
124 |
+
|
125 |
+
For each requested entity, the 'resolve' method of the resolver will
|
126 |
+
be called and the result will be passed to the parser. If this method
|
127 |
+
returns None, the request will be delegated to other resolvers or the
|
128 |
+
default resolver. The resolvers will be tested in an arbitrary order
|
129 |
+
until the first match is found.
|
130 |
+
"""
|
131 |
+
self._resolvers.add(resolver)
|
132 |
+
|
133 |
+
def remove(self, resolver):
|
134 |
+
"remove(self, resolver)"
|
135 |
+
self._resolvers.discard(resolver)
|
136 |
+
|
137 |
+
cdef _ResolverRegistry _copy(self):
|
138 |
+
cdef _ResolverRegistry registry
|
139 |
+
registry = _ResolverRegistry(self._default_resolver)
|
140 |
+
registry._resolvers = self._resolvers.copy()
|
141 |
+
return registry
|
142 |
+
|
143 |
+
def copy(self):
|
144 |
+
"copy(self)"
|
145 |
+
return self._copy()
|
146 |
+
|
147 |
+
def resolve(self, system_url, public_id, context):
|
148 |
+
"resolve(self, system_url, public_id, context)"
|
149 |
+
for resolver in self._resolvers:
|
150 |
+
result = resolver.resolve(system_url, public_id, context)
|
151 |
+
if result is not None:
|
152 |
+
return result
|
153 |
+
if self._default_resolver is None:
|
154 |
+
return None
|
155 |
+
return self._default_resolver.resolve(system_url, public_id, context)
|
156 |
+
|
157 |
+
def __repr__(self):
|
158 |
+
return repr(self._resolvers)
|
159 |
+
|
160 |
+
|
161 |
+
@cython.internal
|
162 |
+
cdef class _ResolverContext(_ExceptionContext):
|
163 |
+
cdef _ResolverRegistry _resolvers
|
164 |
+
cdef _TempStore _storage
|
165 |
+
|
166 |
+
cdef int clear(self) except -1:
|
167 |
+
_ExceptionContext.clear(self)
|
168 |
+
self._storage.clear()
|
169 |
+
return 0
|
170 |
+
|
171 |
+
|
172 |
+
cdef _initResolverContext(_ResolverContext context,
|
173 |
+
_ResolverRegistry resolvers):
|
174 |
+
if resolvers is None:
|
175 |
+
context._resolvers = _ResolverRegistry()
|
176 |
+
else:
|
177 |
+
context._resolvers = resolvers
|
178 |
+
context._storage = _TempStore()
|
env-llmeval/lib/python3.10/site-packages/lxml/doctestcompare.py
ADDED
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
lxml-based doctest output comparison.
|
3 |
+
|
4 |
+
Note: normally, you should just import the `lxml.usedoctest` and
|
5 |
+
`lxml.html.usedoctest` modules from within a doctest, instead of this
|
6 |
+
one::
|
7 |
+
|
8 |
+
>>> import lxml.usedoctest # for XML output
|
9 |
+
|
10 |
+
>>> import lxml.html.usedoctest # for HTML output
|
11 |
+
|
12 |
+
To use this module directly, you must call ``lxmldoctest.install()``,
|
13 |
+
which will cause doctest to use this in all subsequent calls.
|
14 |
+
|
15 |
+
This changes the way output is checked and comparisons are made for
|
16 |
+
XML or HTML-like content.
|
17 |
+
|
18 |
+
XML or HTML content is noticed because the example starts with ``<``
|
19 |
+
(it's HTML if it starts with ``<html``). You can also use the
|
20 |
+
``PARSE_HTML`` and ``PARSE_XML`` flags to force parsing.
|
21 |
+
|
22 |
+
Some rough wildcard-like things are allowed. Whitespace is generally
|
23 |
+
ignored (except in attributes). In text (attributes and text in the
|
24 |
+
body) you can use ``...`` as a wildcard. In an example it also
|
25 |
+
matches any trailing tags in the element, though it does not match
|
26 |
+
leading tags. You may create a tag ``<any>`` or include an ``any``
|
27 |
+
attribute in the tag. An ``any`` tag matches any tag, while the
|
28 |
+
attribute matches any and all attributes.
|
29 |
+
|
30 |
+
When a match fails, the reformatted example and gotten text is
|
31 |
+
displayed (indented), and a rough diff-like output is given. Anything
|
32 |
+
marked with ``+`` is in the output but wasn't supposed to be, and
|
33 |
+
similarly ``-`` means its in the example but wasn't in the output.
|
34 |
+
|
35 |
+
You can disable parsing on one line with ``# doctest:+NOPARSE_MARKUP``
|
36 |
+
"""
|
37 |
+
|
38 |
+
from lxml import etree
|
39 |
+
import sys
|
40 |
+
import re
|
41 |
+
import doctest
|
42 |
+
try:
|
43 |
+
from html import escape as html_escape
|
44 |
+
except ImportError:
|
45 |
+
from cgi import escape as html_escape
|
46 |
+
|
47 |
+
__all__ = ['PARSE_HTML', 'PARSE_XML', 'NOPARSE_MARKUP', 'LXMLOutputChecker',
|
48 |
+
'LHTMLOutputChecker', 'install', 'temp_install']
|
49 |
+
|
50 |
+
PARSE_HTML = doctest.register_optionflag('PARSE_HTML')
|
51 |
+
PARSE_XML = doctest.register_optionflag('PARSE_XML')
|
52 |
+
NOPARSE_MARKUP = doctest.register_optionflag('NOPARSE_MARKUP')
|
53 |
+
|
54 |
+
OutputChecker = doctest.OutputChecker
|
55 |
+
|
56 |
+
def strip(v):
|
57 |
+
if v is None:
|
58 |
+
return None
|
59 |
+
else:
|
60 |
+
return v.strip()
|
61 |
+
|
62 |
+
def norm_whitespace(v):
|
63 |
+
return _norm_whitespace_re.sub(' ', v)
|
64 |
+
|
65 |
+
_html_parser = etree.HTMLParser(recover=False, remove_blank_text=True)
|
66 |
+
|
67 |
+
def html_fromstring(html):
|
68 |
+
return etree.fromstring(html, _html_parser)
|
69 |
+
|
70 |
+
# We use this to distinguish repr()s from elements:
|
71 |
+
_repr_re = re.compile(r'^<[^>]+ (at|object) ')
|
72 |
+
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
|
73 |
+
|
74 |
+
class LXMLOutputChecker(OutputChecker):
|
75 |
+
|
76 |
+
empty_tags = (
|
77 |
+
'param', 'img', 'area', 'br', 'basefont', 'input',
|
78 |
+
'base', 'meta', 'link', 'col')
|
79 |
+
|
80 |
+
def get_default_parser(self):
|
81 |
+
return etree.XML
|
82 |
+
|
83 |
+
def check_output(self, want, got, optionflags):
|
84 |
+
alt_self = getattr(self, '_temp_override_self', None)
|
85 |
+
if alt_self is not None:
|
86 |
+
super_method = self._temp_call_super_check_output
|
87 |
+
self = alt_self
|
88 |
+
else:
|
89 |
+
super_method = OutputChecker.check_output
|
90 |
+
parser = self.get_parser(want, got, optionflags)
|
91 |
+
if not parser:
|
92 |
+
return super_method(
|
93 |
+
self, want, got, optionflags)
|
94 |
+
try:
|
95 |
+
want_doc = parser(want)
|
96 |
+
except etree.XMLSyntaxError:
|
97 |
+
return False
|
98 |
+
try:
|
99 |
+
got_doc = parser(got)
|
100 |
+
except etree.XMLSyntaxError:
|
101 |
+
return False
|
102 |
+
return self.compare_docs(want_doc, got_doc)
|
103 |
+
|
104 |
+
def get_parser(self, want, got, optionflags):
|
105 |
+
parser = None
|
106 |
+
if NOPARSE_MARKUP & optionflags:
|
107 |
+
return None
|
108 |
+
if PARSE_HTML & optionflags:
|
109 |
+
parser = html_fromstring
|
110 |
+
elif PARSE_XML & optionflags:
|
111 |
+
parser = etree.XML
|
112 |
+
elif (want.strip().lower().startswith('<html')
|
113 |
+
and got.strip().startswith('<html')):
|
114 |
+
parser = html_fromstring
|
115 |
+
elif (self._looks_like_markup(want)
|
116 |
+
and self._looks_like_markup(got)):
|
117 |
+
parser = self.get_default_parser()
|
118 |
+
return parser
|
119 |
+
|
120 |
+
def _looks_like_markup(self, s):
|
121 |
+
s = s.strip()
|
122 |
+
return (s.startswith('<')
|
123 |
+
and not _repr_re.search(s))
|
124 |
+
|
125 |
+
def compare_docs(self, want, got):
|
126 |
+
if not self.tag_compare(want.tag, got.tag):
|
127 |
+
return False
|
128 |
+
if not self.text_compare(want.text, got.text, True):
|
129 |
+
return False
|
130 |
+
if not self.text_compare(want.tail, got.tail, True):
|
131 |
+
return False
|
132 |
+
if 'any' not in want.attrib:
|
133 |
+
want_keys = sorted(want.attrib.keys())
|
134 |
+
got_keys = sorted(got.attrib.keys())
|
135 |
+
if want_keys != got_keys:
|
136 |
+
return False
|
137 |
+
for key in want_keys:
|
138 |
+
if not self.text_compare(want.attrib[key], got.attrib[key], False):
|
139 |
+
return False
|
140 |
+
if want.text != '...' or len(want):
|
141 |
+
want_children = list(want)
|
142 |
+
got_children = list(got)
|
143 |
+
while want_children or got_children:
|
144 |
+
if not want_children or not got_children:
|
145 |
+
return False
|
146 |
+
want_first = want_children.pop(0)
|
147 |
+
got_first = got_children.pop(0)
|
148 |
+
if not self.compare_docs(want_first, got_first):
|
149 |
+
return False
|
150 |
+
if not got_children and want_first.tail == '...':
|
151 |
+
break
|
152 |
+
return True
|
153 |
+
|
154 |
+
def text_compare(self, want, got, strip):
|
155 |
+
want = want or ''
|
156 |
+
got = got or ''
|
157 |
+
if strip:
|
158 |
+
want = norm_whitespace(want).strip()
|
159 |
+
got = norm_whitespace(got).strip()
|
160 |
+
want = '^%s$' % re.escape(want)
|
161 |
+
want = want.replace(r'\.\.\.', '.*')
|
162 |
+
if re.search(want, got):
|
163 |
+
return True
|
164 |
+
else:
|
165 |
+
return False
|
166 |
+
|
167 |
+
def tag_compare(self, want, got):
|
168 |
+
if want == 'any':
|
169 |
+
return True
|
170 |
+
if (not isinstance(want, (str, bytes))
|
171 |
+
or not isinstance(got, (str, bytes))):
|
172 |
+
return want == got
|
173 |
+
want = want or ''
|
174 |
+
got = got or ''
|
175 |
+
if want.startswith('{...}'):
|
176 |
+
# Ellipsis on the namespace
|
177 |
+
return want.split('}')[-1] == got.split('}')[-1]
|
178 |
+
else:
|
179 |
+
return want == got
|
180 |
+
|
181 |
+
def output_difference(self, example, got, optionflags):
|
182 |
+
want = example.want
|
183 |
+
parser = self.get_parser(want, got, optionflags)
|
184 |
+
errors = []
|
185 |
+
if parser is not None:
|
186 |
+
try:
|
187 |
+
want_doc = parser(want)
|
188 |
+
except etree.XMLSyntaxError:
|
189 |
+
e = sys.exc_info()[1]
|
190 |
+
errors.append('In example: %s' % e)
|
191 |
+
try:
|
192 |
+
got_doc = parser(got)
|
193 |
+
except etree.XMLSyntaxError:
|
194 |
+
e = sys.exc_info()[1]
|
195 |
+
errors.append('In actual output: %s' % e)
|
196 |
+
if parser is None or errors:
|
197 |
+
value = OutputChecker.output_difference(
|
198 |
+
self, example, got, optionflags)
|
199 |
+
if errors:
|
200 |
+
errors.append(value)
|
201 |
+
return '\n'.join(errors)
|
202 |
+
else:
|
203 |
+
return value
|
204 |
+
html = parser is html_fromstring
|
205 |
+
diff_parts = ['Expected:',
|
206 |
+
self.format_doc(want_doc, html, 2),
|
207 |
+
'Got:',
|
208 |
+
self.format_doc(got_doc, html, 2),
|
209 |
+
'Diff:',
|
210 |
+
self.collect_diff(want_doc, got_doc, html, 2)]
|
211 |
+
return '\n'.join(diff_parts)
|
212 |
+
|
213 |
+
def html_empty_tag(self, el, html=True):
|
214 |
+
if not html:
|
215 |
+
return False
|
216 |
+
if el.tag not in self.empty_tags:
|
217 |
+
return False
|
218 |
+
if el.text or len(el):
|
219 |
+
# This shouldn't happen (contents in an empty tag)
|
220 |
+
return False
|
221 |
+
return True
|
222 |
+
|
223 |
+
def format_doc(self, doc, html, indent, prefix=''):
|
224 |
+
parts = []
|
225 |
+
if not len(doc):
|
226 |
+
# No children...
|
227 |
+
parts.append(' '*indent)
|
228 |
+
parts.append(prefix)
|
229 |
+
parts.append(self.format_tag(doc))
|
230 |
+
if not self.html_empty_tag(doc, html):
|
231 |
+
if strip(doc.text):
|
232 |
+
parts.append(self.format_text(doc.text))
|
233 |
+
parts.append(self.format_end_tag(doc))
|
234 |
+
if strip(doc.tail):
|
235 |
+
parts.append(self.format_text(doc.tail))
|
236 |
+
parts.append('\n')
|
237 |
+
return ''.join(parts)
|
238 |
+
parts.append(' '*indent)
|
239 |
+
parts.append(prefix)
|
240 |
+
parts.append(self.format_tag(doc))
|
241 |
+
if not self.html_empty_tag(doc, html):
|
242 |
+
parts.append('\n')
|
243 |
+
if strip(doc.text):
|
244 |
+
parts.append(' '*indent)
|
245 |
+
parts.append(self.format_text(doc.text))
|
246 |
+
parts.append('\n')
|
247 |
+
for el in doc:
|
248 |
+
parts.append(self.format_doc(el, html, indent+2))
|
249 |
+
parts.append(' '*indent)
|
250 |
+
parts.append(self.format_end_tag(doc))
|
251 |
+
parts.append('\n')
|
252 |
+
if strip(doc.tail):
|
253 |
+
parts.append(' '*indent)
|
254 |
+
parts.append(self.format_text(doc.tail))
|
255 |
+
parts.append('\n')
|
256 |
+
return ''.join(parts)
|
257 |
+
|
258 |
+
def format_text(self, text, strip=True):
|
259 |
+
if text is None:
|
260 |
+
return ''
|
261 |
+
if strip:
|
262 |
+
text = text.strip()
|
263 |
+
return html_escape(text, 1)
|
264 |
+
|
265 |
+
def format_tag(self, el):
|
266 |
+
attrs = []
|
267 |
+
if isinstance(el, etree.CommentBase):
|
268 |
+
# FIXME: probably PIs should be handled specially too?
|
269 |
+
return '<!--'
|
270 |
+
for name, value in sorted(el.attrib.items()):
|
271 |
+
attrs.append('%s="%s"' % (name, self.format_text(value, False)))
|
272 |
+
if not attrs:
|
273 |
+
return '<%s>' % el.tag
|
274 |
+
return '<%s %s>' % (el.tag, ' '.join(attrs))
|
275 |
+
|
276 |
+
def format_end_tag(self, el):
|
277 |
+
if isinstance(el, etree.CommentBase):
|
278 |
+
# FIXME: probably PIs should be handled specially too?
|
279 |
+
return '-->'
|
280 |
+
return '</%s>' % el.tag
|
281 |
+
|
282 |
+
def collect_diff(self, want, got, html, indent):
|
283 |
+
parts = []
|
284 |
+
if not len(want) and not len(got):
|
285 |
+
parts.append(' '*indent)
|
286 |
+
parts.append(self.collect_diff_tag(want, got))
|
287 |
+
if not self.html_empty_tag(got, html):
|
288 |
+
parts.append(self.collect_diff_text(want.text, got.text))
|
289 |
+
parts.append(self.collect_diff_end_tag(want, got))
|
290 |
+
parts.append(self.collect_diff_text(want.tail, got.tail))
|
291 |
+
parts.append('\n')
|
292 |
+
return ''.join(parts)
|
293 |
+
parts.append(' '*indent)
|
294 |
+
parts.append(self.collect_diff_tag(want, got))
|
295 |
+
parts.append('\n')
|
296 |
+
if strip(want.text) or strip(got.text):
|
297 |
+
parts.append(' '*indent)
|
298 |
+
parts.append(self.collect_diff_text(want.text, got.text))
|
299 |
+
parts.append('\n')
|
300 |
+
want_children = list(want)
|
301 |
+
got_children = list(got)
|
302 |
+
while want_children or got_children:
|
303 |
+
if not want_children:
|
304 |
+
parts.append(self.format_doc(got_children.pop(0), html, indent+2, '+'))
|
305 |
+
continue
|
306 |
+
if not got_children:
|
307 |
+
parts.append(self.format_doc(want_children.pop(0), html, indent+2, '-'))
|
308 |
+
continue
|
309 |
+
parts.append(self.collect_diff(
|
310 |
+
want_children.pop(0), got_children.pop(0), html, indent+2))
|
311 |
+
parts.append(' '*indent)
|
312 |
+
parts.append(self.collect_diff_end_tag(want, got))
|
313 |
+
parts.append('\n')
|
314 |
+
if strip(want.tail) or strip(got.tail):
|
315 |
+
parts.append(' '*indent)
|
316 |
+
parts.append(self.collect_diff_text(want.tail, got.tail))
|
317 |
+
parts.append('\n')
|
318 |
+
return ''.join(parts)
|
319 |
+
|
320 |
+
def collect_diff_tag(self, want, got):
|
321 |
+
if not self.tag_compare(want.tag, got.tag):
|
322 |
+
tag = '%s (got: %s)' % (want.tag, got.tag)
|
323 |
+
else:
|
324 |
+
tag = got.tag
|
325 |
+
attrs = []
|
326 |
+
any = want.tag == 'any' or 'any' in want.attrib
|
327 |
+
for name, value in sorted(got.attrib.items()):
|
328 |
+
if name not in want.attrib and not any:
|
329 |
+
attrs.append('+%s="%s"' % (name, self.format_text(value, False)))
|
330 |
+
else:
|
331 |
+
if name in want.attrib:
|
332 |
+
text = self.collect_diff_text(want.attrib[name], value, False)
|
333 |
+
else:
|
334 |
+
text = self.format_text(value, False)
|
335 |
+
attrs.append('%s="%s"' % (name, text))
|
336 |
+
if not any:
|
337 |
+
for name, value in sorted(want.attrib.items()):
|
338 |
+
if name in got.attrib:
|
339 |
+
continue
|
340 |
+
attrs.append('-%s="%s"' % (name, self.format_text(value, False)))
|
341 |
+
if attrs:
|
342 |
+
tag = '<%s %s>' % (tag, ' '.join(attrs))
|
343 |
+
else:
|
344 |
+
tag = '<%s>' % tag
|
345 |
+
return tag
|
346 |
+
|
347 |
+
def collect_diff_end_tag(self, want, got):
|
348 |
+
if want.tag != got.tag:
|
349 |
+
tag = '%s (got: %s)' % (want.tag, got.tag)
|
350 |
+
else:
|
351 |
+
tag = got.tag
|
352 |
+
return '</%s>' % tag
|
353 |
+
|
354 |
+
def collect_diff_text(self, want, got, strip=True):
|
355 |
+
if self.text_compare(want, got, strip):
|
356 |
+
if not got:
|
357 |
+
return ''
|
358 |
+
return self.format_text(got, strip)
|
359 |
+
text = '%s (got: %s)' % (want, got)
|
360 |
+
return self.format_text(text, strip)
|
361 |
+
|
362 |
+
class LHTMLOutputChecker(LXMLOutputChecker):
|
363 |
+
def get_default_parser(self):
|
364 |
+
return html_fromstring
|
365 |
+
|
366 |
+
def install(html=False):
|
367 |
+
"""
|
368 |
+
Install doctestcompare for all future doctests.
|
369 |
+
|
370 |
+
If html is true, then by default the HTML parser will be used;
|
371 |
+
otherwise the XML parser is used.
|
372 |
+
"""
|
373 |
+
if html:
|
374 |
+
doctest.OutputChecker = LHTMLOutputChecker
|
375 |
+
else:
|
376 |
+
doctest.OutputChecker = LXMLOutputChecker
|
377 |
+
|
378 |
+
def temp_install(html=False, del_module=None):
|
379 |
+
"""
|
380 |
+
Use this *inside* a doctest to enable this checker for this
|
381 |
+
doctest only.
|
382 |
+
|
383 |
+
If html is true, then by default the HTML parser will be used;
|
384 |
+
otherwise the XML parser is used.
|
385 |
+
"""
|
386 |
+
if html:
|
387 |
+
Checker = LHTMLOutputChecker
|
388 |
+
else:
|
389 |
+
Checker = LXMLOutputChecker
|
390 |
+
frame = _find_doctest_frame()
|
391 |
+
dt_self = frame.f_locals['self']
|
392 |
+
checker = Checker()
|
393 |
+
old_checker = dt_self._checker
|
394 |
+
dt_self._checker = checker
|
395 |
+
# The unfortunate thing is that there is a local variable 'check'
|
396 |
+
# in the function that runs the doctests, that is a bound method
|
397 |
+
# into the output checker. We have to update that. We can't
|
398 |
+
# modify the frame, so we have to modify the object in place. The
|
399 |
+
# only way to do this is to actually change the func_code
|
400 |
+
# attribute of the method. We change it, and then wait for
|
401 |
+
# __record_outcome to be run, which signals the end of the __run
|
402 |
+
# method, at which point we restore the previous check_output
|
403 |
+
# implementation.
|
404 |
+
check_func = frame.f_locals['check'].__func__
|
405 |
+
checker_check_func = checker.check_output.__func__
|
406 |
+
# Because we can't patch up func_globals, this is the only global
|
407 |
+
# in check_output that we care about:
|
408 |
+
doctest.etree = etree
|
409 |
+
_RestoreChecker(dt_self, old_checker, checker,
|
410 |
+
check_func, checker_check_func,
|
411 |
+
del_module)
|
412 |
+
|
413 |
+
class _RestoreChecker:
|
414 |
+
def __init__(self, dt_self, old_checker, new_checker, check_func, clone_func,
|
415 |
+
del_module):
|
416 |
+
self.dt_self = dt_self
|
417 |
+
self.checker = old_checker
|
418 |
+
self.checker._temp_call_super_check_output = self.call_super
|
419 |
+
self.checker._temp_override_self = new_checker
|
420 |
+
self.check_func = check_func
|
421 |
+
self.clone_func = clone_func
|
422 |
+
self.del_module = del_module
|
423 |
+
self.install_clone()
|
424 |
+
self.install_dt_self()
|
425 |
+
def install_clone(self):
|
426 |
+
self.func_code = self.check_func.__code__
|
427 |
+
self.func_globals = self.check_func.__globals__
|
428 |
+
self.check_func.__code__ = self.clone_func.__code__
|
429 |
+
def uninstall_clone(self):
|
430 |
+
self.check_func.__code__ = self.func_code
|
431 |
+
def install_dt_self(self):
|
432 |
+
self.prev_func = self.dt_self._DocTestRunner__record_outcome
|
433 |
+
self.dt_self._DocTestRunner__record_outcome = self
|
434 |
+
def uninstall_dt_self(self):
|
435 |
+
self.dt_self._DocTestRunner__record_outcome = self.prev_func
|
436 |
+
def uninstall_module(self):
|
437 |
+
if self.del_module:
|
438 |
+
import sys
|
439 |
+
del sys.modules[self.del_module]
|
440 |
+
if '.' in self.del_module:
|
441 |
+
package, module = self.del_module.rsplit('.', 1)
|
442 |
+
package_mod = sys.modules[package]
|
443 |
+
delattr(package_mod, module)
|
444 |
+
def __call__(self, *args, **kw):
|
445 |
+
self.uninstall_clone()
|
446 |
+
self.uninstall_dt_self()
|
447 |
+
del self.checker._temp_override_self
|
448 |
+
del self.checker._temp_call_super_check_output
|
449 |
+
result = self.prev_func(*args, **kw)
|
450 |
+
self.uninstall_module()
|
451 |
+
return result
|
452 |
+
def call_super(self, *args, **kw):
|
453 |
+
self.uninstall_clone()
|
454 |
+
try:
|
455 |
+
return self.check_func(*args, **kw)
|
456 |
+
finally:
|
457 |
+
self.install_clone()
|
458 |
+
|
459 |
+
def _find_doctest_frame():
|
460 |
+
import sys
|
461 |
+
frame = sys._getframe(1)
|
462 |
+
while frame:
|
463 |
+
l = frame.f_locals
|
464 |
+
if 'BOOM' in l:
|
465 |
+
# Sign of doctest
|
466 |
+
return frame
|
467 |
+
frame = frame.f_back
|
468 |
+
raise LookupError(
|
469 |
+
"Could not find doctest (only use this function *inside* a doctest)")
|
470 |
+
|
471 |
+
__test__ = {
|
472 |
+
'basic': '''
|
473 |
+
>>> temp_install()
|
474 |
+
>>> print """<xml a="1" b="2">stuff</xml>"""
|
475 |
+
<xml b="2" a="1">...</xml>
|
476 |
+
>>> print """<xml xmlns="http://example.com"><tag attr="bar" /></xml>"""
|
477 |
+
<xml xmlns="...">
|
478 |
+
<tag attr="..." />
|
479 |
+
</xml>
|
480 |
+
>>> print """<xml>blahblahblah<foo /></xml>""" # doctest: +NOPARSE_MARKUP, +ELLIPSIS
|
481 |
+
<xml>...foo /></xml>
|
482 |
+
'''}
|
483 |
+
|
484 |
+
if __name__ == '__main__':
|
485 |
+
import doctest
|
486 |
+
doctest.testmod()
|
487 |
+
|
488 |
+
|
env-llmeval/lib/python3.10/site-packages/lxml/etree.pyx
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/lxml/etree_api.h
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* Generated by Cython 3.0.10 */
|
2 |
+
|
3 |
+
#ifndef __PYX_HAVE_API__lxml__etree
|
4 |
+
#define __PYX_HAVE_API__lxml__etree
|
5 |
+
#ifdef __MINGW64__
|
6 |
+
#define MS_WIN64
|
7 |
+
#endif
|
8 |
+
#include "Python.h"
|
9 |
+
#include "etree.h"
|
10 |
+
|
11 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0;
|
12 |
+
#define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument
|
13 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0;
|
14 |
+
#define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory
|
15 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0;
|
16 |
+
#define newElementTree __pyx_api_f_4lxml_5etree_newElementTree
|
17 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0;
|
18 |
+
#define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument
|
19 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0;
|
20 |
+
#define elementFactory __pyx_api_f_4lxml_5etree_elementFactory
|
21 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
22 |
+
#define makeElement __pyx_api_f_4lxml_5etree_makeElement
|
23 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
24 |
+
#define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement
|
25 |
+
static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0;
|
26 |
+
#define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction
|
27 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
28 |
+
#define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass
|
29 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
30 |
+
#define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass
|
31 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0;
|
32 |
+
#define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback
|
33 |
+
static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
34 |
+
#define tagMatches __pyx_api_f_4lxml_5etree_tagMatches
|
35 |
+
static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0;
|
36 |
+
#define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise
|
37 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0;
|
38 |
+
#define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise
|
39 |
+
static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0;
|
40 |
+
#define hasText __pyx_api_f_4lxml_5etree_hasText
|
41 |
+
static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0;
|
42 |
+
#define hasTail __pyx_api_f_4lxml_5etree_hasTail
|
43 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0;
|
44 |
+
#define textOf __pyx_api_f_4lxml_5etree_textOf
|
45 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0;
|
46 |
+
#define tailOf __pyx_api_f_4lxml_5etree_tailOf
|
47 |
+
static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0;
|
48 |
+
#define setNodeText __pyx_api_f_4lxml_5etree_setNodeText
|
49 |
+
static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0;
|
50 |
+
#define setTailText __pyx_api_f_4lxml_5etree_setTailText
|
51 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0;
|
52 |
+
#define attributeValue __pyx_api_f_4lxml_5etree_attributeValue
|
53 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
54 |
+
#define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName
|
55 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
56 |
+
#define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue
|
57 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0;
|
58 |
+
#define iterattributes __pyx_api_f_4lxml_5etree_iterattributes
|
59 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0;
|
60 |
+
#define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes
|
61 |
+
static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
62 |
+
#define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue
|
63 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0;
|
64 |
+
#define delAttribute __pyx_api_f_4lxml_5etree_delAttribute
|
65 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
66 |
+
#define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName
|
67 |
+
static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0;
|
68 |
+
#define hasChild __pyx_api_f_4lxml_5etree_hasChild
|
69 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0;
|
70 |
+
#define findChild __pyx_api_f_4lxml_5etree_findChild
|
71 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0;
|
72 |
+
#define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards
|
73 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0;
|
74 |
+
#define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards
|
75 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0;
|
76 |
+
#define nextElement __pyx_api_f_4lxml_5etree_nextElement
|
77 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0;
|
78 |
+
#define previousElement __pyx_api_f_4lxml_5etree_previousElement
|
79 |
+
static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0;
|
80 |
+
#define appendChild __pyx_api_f_4lxml_5etree_appendChild
|
81 |
+
static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0;
|
82 |
+
#define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement
|
83 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0;
|
84 |
+
#define pyunicode __pyx_api_f_4lxml_5etree_pyunicode
|
85 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0;
|
86 |
+
#define utf8 __pyx_api_f_4lxml_5etree_utf8
|
87 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0;
|
88 |
+
#define getNsTag __pyx_api_f_4lxml_5etree_getNsTag
|
89 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0;
|
90 |
+
#define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs
|
91 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0;
|
92 |
+
#define namespacedName __pyx_api_f_4lxml_5etree_namespacedName
|
93 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0;
|
94 |
+
#define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName
|
95 |
+
static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0;
|
96 |
+
#define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext
|
97 |
+
static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0;
|
98 |
+
#define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch
|
99 |
+
static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
100 |
+
#define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix
|
101 |
+
#ifndef __PYX_HAVE_RT_ImportFunction_3_0_10
|
102 |
+
#define __PYX_HAVE_RT_ImportFunction_3_0_10
|
103 |
+
static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
|
104 |
+
PyObject *d = 0;
|
105 |
+
PyObject *cobj = 0;
|
106 |
+
union {
|
107 |
+
void (*fp)(void);
|
108 |
+
void *p;
|
109 |
+
} tmp;
|
110 |
+
d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
|
111 |
+
if (!d)
|
112 |
+
goto bad;
|
113 |
+
cobj = PyDict_GetItemString(d, funcname);
|
114 |
+
if (!cobj) {
|
115 |
+
PyErr_Format(PyExc_ImportError,
|
116 |
+
"%.200s does not export expected C function %.200s",
|
117 |
+
PyModule_GetName(module), funcname);
|
118 |
+
goto bad;
|
119 |
+
}
|
120 |
+
if (!PyCapsule_IsValid(cobj, sig)) {
|
121 |
+
PyErr_Format(PyExc_TypeError,
|
122 |
+
"C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
|
123 |
+
PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
|
124 |
+
goto bad;
|
125 |
+
}
|
126 |
+
tmp.p = PyCapsule_GetPointer(cobj, sig);
|
127 |
+
*f = tmp.fp;
|
128 |
+
if (!(*f))
|
129 |
+
goto bad;
|
130 |
+
Py_DECREF(d);
|
131 |
+
return 0;
|
132 |
+
bad:
|
133 |
+
Py_XDECREF(d);
|
134 |
+
return -1;
|
135 |
+
}
|
136 |
+
#endif
|
137 |
+
|
138 |
+
|
139 |
+
static int import_lxml__etree(void) {
|
140 |
+
PyObject *module = 0;
|
141 |
+
module = PyImport_ImportModule("lxml.etree");
|
142 |
+
if (!module) goto bad;
|
143 |
+
if (__Pyx_ImportFunction_3_0_10(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
144 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad;
|
145 |
+
if (__Pyx_ImportFunction_3_0_10(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad;
|
146 |
+
if (__Pyx_ImportFunction_3_0_10(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad;
|
147 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
148 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeElement, "struct LxmlElement *(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
149 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeSubElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeSubElement, "struct LxmlElement *(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
150 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setElementClassLookupFunction", (void (**)(void))&__pyx_api_f_4lxml_5etree_setElementClassLookupFunction, "void (_element_class_lookup_function, PyObject *)") < 0) goto bad;
|
151 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
152 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
153 |
+
if (__Pyx_ImportFunction_3_0_10(module, "callLookupFallback", (void (**)(void))&__pyx_api_f_4lxml_5etree_callLookupFallback, "PyObject *(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
154 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tagMatches", (void (**)(void))&__pyx_api_f_4lxml_5etree_tagMatches, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
155 |
+
if (__Pyx_ImportFunction_3_0_10(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad;
|
156 |
+
if (__Pyx_ImportFunction_3_0_10(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad;
|
157 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad;
|
158 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad;
|
159 |
+
if (__Pyx_ImportFunction_3_0_10(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
160 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
161 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
162 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
163 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad;
|
164 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValueFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValueFromNsName, "PyObject *(xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
165 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
166 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad;
|
167 |
+
if (__Pyx_ImportFunction_3_0_10(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad;
|
168 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
169 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad;
|
170 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttributeFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttributeFromNsName, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
171 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad;
|
172 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
173 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
174 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
175 |
+
if (__Pyx_ImportFunction_3_0_10(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
176 |
+
if (__Pyx_ImportFunction_3_0_10(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
177 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
178 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
179 |
+
if (__Pyx_ImportFunction_3_0_10(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad;
|
180 |
+
if (__Pyx_ImportFunction_3_0_10(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad;
|
181 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad;
|
182 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad;
|
183 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad;
|
184 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad;
|
185 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad;
|
186 |
+
if (__Pyx_ImportFunction_3_0_10(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad;
|
187 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findOrBuildNodeNsPrefix", (void (**)(void))&__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix, "xmlNs *(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
188 |
+
Py_DECREF(module); module = 0;
|
189 |
+
return 0;
|
190 |
+
bad:
|
191 |
+
Py_XDECREF(module);
|
192 |
+
return -1;
|
193 |
+
}
|
194 |
+
|
195 |
+
#endif /* !__PYX_HAVE_API__lxml__etree */
|
env-llmeval/lib/python3.10/site-packages/lxml/extensions.pxi
ADDED
@@ -0,0 +1,833 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
env-llmeval/lib/python3.10/site-packages/lxml/iterparse.pxi
ADDED
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# iterparse -- event-driven parsing
|
2 |
+
|
3 |
+
DEF __ITERPARSE_CHUNK_SIZE = 32768
|
4 |
+
|
5 |
+
cdef class iterparse:
|
6 |
+
"""iterparse(self, source, events=("end",), tag=None, \
|
7 |
+
attribute_defaults=False, dtd_validation=False, \
|
8 |
+
load_dtd=False, no_network=True, remove_blank_text=False, \
|
9 |
+
remove_comments=False, remove_pis=False, encoding=None, \
|
10 |
+
html=False, recover=None, huge_tree=False, schema=None)
|
11 |
+
|
12 |
+
Incremental parser.
|
13 |
+
|
14 |
+
Parses XML into a tree and generates tuples (event, element) in a
|
15 |
+
SAX-like fashion. ``event`` is any of 'start', 'end', 'start-ns',
|
16 |
+
'end-ns'.
|
17 |
+
|
18 |
+
For 'start' and 'end', ``element`` is the Element that the parser just
|
19 |
+
found opening or closing. For 'start-ns', it is a tuple (prefix, URI) of
|
20 |
+
a new namespace declaration. For 'end-ns', it is simply None. Note that
|
21 |
+
all start and end events are guaranteed to be properly nested.
|
22 |
+
|
23 |
+
The keyword argument ``events`` specifies a sequence of event type names
|
24 |
+
that should be generated. By default, only 'end' events will be
|
25 |
+
generated.
|
26 |
+
|
27 |
+
The additional ``tag`` argument restricts the 'start' and 'end' events to
|
28 |
+
those elements that match the given tag. The ``tag`` argument can also be
|
29 |
+
a sequence of tags to allow matching more than one tag. By default,
|
30 |
+
events are generated for all elements. Note that the 'start-ns' and
|
31 |
+
'end-ns' events are not impacted by this restriction.
|
32 |
+
|
33 |
+
The other keyword arguments in the constructor are mainly based on the
|
34 |
+
libxml2 parser configuration. A DTD will also be loaded if validation or
|
35 |
+
attribute default values are requested.
|
36 |
+
|
37 |
+
Available boolean keyword arguments:
|
38 |
+
- attribute_defaults: read default attributes from DTD
|
39 |
+
- dtd_validation: validate (if DTD is available)
|
40 |
+
- load_dtd: use DTD for parsing
|
41 |
+
- no_network: prevent network access for related files
|
42 |
+
- remove_blank_text: discard blank text nodes
|
43 |
+
- remove_comments: discard comments
|
44 |
+
- remove_pis: discard processing instructions
|
45 |
+
- strip_cdata: replace CDATA sections by normal text content (default: True)
|
46 |
+
- compact: safe memory for short text content (default: True)
|
47 |
+
- resolve_entities: replace entities by their text value (default: True)
|
48 |
+
- huge_tree: disable security restrictions and support very deep trees
|
49 |
+
and very long text content (only affects libxml2 2.7+)
|
50 |
+
- html: parse input as HTML (default: XML)
|
51 |
+
- recover: try hard to parse through broken input (default: True for HTML,
|
52 |
+
False otherwise)
|
53 |
+
|
54 |
+
Other keyword arguments:
|
55 |
+
- encoding: override the document encoding
|
56 |
+
- schema: an XMLSchema to validate against
|
57 |
+
"""
|
58 |
+
cdef _FeedParser _parser
|
59 |
+
cdef object _tag
|
60 |
+
cdef object _events
|
61 |
+
cdef readonly object root
|
62 |
+
cdef object _source
|
63 |
+
cdef object _filename
|
64 |
+
cdef object _error
|
65 |
+
cdef bint _close_source_after_read
|
66 |
+
|
67 |
+
def __init__(self, source, events=("end",), *, tag=None,
|
68 |
+
attribute_defaults=False, dtd_validation=False,
|
69 |
+
load_dtd=False, no_network=True, remove_blank_text=False,
|
70 |
+
compact=True, resolve_entities=True, remove_comments=False,
|
71 |
+
remove_pis=False, strip_cdata=True, encoding=None,
|
72 |
+
html=False, recover=None, huge_tree=False, collect_ids=True,
|
73 |
+
XMLSchema schema=None):
|
74 |
+
if not hasattr(source, 'read'):
|
75 |
+
source = _getFSPathOrObject(source)
|
76 |
+
self._filename = source
|
77 |
+
self._source = open(source, 'rb')
|
78 |
+
self._close_source_after_read = True
|
79 |
+
else:
|
80 |
+
self._filename = _getFilenameForFile(source)
|
81 |
+
self._source = source
|
82 |
+
self._close_source_after_read = False
|
83 |
+
|
84 |
+
if recover is None:
|
85 |
+
recover = html
|
86 |
+
|
87 |
+
if html:
|
88 |
+
# make sure we're not looking for namespaces
|
89 |
+
events = [event for event in events
|
90 |
+
if event not in ('start-ns', 'end-ns')]
|
91 |
+
parser = HTMLPullParser(
|
92 |
+
events,
|
93 |
+
tag=tag,
|
94 |
+
recover=recover,
|
95 |
+
base_url=self._filename,
|
96 |
+
encoding=encoding,
|
97 |
+
remove_blank_text=remove_blank_text,
|
98 |
+
remove_comments=remove_comments,
|
99 |
+
remove_pis=remove_pis,
|
100 |
+
strip_cdata=strip_cdata,
|
101 |
+
no_network=no_network,
|
102 |
+
target=None, # TODO
|
103 |
+
schema=schema,
|
104 |
+
compact=compact)
|
105 |
+
else:
|
106 |
+
parser = XMLPullParser(
|
107 |
+
events,
|
108 |
+
tag=tag,
|
109 |
+
recover=recover,
|
110 |
+
base_url=self._filename,
|
111 |
+
encoding=encoding,
|
112 |
+
attribute_defaults=attribute_defaults,
|
113 |
+
dtd_validation=dtd_validation,
|
114 |
+
load_dtd=load_dtd,
|
115 |
+
no_network=no_network,
|
116 |
+
schema=schema,
|
117 |
+
huge_tree=huge_tree,
|
118 |
+
remove_blank_text=remove_blank_text,
|
119 |
+
resolve_entities=resolve_entities,
|
120 |
+
remove_comments=remove_comments,
|
121 |
+
remove_pis=remove_pis,
|
122 |
+
strip_cdata=strip_cdata,
|
123 |
+
collect_ids=True,
|
124 |
+
target=None, # TODO
|
125 |
+
compact=compact)
|
126 |
+
|
127 |
+
self._events = parser.read_events()
|
128 |
+
self._parser = parser
|
129 |
+
|
130 |
+
@property
|
131 |
+
def error_log(self):
|
132 |
+
"""The error log of the last (or current) parser run.
|
133 |
+
"""
|
134 |
+
return self._parser.feed_error_log
|
135 |
+
|
136 |
+
@property
|
137 |
+
def resolvers(self):
|
138 |
+
"""The custom resolver registry of the last (or current) parser run.
|
139 |
+
"""
|
140 |
+
return self._parser.resolvers
|
141 |
+
|
142 |
+
@property
|
143 |
+
def version(self):
|
144 |
+
"""The version of the underlying XML parser."""
|
145 |
+
return self._parser.version
|
146 |
+
|
147 |
+
def set_element_class_lookup(self, ElementClassLookup lookup = None):
|
148 |
+
"""set_element_class_lookup(self, lookup = None)
|
149 |
+
|
150 |
+
Set a lookup scheme for element classes generated from this parser.
|
151 |
+
|
152 |
+
Reset it by passing None or nothing.
|
153 |
+
"""
|
154 |
+
self._parser.set_element_class_lookup(lookup)
|
155 |
+
|
156 |
+
def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
|
157 |
+
"""makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
|
158 |
+
|
159 |
+
Creates a new element associated with this parser.
|
160 |
+
"""
|
161 |
+
self._parser.makeelement(
|
162 |
+
_tag, attrib=None, nsmap=None, **_extra)
|
163 |
+
|
164 |
+
@cython.final
|
165 |
+
cdef _close_source(self):
|
166 |
+
if self._source is None:
|
167 |
+
return
|
168 |
+
if not self._close_source_after_read:
|
169 |
+
self._source = None
|
170 |
+
return
|
171 |
+
try:
|
172 |
+
close = self._source.close
|
173 |
+
except AttributeError:
|
174 |
+
close = None
|
175 |
+
finally:
|
176 |
+
self._source = None
|
177 |
+
if close is not None:
|
178 |
+
close()
|
179 |
+
|
180 |
+
def __iter__(self):
|
181 |
+
return self
|
182 |
+
|
183 |
+
def __next__(self):
|
184 |
+
try:
|
185 |
+
return next(self._events)
|
186 |
+
except StopIteration:
|
187 |
+
pass
|
188 |
+
context = <_SaxParserContext>self._parser._getPushParserContext()
|
189 |
+
if self._source is not None:
|
190 |
+
done = False
|
191 |
+
while not done:
|
192 |
+
try:
|
193 |
+
done = self._read_more_events(context)
|
194 |
+
return next(self._events)
|
195 |
+
except StopIteration:
|
196 |
+
pass # no events yet
|
197 |
+
except Exception as e:
|
198 |
+
self._error = e
|
199 |
+
self._close_source()
|
200 |
+
try:
|
201 |
+
return next(self._events)
|
202 |
+
except StopIteration:
|
203 |
+
break
|
204 |
+
# nothing left to read or return
|
205 |
+
if self._error is not None:
|
206 |
+
error = self._error
|
207 |
+
self._error = None
|
208 |
+
raise error
|
209 |
+
if (context._validator is not None
|
210 |
+
and not context._validator.isvalid()):
|
211 |
+
_raiseParseError(context._c_ctxt, self._filename,
|
212 |
+
context._error_log)
|
213 |
+
# no errors => all done
|
214 |
+
raise StopIteration
|
215 |
+
|
216 |
+
@cython.final
|
217 |
+
cdef bint _read_more_events(self, _SaxParserContext context) except -123:
|
218 |
+
data = self._source.read(__ITERPARSE_CHUNK_SIZE)
|
219 |
+
if not isinstance(data, bytes):
|
220 |
+
self._close_source()
|
221 |
+
raise TypeError("reading file objects must return bytes objects")
|
222 |
+
if not data:
|
223 |
+
try:
|
224 |
+
self.root = self._parser.close()
|
225 |
+
finally:
|
226 |
+
self._close_source()
|
227 |
+
return True
|
228 |
+
self._parser.feed(data)
|
229 |
+
return False
|
230 |
+
|
231 |
+
|
232 |
+
cdef enum _IterwalkSkipStates:
|
233 |
+
IWSKIP_NEXT_IS_START
|
234 |
+
IWSKIP_SKIP_NEXT
|
235 |
+
IWSKIP_CAN_SKIP
|
236 |
+
IWSKIP_CANNOT_SKIP
|
237 |
+
|
238 |
+
|
239 |
+
cdef class iterwalk:
|
240 |
+
"""iterwalk(self, element_or_tree, events=("end",), tag=None)
|
241 |
+
|
242 |
+
A tree walker that generates events from an existing tree as if it
|
243 |
+
was parsing XML data with ``iterparse()``.
|
244 |
+
|
245 |
+
Just as for ``iterparse()``, the ``tag`` argument can be a single tag or a
|
246 |
+
sequence of tags.
|
247 |
+
|
248 |
+
After receiving a 'start' or 'start-ns' event, the children and
|
249 |
+
descendants of the current element can be excluded from iteration
|
250 |
+
by calling the ``skip_subtree()`` method.
|
251 |
+
"""
|
252 |
+
cdef _MultiTagMatcher _matcher
|
253 |
+
cdef list _node_stack
|
254 |
+
cdef list _events
|
255 |
+
cdef object _pop_event
|
256 |
+
cdef object _include_siblings
|
257 |
+
cdef int _index
|
258 |
+
cdef int _event_filter
|
259 |
+
cdef _IterwalkSkipStates _skip_state
|
260 |
+
|
261 |
+
def __init__(self, element_or_tree, events=("end",), tag=None):
|
262 |
+
cdef _Element root
|
263 |
+
cdef int ns_count
|
264 |
+
root = _rootNodeOrRaise(element_or_tree)
|
265 |
+
self._event_filter = _buildParseEventFilter(events)
|
266 |
+
if tag is None or tag == '*':
|
267 |
+
self._matcher = None
|
268 |
+
else:
|
269 |
+
self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag)
|
270 |
+
self._node_stack = []
|
271 |
+
self._events = []
|
272 |
+
self._pop_event = self._events.pop
|
273 |
+
self._skip_state = IWSKIP_CANNOT_SKIP # ignore all skip requests by default
|
274 |
+
|
275 |
+
if self._event_filter:
|
276 |
+
self._index = 0
|
277 |
+
if self._matcher is not None and self._event_filter & PARSE_EVENT_FILTER_START:
|
278 |
+
self._matcher.cacheTags(root._doc)
|
279 |
+
|
280 |
+
# When processing an ElementTree, add events for the preceding comments/PIs.
|
281 |
+
if self._event_filter & (PARSE_EVENT_FILTER_COMMENT | PARSE_EVENT_FILTER_PI):
|
282 |
+
if isinstance(element_or_tree, _ElementTree):
|
283 |
+
self._include_siblings = root
|
284 |
+
for elem in list(root.itersiblings(preceding=True))[::-1]:
|
285 |
+
if self._event_filter & PARSE_EVENT_FILTER_COMMENT and elem.tag is Comment:
|
286 |
+
self._events.append(('comment', elem))
|
287 |
+
elif self._event_filter & PARSE_EVENT_FILTER_PI and elem.tag is PI:
|
288 |
+
self._events.append(('pi', elem))
|
289 |
+
|
290 |
+
ns_count = self._start_node(root)
|
291 |
+
self._node_stack.append( (root, ns_count) )
|
292 |
+
else:
|
293 |
+
self._index = -1
|
294 |
+
|
295 |
+
def __iter__(self):
|
296 |
+
return self
|
297 |
+
|
298 |
+
def __next__(self):
|
299 |
+
cdef xmlNode* c_child
|
300 |
+
cdef _Element node
|
301 |
+
cdef _Element next_node
|
302 |
+
cdef int ns_count = 0
|
303 |
+
if self._events:
|
304 |
+
return self._next_event()
|
305 |
+
if self._matcher is not None and self._index >= 0:
|
306 |
+
node = self._node_stack[self._index][0]
|
307 |
+
self._matcher.cacheTags(node._doc)
|
308 |
+
|
309 |
+
# find next node
|
310 |
+
while self._index >= 0:
|
311 |
+
node = self._node_stack[self._index][0]
|
312 |
+
|
313 |
+
if self._skip_state == IWSKIP_SKIP_NEXT:
|
314 |
+
c_child = NULL
|
315 |
+
else:
|
316 |
+
c_child = self._process_non_elements(
|
317 |
+
node._doc, _findChildForwards(node._c_node, 0))
|
318 |
+
self._skip_state = IWSKIP_CANNOT_SKIP
|
319 |
+
|
320 |
+
while c_child is NULL:
|
321 |
+
# back off through parents
|
322 |
+
self._index -= 1
|
323 |
+
node = self._end_node()
|
324 |
+
if self._index < 0:
|
325 |
+
break
|
326 |
+
c_child = self._process_non_elements(
|
327 |
+
node._doc, _nextElement(node._c_node))
|
328 |
+
|
329 |
+
if c_child is not NULL:
|
330 |
+
next_node = _elementFactory(node._doc, c_child)
|
331 |
+
if self._event_filter & (PARSE_EVENT_FILTER_START |
|
332 |
+
PARSE_EVENT_FILTER_START_NS):
|
333 |
+
ns_count = self._start_node(next_node)
|
334 |
+
elif self._event_filter & PARSE_EVENT_FILTER_END_NS:
|
335 |
+
ns_count = _countNsDefs(next_node._c_node)
|
336 |
+
self._node_stack.append( (next_node, ns_count) )
|
337 |
+
self._index += 1
|
338 |
+
if self._events:
|
339 |
+
return self._next_event()
|
340 |
+
|
341 |
+
if self._include_siblings is not None:
|
342 |
+
node, self._include_siblings = self._include_siblings, None
|
343 |
+
self._process_non_elements(node._doc, _nextElement(node._c_node))
|
344 |
+
if self._events:
|
345 |
+
return self._next_event()
|
346 |
+
|
347 |
+
raise StopIteration
|
348 |
+
|
349 |
+
@cython.final
|
350 |
+
cdef xmlNode* _process_non_elements(self, _Document doc, xmlNode* c_node):
|
351 |
+
while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE:
|
352 |
+
if c_node.type == tree.XML_COMMENT_NODE:
|
353 |
+
if self._event_filter & PARSE_EVENT_FILTER_COMMENT:
|
354 |
+
self._events.append(
|
355 |
+
("comment", _elementFactory(doc, c_node)))
|
356 |
+
c_node = _nextElement(c_node)
|
357 |
+
elif c_node.type == tree.XML_PI_NODE:
|
358 |
+
if self._event_filter & PARSE_EVENT_FILTER_PI:
|
359 |
+
self._events.append(
|
360 |
+
("pi", _elementFactory(doc, c_node)))
|
361 |
+
c_node = _nextElement(c_node)
|
362 |
+
else:
|
363 |
+
break
|
364 |
+
return c_node
|
365 |
+
|
366 |
+
@cython.final
|
367 |
+
cdef _next_event(self):
|
368 |
+
if self._skip_state == IWSKIP_NEXT_IS_START:
|
369 |
+
if self._events[0][0] in ('start', 'start-ns'):
|
370 |
+
self._skip_state = IWSKIP_CAN_SKIP
|
371 |
+
return self._pop_event(0)
|
372 |
+
|
373 |
+
def skip_subtree(self):
|
374 |
+
"""Prevent descending into the current subtree.
|
375 |
+
Instead, the next returned event will be the 'end' event of the current element
|
376 |
+
(if included), ignoring any children or descendants.
|
377 |
+
|
378 |
+
This has no effect right after an 'end' or 'end-ns' event.
|
379 |
+
"""
|
380 |
+
if self._skip_state == IWSKIP_CAN_SKIP:
|
381 |
+
self._skip_state = IWSKIP_SKIP_NEXT
|
382 |
+
|
383 |
+
@cython.final
|
384 |
+
cdef int _start_node(self, _Element node) except -1:
|
385 |
+
cdef int ns_count
|
386 |
+
if self._event_filter & PARSE_EVENT_FILTER_START_NS:
|
387 |
+
ns_count = _appendStartNsEvents(node._c_node, self._events)
|
388 |
+
if self._events:
|
389 |
+
self._skip_state = IWSKIP_NEXT_IS_START
|
390 |
+
elif self._event_filter & PARSE_EVENT_FILTER_END_NS:
|
391 |
+
ns_count = _countNsDefs(node._c_node)
|
392 |
+
else:
|
393 |
+
ns_count = 0
|
394 |
+
if self._event_filter & PARSE_EVENT_FILTER_START:
|
395 |
+
if self._matcher is None or self._matcher.matches(node._c_node):
|
396 |
+
self._events.append( ("start", node) )
|
397 |
+
self._skip_state = IWSKIP_NEXT_IS_START
|
398 |
+
return ns_count
|
399 |
+
|
400 |
+
@cython.final
|
401 |
+
cdef _Element _end_node(self):
|
402 |
+
cdef _Element node
|
403 |
+
cdef int i, ns_count
|
404 |
+
node, ns_count = self._node_stack.pop()
|
405 |
+
if self._event_filter & PARSE_EVENT_FILTER_END:
|
406 |
+
if self._matcher is None or self._matcher.matches(node._c_node):
|
407 |
+
self._events.append( ("end", node) )
|
408 |
+
if self._event_filter & PARSE_EVENT_FILTER_END_NS and ns_count:
|
409 |
+
event = ("end-ns", None)
|
410 |
+
for i in range(ns_count):
|
411 |
+
self._events.append(event)
|
412 |
+
return node
|
413 |
+
|
414 |
+
|
415 |
+
cdef int _countNsDefs(xmlNode* c_node) noexcept:
|
416 |
+
cdef xmlNs* c_ns
|
417 |
+
cdef int count
|
418 |
+
count = 0
|
419 |
+
c_ns = c_node.nsDef
|
420 |
+
while c_ns is not NULL:
|
421 |
+
count += (c_ns.href is not NULL)
|
422 |
+
c_ns = c_ns.next
|
423 |
+
return count
|
424 |
+
|
425 |
+
|
426 |
+
cdef int _appendStartNsEvents(xmlNode* c_node, list event_list) except -1:
|
427 |
+
cdef xmlNs* c_ns
|
428 |
+
cdef int count
|
429 |
+
count = 0
|
430 |
+
c_ns = c_node.nsDef
|
431 |
+
while c_ns is not NULL:
|
432 |
+
if c_ns.href:
|
433 |
+
ns_tuple = (funicodeOrEmpty(c_ns.prefix),
|
434 |
+
funicode(c_ns.href))
|
435 |
+
event_list.append( ("start-ns", ns_tuple) )
|
436 |
+
count += 1
|
437 |
+
c_ns = c_ns.next
|
438 |
+
return count
|
env-llmeval/lib/python3.10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|
|
|
|
|
|
|
1 |
+
/* Generated by Cython 3.0.10 */
|
2 |
+
|
3 |
+
#ifndef __PYX_HAVE__lxml__etree
|
4 |
+
#define __PYX_HAVE__lxml__etree
|
5 |
+
|
6 |
+
#include "Python.h"
|
7 |
+
struct LxmlDocument;
|
8 |
+
struct LxmlElement;
|
9 |
+
struct LxmlElementTree;
|
10 |
+
struct LxmlElementTagMatcher;
|
11 |
+
struct LxmlElementIterator;
|
12 |
+
struct LxmlElementBase;
|
13 |
+
struct LxmlElementClassLookup;
|
14 |
+
struct LxmlFallbackElementClassLookup;
|
15 |
+
|
16 |
+
/* "lxml/etree.pyx":333
|
17 |
+
*
|
18 |
+
* # type of a function that steps from node to node
|
19 |
+
* ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*) # <<<<<<<<<<<<<<
|
20 |
+
*
|
21 |
+
*
|
22 |
+
*/
|
23 |
+
typedef xmlNode *(*_node_to_node_function)(xmlNode *);
|
24 |
+
|
25 |
+
/* "lxml/etree.pyx":349
|
26 |
+
* @cython.final
|
27 |
+
* @cython.freelist(8)
|
28 |
+
* cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]: # <<<<<<<<<<<<<<
|
29 |
+
* """Internal base class to reference a libxml document.
|
30 |
+
*
|
31 |
+
*/
|
32 |
+
struct LxmlDocument {
|
33 |
+
PyObject_HEAD
|
34 |
+
struct __pyx_vtabstruct_4lxml_5etree__Document *__pyx_vtab;
|
35 |
+
int _ns_counter;
|
36 |
+
PyObject *_prefix_tail;
|
37 |
+
xmlDoc *_c_doc;
|
38 |
+
struct __pyx_obj_4lxml_5etree__BaseParser *_parser;
|
39 |
+
};
|
40 |
+
|
41 |
+
/* "lxml/etree.pyx":698
|
42 |
+
*
|
43 |
+
* @cython.no_gc_clear
|
44 |
+
* cdef public class _Element [ type LxmlElementType, object LxmlElement ]: # <<<<<<<<<<<<<<
|
45 |
+
* """Element class.
|
46 |
+
*
|
47 |
+
*/
|
48 |
+
struct LxmlElement {
|
49 |
+
PyObject_HEAD
|
50 |
+
struct LxmlDocument *_doc;
|
51 |
+
xmlNode *_c_node;
|
52 |
+
PyObject *_tag;
|
53 |
+
};
|
54 |
+
|
55 |
+
/* "lxml/etree.pyx":1872
|
56 |
+
*
|
57 |
+
*
|
58 |
+
* cdef public class _ElementTree [ type LxmlElementTreeType, # <<<<<<<<<<<<<<
|
59 |
+
* object LxmlElementTree ]:
|
60 |
+
* cdef _Document _doc
|
61 |
+
*/
|
62 |
+
struct LxmlElementTree {
|
63 |
+
PyObject_HEAD
|
64 |
+
struct __pyx_vtabstruct_4lxml_5etree__ElementTree *__pyx_vtab;
|
65 |
+
struct LxmlDocument *_doc;
|
66 |
+
struct LxmlElement *_context_node;
|
67 |
+
};
|
68 |
+
|
69 |
+
/* "lxml/etree.pyx":2646
|
70 |
+
*
|
71 |
+
*
|
72 |
+
* cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher, # <<<<<<<<<<<<<<
|
73 |
+
* type LxmlElementTagMatcherType ]:
|
74 |
+
* """
|
75 |
+
*/
|
76 |
+
struct LxmlElementTagMatcher {
|
77 |
+
PyObject_HEAD
|
78 |
+
struct __pyx_vtabstruct_4lxml_5etree__ElementTagMatcher *__pyx_vtab;
|
79 |
+
PyObject *_pystrings;
|
80 |
+
int _node_type;
|
81 |
+
char *_href;
|
82 |
+
char *_name;
|
83 |
+
};
|
84 |
+
|
85 |
+
/* "lxml/etree.pyx":2677
|
86 |
+
* self._name = NULL
|
87 |
+
*
|
88 |
+
* cdef public class _ElementIterator(_ElementTagMatcher) [ # <<<<<<<<<<<<<<
|
89 |
+
* object LxmlElementIterator, type LxmlElementIteratorType ]:
|
90 |
+
* """
|
91 |
+
*/
|
92 |
+
struct LxmlElementIterator {
|
93 |
+
struct LxmlElementTagMatcher __pyx_base;
|
94 |
+
struct LxmlElement *_node;
|
95 |
+
_node_to_node_function _next_element;
|
96 |
+
};
|
97 |
+
|
98 |
+
/* "src/lxml/classlookup.pxi":6
|
99 |
+
* # Custom Element classes
|
100 |
+
*
|
101 |
+
* cdef public class ElementBase(_Element) [ type LxmlElementBaseType, # <<<<<<<<<<<<<<
|
102 |
+
* object LxmlElementBase ]:
|
103 |
+
* """ElementBase(*children, attrib=None, nsmap=None, **_extra)
|
104 |
+
*/
|
105 |
+
struct LxmlElementBase {
|
106 |
+
struct LxmlElement __pyx_base;
|
107 |
+
};
|
108 |
+
|
109 |
+
/* "src/lxml/classlookup.pxi":210
|
110 |
+
* # Element class lookup
|
111 |
+
*
|
112 |
+
* ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*) # <<<<<<<<<<<<<<
|
113 |
+
*
|
114 |
+
* # class to store element class lookup functions
|
115 |
+
*/
|
116 |
+
typedef PyObject *(*_element_class_lookup_function)(PyObject *, struct LxmlDocument *, xmlNode *);
|
117 |
+
|
118 |
+
/* "src/lxml/classlookup.pxi":213
|
119 |
+
*
|
120 |
+
* # class to store element class lookup functions
|
121 |
+
* cdef public class ElementClassLookup [ type LxmlElementClassLookupType, # <<<<<<<<<<<<<<
|
122 |
+
* object LxmlElementClassLookup ]:
|
123 |
+
* """ElementClassLookup(self)
|
124 |
+
*/
|
125 |
+
struct LxmlElementClassLookup {
|
126 |
+
PyObject_HEAD
|
127 |
+
_element_class_lookup_function _lookup_function;
|
128 |
+
};
|
129 |
+
|
130 |
+
/* "src/lxml/classlookup.pxi":221
|
131 |
+
*
|
132 |
+
*
|
133 |
+
* cdef public class FallbackElementClassLookup(ElementClassLookup) \ # <<<<<<<<<<<<<<
|
134 |
+
* [ type LxmlFallbackElementClassLookupType,
|
135 |
+
* object LxmlFallbackElementClassLookup ]:
|
136 |
+
*/
|
137 |
+
struct LxmlFallbackElementClassLookup {
|
138 |
+
struct LxmlElementClassLookup __pyx_base;
|
139 |
+
struct __pyx_vtabstruct_4lxml_5etree_FallbackElementClassLookup *__pyx_vtab;
|
140 |
+
struct LxmlElementClassLookup *fallback;
|
141 |
+
_element_class_lookup_function _fallback_function;
|
142 |
+
};
|
143 |
+
|
144 |
+
#ifndef __PYX_HAVE_API__lxml__etree
|
145 |
+
|
146 |
+
#ifdef CYTHON_EXTERN_C
|
147 |
+
#undef __PYX_EXTERN_C
|
148 |
+
#define __PYX_EXTERN_C CYTHON_EXTERN_C
|
149 |
+
#elif defined(__PYX_EXTERN_C)
|
150 |
+
#ifdef _MSC_VER
|
151 |
+
#pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.")
|
152 |
+
#else
|
153 |
+
#warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.
|
154 |
+
#endif
|
155 |
+
#else
|
156 |
+
#ifdef __cplusplus
|
157 |
+
#define __PYX_EXTERN_C extern "C"
|
158 |
+
#else
|
159 |
+
#define __PYX_EXTERN_C extern
|
160 |
+
#endif
|
161 |
+
#endif
|
162 |
+
|
163 |
+
#ifndef DL_IMPORT
|
164 |
+
#define DL_IMPORT(_T) _T
|
165 |
+
#endif
|
166 |
+
|
167 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlDocumentType;
|
168 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementType;
|
169 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTreeType;
|
170 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTagMatcherType;
|
171 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementIteratorType;
|
172 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementBaseType;
|
173 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementClassLookupType;
|
174 |
+
__PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlFallbackElementClassLookupType;
|
175 |
+
|
176 |
+
__PYX_EXTERN_C struct LxmlElement *deepcopyNodeToDocument(struct LxmlDocument *, xmlNode *);
|
177 |
+
__PYX_EXTERN_C struct LxmlElementTree *elementTreeFactory(struct LxmlElement *);
|
178 |
+
__PYX_EXTERN_C struct LxmlElementTree *newElementTree(struct LxmlElement *, PyObject *);
|
179 |
+
__PYX_EXTERN_C struct LxmlElementTree *adoptExternalDocument(xmlDoc *, PyObject *, int);
|
180 |
+
__PYX_EXTERN_C struct LxmlElement *elementFactory(struct LxmlDocument *, xmlNode *);
|
181 |
+
__PYX_EXTERN_C struct LxmlElement *makeElement(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
|
182 |
+
__PYX_EXTERN_C struct LxmlElement *makeSubElement(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
|
183 |
+
__PYX_EXTERN_C void setElementClassLookupFunction(_element_class_lookup_function, PyObject *);
|
184 |
+
__PYX_EXTERN_C PyObject *lookupDefaultElementClass(PyObject *, PyObject *, xmlNode *);
|
185 |
+
__PYX_EXTERN_C PyObject *lookupNamespaceElementClass(PyObject *, PyObject *, xmlNode *);
|
186 |
+
__PYX_EXTERN_C PyObject *callLookupFallback(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *);
|
187 |
+
__PYX_EXTERN_C int tagMatches(xmlNode *, const xmlChar *, const xmlChar *);
|
188 |
+
__PYX_EXTERN_C struct LxmlDocument *documentOrRaise(PyObject *);
|
189 |
+
__PYX_EXTERN_C struct LxmlElement *rootNodeOrRaise(PyObject *);
|
190 |
+
__PYX_EXTERN_C int hasText(xmlNode *);
|
191 |
+
__PYX_EXTERN_C int hasTail(xmlNode *);
|
192 |
+
__PYX_EXTERN_C PyObject *textOf(xmlNode *);
|
193 |
+
__PYX_EXTERN_C PyObject *tailOf(xmlNode *);
|
194 |
+
__PYX_EXTERN_C int setNodeText(xmlNode *, PyObject *);
|
195 |
+
__PYX_EXTERN_C int setTailText(xmlNode *, PyObject *);
|
196 |
+
__PYX_EXTERN_C PyObject *attributeValue(xmlNode *, xmlAttr *);
|
197 |
+
__PYX_EXTERN_C PyObject *attributeValueFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
|
198 |
+
__PYX_EXTERN_C PyObject *getAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
|
199 |
+
__PYX_EXTERN_C PyObject *iterattributes(struct LxmlElement *, int);
|
200 |
+
__PYX_EXTERN_C PyObject *collectAttributes(xmlNode *, int);
|
201 |
+
__PYX_EXTERN_C int setAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
|
202 |
+
__PYX_EXTERN_C int delAttribute(struct LxmlElement *, PyObject *);
|
203 |
+
__PYX_EXTERN_C int delAttributeFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
|
204 |
+
__PYX_EXTERN_C int hasChild(xmlNode *);
|
205 |
+
__PYX_EXTERN_C xmlNode *findChild(xmlNode *, Py_ssize_t);
|
206 |
+
__PYX_EXTERN_C xmlNode *findChildForwards(xmlNode *, Py_ssize_t);
|
207 |
+
__PYX_EXTERN_C xmlNode *findChildBackwards(xmlNode *, Py_ssize_t);
|
208 |
+
__PYX_EXTERN_C xmlNode *nextElement(xmlNode *);
|
209 |
+
__PYX_EXTERN_C xmlNode *previousElement(xmlNode *);
|
210 |
+
__PYX_EXTERN_C void appendChild(struct LxmlElement *, struct LxmlElement *);
|
211 |
+
__PYX_EXTERN_C int appendChildToElement(struct LxmlElement *, struct LxmlElement *);
|
212 |
+
__PYX_EXTERN_C PyObject *pyunicode(const xmlChar *);
|
213 |
+
__PYX_EXTERN_C PyObject *utf8(PyObject *);
|
214 |
+
__PYX_EXTERN_C PyObject *getNsTag(PyObject *);
|
215 |
+
__PYX_EXTERN_C PyObject *getNsTagWithEmptyNs(PyObject *);
|
216 |
+
__PYX_EXTERN_C PyObject *namespacedName(xmlNode *);
|
217 |
+
__PYX_EXTERN_C PyObject *namespacedNameFromNsName(const xmlChar *, const xmlChar *);
|
218 |
+
__PYX_EXTERN_C void iteratorStoreNext(struct LxmlElementIterator *, struct LxmlElement *);
|
219 |
+
__PYX_EXTERN_C void initTagMatch(struct LxmlElementTagMatcher *, PyObject *);
|
220 |
+
__PYX_EXTERN_C xmlNs *findOrBuildNodeNsPrefix(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *);
|
221 |
+
|
222 |
+
#endif /* !__PYX_HAVE_API__lxml__etree */
|
223 |
+
|
224 |
+
/* WARNING: the interface of the module init function changed in CPython 3.5. */
|
225 |
+
/* It now returns a PyModuleDef instance instead of a PyModule instance. */
|
226 |
+
|
227 |
+
#if PY_MAJOR_VERSION < 3
|
228 |
+
PyMODINIT_FUNC initetree(void);
|
229 |
+
#else
|
230 |
+
/* WARNING: Use PyImport_AppendInittab("etree", PyInit_etree) instead of calling PyInit_etree directly from Python 3.5 */
|
231 |
+
PyMODINIT_FUNC PyInit_etree(void);
|
232 |
+
|
233 |
+
#if PY_VERSION_HEX >= 0x03050000 && (defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) || (defined(__cplusplus) && __cplusplus >= 201402L))
|
234 |
+
#if defined(__cplusplus) && __cplusplus >= 201402L
|
235 |
+
[[deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")]] inline
|
236 |
+
#elif defined(__GNUC__) || defined(__clang__)
|
237 |
+
__attribute__ ((__deprecated__("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly."), __unused__)) __inline__
|
238 |
+
#elif defined(_MSC_VER)
|
239 |
+
__declspec(deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")) __inline
|
240 |
+
#endif
|
241 |
+
static PyObject* __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyObject* res) {
|
242 |
+
return res;
|
243 |
+
}
|
244 |
+
#define PyInit_etree() __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyInit_etree())
|
245 |
+
#endif
|
246 |
+
#endif
|
247 |
+
|
248 |
+
#endif /* !__PYX_HAVE__lxml__etree */
|
env-llmeval/lib/python3.10/site-packages/lxml/lxml.etree_api.h
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* Generated by Cython 3.0.10 */
|
2 |
+
|
3 |
+
#ifndef __PYX_HAVE_API__lxml__etree
|
4 |
+
#define __PYX_HAVE_API__lxml__etree
|
5 |
+
#ifdef __MINGW64__
|
6 |
+
#define MS_WIN64
|
7 |
+
#endif
|
8 |
+
#include "Python.h"
|
9 |
+
#include "lxml.etree.h"
|
10 |
+
|
11 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0;
|
12 |
+
#define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument
|
13 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0;
|
14 |
+
#define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory
|
15 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0;
|
16 |
+
#define newElementTree __pyx_api_f_4lxml_5etree_newElementTree
|
17 |
+
static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0;
|
18 |
+
#define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument
|
19 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0;
|
20 |
+
#define elementFactory __pyx_api_f_4lxml_5etree_elementFactory
|
21 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
22 |
+
#define makeElement __pyx_api_f_4lxml_5etree_makeElement
|
23 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
|
24 |
+
#define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement
|
25 |
+
static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0;
|
26 |
+
#define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction
|
27 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
28 |
+
#define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass
|
29 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
|
30 |
+
#define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass
|
31 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0;
|
32 |
+
#define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback
|
33 |
+
static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
34 |
+
#define tagMatches __pyx_api_f_4lxml_5etree_tagMatches
|
35 |
+
static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0;
|
36 |
+
#define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise
|
37 |
+
static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0;
|
38 |
+
#define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise
|
39 |
+
static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0;
|
40 |
+
#define hasText __pyx_api_f_4lxml_5etree_hasText
|
41 |
+
static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0;
|
42 |
+
#define hasTail __pyx_api_f_4lxml_5etree_hasTail
|
43 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0;
|
44 |
+
#define textOf __pyx_api_f_4lxml_5etree_textOf
|
45 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0;
|
46 |
+
#define tailOf __pyx_api_f_4lxml_5etree_tailOf
|
47 |
+
static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0;
|
48 |
+
#define setNodeText __pyx_api_f_4lxml_5etree_setNodeText
|
49 |
+
static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0;
|
50 |
+
#define setTailText __pyx_api_f_4lxml_5etree_setTailText
|
51 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0;
|
52 |
+
#define attributeValue __pyx_api_f_4lxml_5etree_attributeValue
|
53 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
54 |
+
#define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName
|
55 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
56 |
+
#define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue
|
57 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0;
|
58 |
+
#define iterattributes __pyx_api_f_4lxml_5etree_iterattributes
|
59 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0;
|
60 |
+
#define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes
|
61 |
+
static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
|
62 |
+
#define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue
|
63 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0;
|
64 |
+
#define delAttribute __pyx_api_f_4lxml_5etree_delAttribute
|
65 |
+
static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
66 |
+
#define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName
|
67 |
+
static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0;
|
68 |
+
#define hasChild __pyx_api_f_4lxml_5etree_hasChild
|
69 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0;
|
70 |
+
#define findChild __pyx_api_f_4lxml_5etree_findChild
|
71 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0;
|
72 |
+
#define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards
|
73 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0;
|
74 |
+
#define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards
|
75 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0;
|
76 |
+
#define nextElement __pyx_api_f_4lxml_5etree_nextElement
|
77 |
+
static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0;
|
78 |
+
#define previousElement __pyx_api_f_4lxml_5etree_previousElement
|
79 |
+
static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0;
|
80 |
+
#define appendChild __pyx_api_f_4lxml_5etree_appendChild
|
81 |
+
static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0;
|
82 |
+
#define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement
|
83 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0;
|
84 |
+
#define pyunicode __pyx_api_f_4lxml_5etree_pyunicode
|
85 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0;
|
86 |
+
#define utf8 __pyx_api_f_4lxml_5etree_utf8
|
87 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0;
|
88 |
+
#define getNsTag __pyx_api_f_4lxml_5etree_getNsTag
|
89 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0;
|
90 |
+
#define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs
|
91 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0;
|
92 |
+
#define namespacedName __pyx_api_f_4lxml_5etree_namespacedName
|
93 |
+
static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0;
|
94 |
+
#define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName
|
95 |
+
static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0;
|
96 |
+
#define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext
|
97 |
+
static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0;
|
98 |
+
#define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch
|
99 |
+
static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0;
|
100 |
+
#define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix
|
101 |
+
#ifndef __PYX_HAVE_RT_ImportFunction_3_0_10
|
102 |
+
#define __PYX_HAVE_RT_ImportFunction_3_0_10
|
103 |
+
static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
|
104 |
+
PyObject *d = 0;
|
105 |
+
PyObject *cobj = 0;
|
106 |
+
union {
|
107 |
+
void (*fp)(void);
|
108 |
+
void *p;
|
109 |
+
} tmp;
|
110 |
+
d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
|
111 |
+
if (!d)
|
112 |
+
goto bad;
|
113 |
+
cobj = PyDict_GetItemString(d, funcname);
|
114 |
+
if (!cobj) {
|
115 |
+
PyErr_Format(PyExc_ImportError,
|
116 |
+
"%.200s does not export expected C function %.200s",
|
117 |
+
PyModule_GetName(module), funcname);
|
118 |
+
goto bad;
|
119 |
+
}
|
120 |
+
if (!PyCapsule_IsValid(cobj, sig)) {
|
121 |
+
PyErr_Format(PyExc_TypeError,
|
122 |
+
"C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
|
123 |
+
PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
|
124 |
+
goto bad;
|
125 |
+
}
|
126 |
+
tmp.p = PyCapsule_GetPointer(cobj, sig);
|
127 |
+
*f = tmp.fp;
|
128 |
+
if (!(*f))
|
129 |
+
goto bad;
|
130 |
+
Py_DECREF(d);
|
131 |
+
return 0;
|
132 |
+
bad:
|
133 |
+
Py_XDECREF(d);
|
134 |
+
return -1;
|
135 |
+
}
|
136 |
+
#endif
|
137 |
+
|
138 |
+
|
139 |
+
static int import_lxml__etree(void) {
|
140 |
+
PyObject *module = 0;
|
141 |
+
module = PyImport_ImportModule("lxml.etree");
|
142 |
+
if (!module) goto bad;
|
143 |
+
if (__Pyx_ImportFunction_3_0_10(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
144 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad;
|
145 |
+
if (__Pyx_ImportFunction_3_0_10(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad;
|
146 |
+
if (__Pyx_ImportFunction_3_0_10(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad;
|
147 |
+
if (__Pyx_ImportFunction_3_0_10(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
148 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeElement, "struct LxmlElement *(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
149 |
+
if (__Pyx_ImportFunction_3_0_10(module, "makeSubElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeSubElement, "struct LxmlElement *(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
|
150 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setElementClassLookupFunction", (void (**)(void))&__pyx_api_f_4lxml_5etree_setElementClassLookupFunction, "void (_element_class_lookup_function, PyObject *)") < 0) goto bad;
|
151 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
152 |
+
if (__Pyx_ImportFunction_3_0_10(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
|
153 |
+
if (__Pyx_ImportFunction_3_0_10(module, "callLookupFallback", (void (**)(void))&__pyx_api_f_4lxml_5etree_callLookupFallback, "PyObject *(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *)") < 0) goto bad;
|
154 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tagMatches", (void (**)(void))&__pyx_api_f_4lxml_5etree_tagMatches, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
155 |
+
if (__Pyx_ImportFunction_3_0_10(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad;
|
156 |
+
if (__Pyx_ImportFunction_3_0_10(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad;
|
157 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad;
|
158 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad;
|
159 |
+
if (__Pyx_ImportFunction_3_0_10(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
160 |
+
if (__Pyx_ImportFunction_3_0_10(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad;
|
161 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
162 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad;
|
163 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad;
|
164 |
+
if (__Pyx_ImportFunction_3_0_10(module, "attributeValueFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValueFromNsName, "PyObject *(xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
165 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
166 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad;
|
167 |
+
if (__Pyx_ImportFunction_3_0_10(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad;
|
168 |
+
if (__Pyx_ImportFunction_3_0_10(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
|
169 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad;
|
170 |
+
if (__Pyx_ImportFunction_3_0_10(module, "delAttributeFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttributeFromNsName, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
171 |
+
if (__Pyx_ImportFunction_3_0_10(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad;
|
172 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
173 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
174 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
|
175 |
+
if (__Pyx_ImportFunction_3_0_10(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
176 |
+
if (__Pyx_ImportFunction_3_0_10(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad;
|
177 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
178 |
+
if (__Pyx_ImportFunction_3_0_10(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
|
179 |
+
if (__Pyx_ImportFunction_3_0_10(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad;
|
180 |
+
if (__Pyx_ImportFunction_3_0_10(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad;
|
181 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad;
|
182 |
+
if (__Pyx_ImportFunction_3_0_10(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad;
|
183 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad;
|
184 |
+
if (__Pyx_ImportFunction_3_0_10(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad;
|
185 |
+
if (__Pyx_ImportFunction_3_0_10(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad;
|
186 |
+
if (__Pyx_ImportFunction_3_0_10(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad;
|
187 |
+
if (__Pyx_ImportFunction_3_0_10(module, "findOrBuildNodeNsPrefix", (void (**)(void))&__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix, "xmlNs *(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
|
188 |
+
Py_DECREF(module); module = 0;
|
189 |
+
return 0;
|
190 |
+
bad:
|
191 |
+
Py_XDECREF(module);
|
192 |
+
return -1;
|
193 |
+
}
|
194 |
+
|
195 |
+
#endif /* !__PYX_HAVE_API__lxml__etree */
|
env-llmeval/lib/python3.10/site-packages/lxml/nsclasses.pxi
ADDED
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# module-level API for namespace implementations
|
2 |
+
|
3 |
+
cdef class LxmlRegistryError(LxmlError):
|
4 |
+
"""Base class of lxml registry errors.
|
5 |
+
"""
|
6 |
+
|
7 |
+
cdef class NamespaceRegistryError(LxmlRegistryError):
|
8 |
+
"""Error registering a namespace extension.
|
9 |
+
"""
|
10 |
+
|
11 |
+
|
12 |
+
@cython.internal
|
13 |
+
cdef class _NamespaceRegistry:
|
14 |
+
"Dictionary-like namespace registry"
|
15 |
+
cdef object _ns_uri
|
16 |
+
cdef bytes _ns_uri_utf
|
17 |
+
cdef dict _entries
|
18 |
+
cdef char* _c_ns_uri_utf
|
19 |
+
def __cinit__(self, ns_uri):
|
20 |
+
self._ns_uri = ns_uri
|
21 |
+
if ns_uri is None:
|
22 |
+
self._ns_uri_utf = None
|
23 |
+
self._c_ns_uri_utf = NULL
|
24 |
+
else:
|
25 |
+
self._ns_uri_utf = _utf8(ns_uri)
|
26 |
+
self._c_ns_uri_utf = _cstr(self._ns_uri_utf)
|
27 |
+
self._entries = {}
|
28 |
+
|
29 |
+
def update(self, class_dict_iterable):
|
30 |
+
"""update(self, class_dict_iterable)
|
31 |
+
|
32 |
+
Forgivingly update the registry.
|
33 |
+
|
34 |
+
``class_dict_iterable`` may be a dict or some other iterable
|
35 |
+
that yields (name, value) pairs.
|
36 |
+
|
37 |
+
If a value does not match the required type for this registry,
|
38 |
+
or if the name starts with '_', it will be silently discarded.
|
39 |
+
This allows registrations at the module or class level using
|
40 |
+
vars(), globals() etc."""
|
41 |
+
if hasattr(class_dict_iterable, 'items'):
|
42 |
+
class_dict_iterable = class_dict_iterable.items()
|
43 |
+
for name, item in class_dict_iterable:
|
44 |
+
if (name is None or name[:1] != '_') and callable(item):
|
45 |
+
self[name] = item
|
46 |
+
|
47 |
+
def __getitem__(self, name):
|
48 |
+
if name is not None:
|
49 |
+
name = _utf8(name)
|
50 |
+
return self._get(name)
|
51 |
+
|
52 |
+
def __delitem__(self, name):
|
53 |
+
if name is not None:
|
54 |
+
name = _utf8(name)
|
55 |
+
del self._entries[name]
|
56 |
+
|
57 |
+
cdef object _get(self, object name):
|
58 |
+
cdef python.PyObject* dict_result
|
59 |
+
dict_result = python.PyDict_GetItem(self._entries, name)
|
60 |
+
if dict_result is NULL:
|
61 |
+
raise KeyError, "Name not registered."
|
62 |
+
return <object>dict_result
|
63 |
+
|
64 |
+
cdef object _getForString(self, char* name):
|
65 |
+
cdef python.PyObject* dict_result
|
66 |
+
dict_result = python.PyDict_GetItem(self._entries, name)
|
67 |
+
if dict_result is NULL:
|
68 |
+
raise KeyError, "Name not registered."
|
69 |
+
return <object>dict_result
|
70 |
+
|
71 |
+
def __iter__(self):
|
72 |
+
return iter(self._entries)
|
73 |
+
|
74 |
+
def items(self):
|
75 |
+
return list(self._entries.items())
|
76 |
+
|
77 |
+
def iteritems(self):
|
78 |
+
return iter(self._entries.items())
|
79 |
+
|
80 |
+
def clear(self):
|
81 |
+
self._entries.clear()
|
82 |
+
|
83 |
+
def __call__(self, obj):
|
84 |
+
# Usage as decorator:
|
85 |
+
# ns = lookup.get_namespace("...")
|
86 |
+
# @ns('abc')
|
87 |
+
# class element(ElementBase): pass
|
88 |
+
#
|
89 |
+
# @ns
|
90 |
+
# class elementname(ElementBase): pass
|
91 |
+
|
92 |
+
if obj is None or python._isString(obj):
|
93 |
+
# @ns(None) or @ns('tag')
|
94 |
+
return partial(self.__deco, obj)
|
95 |
+
# plain @ns decorator
|
96 |
+
self[obj.__name__] = obj
|
97 |
+
return obj
|
98 |
+
|
99 |
+
def __deco(self, name, obj):
|
100 |
+
self[name] = obj
|
101 |
+
return obj
|
102 |
+
|
103 |
+
|
104 |
+
@cython.final
|
105 |
+
@cython.internal
|
106 |
+
cdef class _ClassNamespaceRegistry(_NamespaceRegistry):
|
107 |
+
"Dictionary-like registry for namespace implementation classes"
|
108 |
+
def __setitem__(self, name, item):
|
109 |
+
if not isinstance(item, type) or not issubclass(item, ElementBase):
|
110 |
+
raise NamespaceRegistryError, \
|
111 |
+
"Registered element classes must be subtypes of ElementBase"
|
112 |
+
if name is not None:
|
113 |
+
name = _utf8(name)
|
114 |
+
self._entries[name] = item
|
115 |
+
|
116 |
+
def __repr__(self):
|
117 |
+
return "Namespace(%r)" % self._ns_uri
|
118 |
+
|
119 |
+
|
120 |
+
cdef class ElementNamespaceClassLookup(FallbackElementClassLookup):
|
121 |
+
"""ElementNamespaceClassLookup(self, fallback=None)
|
122 |
+
|
123 |
+
Element class lookup scheme that searches the Element class in the
|
124 |
+
Namespace registry.
|
125 |
+
|
126 |
+
Usage:
|
127 |
+
|
128 |
+
>>> lookup = ElementNamespaceClassLookup()
|
129 |
+
>>> ns_elements = lookup.get_namespace("http://schema.org/Movie")
|
130 |
+
|
131 |
+
>>> @ns_elements
|
132 |
+
... class movie(ElementBase):
|
133 |
+
... "Element implementation for 'movie' tag (using class name) in schema namespace."
|
134 |
+
|
135 |
+
>>> @ns_elements("movie")
|
136 |
+
... class MovieElement(ElementBase):
|
137 |
+
... "Element implementation for 'movie' tag (explicit tag name) in schema namespace."
|
138 |
+
"""
|
139 |
+
cdef dict _namespace_registries
|
140 |
+
def __cinit__(self):
|
141 |
+
self._namespace_registries = {}
|
142 |
+
|
143 |
+
def __init__(self, ElementClassLookup fallback=None):
|
144 |
+
FallbackElementClassLookup.__init__(self, fallback)
|
145 |
+
self._lookup_function = _find_nselement_class
|
146 |
+
|
147 |
+
def get_namespace(self, ns_uri):
|
148 |
+
"""get_namespace(self, ns_uri)
|
149 |
+
|
150 |
+
Retrieve the namespace object associated with the given URI.
|
151 |
+
Pass None for the empty namespace.
|
152 |
+
|
153 |
+
Creates a new namespace object if it does not yet exist."""
|
154 |
+
if ns_uri:
|
155 |
+
ns_utf = _utf8(ns_uri)
|
156 |
+
else:
|
157 |
+
ns_utf = None
|
158 |
+
try:
|
159 |
+
return self._namespace_registries[ns_utf]
|
160 |
+
except KeyError:
|
161 |
+
registry = self._namespace_registries[ns_utf] = \
|
162 |
+
_ClassNamespaceRegistry(ns_uri)
|
163 |
+
return registry
|
164 |
+
|
165 |
+
cdef object _find_nselement_class(state, _Document doc, xmlNode* c_node):
|
166 |
+
cdef python.PyObject* dict_result
|
167 |
+
cdef ElementNamespaceClassLookup lookup
|
168 |
+
cdef _NamespaceRegistry registry
|
169 |
+
if state is None:
|
170 |
+
return _lookupDefaultElementClass(None, doc, c_node)
|
171 |
+
|
172 |
+
lookup = <ElementNamespaceClassLookup>state
|
173 |
+
if c_node.type != tree.XML_ELEMENT_NODE:
|
174 |
+
return _callLookupFallback(lookup, doc, c_node)
|
175 |
+
|
176 |
+
c_namespace_utf = _getNs(c_node)
|
177 |
+
if c_namespace_utf is not NULL:
|
178 |
+
dict_result = python.PyDict_GetItem(
|
179 |
+
lookup._namespace_registries, <unsigned char*>c_namespace_utf)
|
180 |
+
else:
|
181 |
+
dict_result = python.PyDict_GetItem(
|
182 |
+
lookup._namespace_registries, None)
|
183 |
+
if dict_result is not NULL:
|
184 |
+
registry = <_NamespaceRegistry>dict_result
|
185 |
+
classes = registry._entries
|
186 |
+
|
187 |
+
if c_node.name is not NULL:
|
188 |
+
dict_result = python.PyDict_GetItem(
|
189 |
+
classes, <unsigned char*>c_node.name)
|
190 |
+
else:
|
191 |
+
dict_result = NULL
|
192 |
+
|
193 |
+
if dict_result is NULL:
|
194 |
+
dict_result = python.PyDict_GetItem(classes, None)
|
195 |
+
|
196 |
+
if dict_result is not NULL:
|
197 |
+
return <object>dict_result
|
198 |
+
return _callLookupFallback(lookup, doc, c_node)
|
199 |
+
|
200 |
+
|
201 |
+
################################################################################
|
202 |
+
# XPath extension functions
|
203 |
+
|
204 |
+
cdef dict __FUNCTION_NAMESPACE_REGISTRIES
|
205 |
+
__FUNCTION_NAMESPACE_REGISTRIES = {}
|
206 |
+
|
207 |
+
def FunctionNamespace(ns_uri):
|
208 |
+
"""FunctionNamespace(ns_uri)
|
209 |
+
|
210 |
+
Retrieve the function namespace object associated with the given
|
211 |
+
URI.
|
212 |
+
|
213 |
+
Creates a new one if it does not yet exist. A function namespace
|
214 |
+
can only be used to register extension functions.
|
215 |
+
|
216 |
+
Usage:
|
217 |
+
|
218 |
+
>>> ns_functions = FunctionNamespace("http://schema.org/Movie")
|
219 |
+
|
220 |
+
>>> @ns_functions # uses function name
|
221 |
+
... def add2(x):
|
222 |
+
... return x + 2
|
223 |
+
|
224 |
+
>>> @ns_functions("add3") # uses explicit name
|
225 |
+
... def add_three(x):
|
226 |
+
... return x + 3
|
227 |
+
"""
|
228 |
+
ns_utf = _utf8(ns_uri) if ns_uri else None
|
229 |
+
try:
|
230 |
+
return __FUNCTION_NAMESPACE_REGISTRIES[ns_utf]
|
231 |
+
except KeyError:
|
232 |
+
registry = __FUNCTION_NAMESPACE_REGISTRIES[ns_utf] = \
|
233 |
+
_XPathFunctionNamespaceRegistry(ns_uri)
|
234 |
+
return registry
|
235 |
+
|
236 |
+
@cython.internal
|
237 |
+
cdef class _FunctionNamespaceRegistry(_NamespaceRegistry):
|
238 |
+
def __setitem__(self, name, item):
|
239 |
+
if not callable(item):
|
240 |
+
raise NamespaceRegistryError, \
|
241 |
+
"Registered functions must be callable."
|
242 |
+
if not name:
|
243 |
+
raise ValueError, \
|
244 |
+
"extensions must have non empty names"
|
245 |
+
self._entries[_utf8(name)] = item
|
246 |
+
|
247 |
+
def __repr__(self):
|
248 |
+
return "FunctionNamespace(%r)" % self._ns_uri
|
249 |
+
|
250 |
+
@cython.final
|
251 |
+
@cython.internal
|
252 |
+
cdef class _XPathFunctionNamespaceRegistry(_FunctionNamespaceRegistry):
|
253 |
+
cdef object _prefix
|
254 |
+
cdef bytes _prefix_utf
|
255 |
+
|
256 |
+
property prefix:
|
257 |
+
"Namespace prefix for extension functions."
|
258 |
+
def __del__(self):
|
259 |
+
self._prefix = None # no prefix configured
|
260 |
+
self._prefix_utf = None
|
261 |
+
def __get__(self):
|
262 |
+
if self._prefix is None:
|
263 |
+
return ''
|
264 |
+
else:
|
265 |
+
return self._prefix
|
266 |
+
def __set__(self, prefix):
|
267 |
+
if prefix == '':
|
268 |
+
prefix = None # empty prefix
|
269 |
+
self._prefix_utf = _utf8(prefix) if prefix is not None else None
|
270 |
+
self._prefix = prefix
|
271 |
+
|
272 |
+
cdef list _find_all_extension_prefixes():
|
273 |
+
"Internal lookup function to find all function prefixes for XSLT/XPath."
|
274 |
+
cdef _XPathFunctionNamespaceRegistry registry
|
275 |
+
cdef list ns_prefixes = []
|
276 |
+
for registry in __FUNCTION_NAMESPACE_REGISTRIES.itervalues():
|
277 |
+
if registry._prefix_utf is not None:
|
278 |
+
if registry._ns_uri_utf is not None:
|
279 |
+
ns_prefixes.append(
|
280 |
+
(registry._prefix_utf, registry._ns_uri_utf))
|
281 |
+
return ns_prefixes
|
env-llmeval/lib/python3.10/site-packages/lxml/objectify.pyx
ADDED
@@ -0,0 +1,2145 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: binding=True
|
2 |
+
# cython: auto_pickle=False
|
3 |
+
# cython: language_level=3
|
4 |
+
|
5 |
+
"""
|
6 |
+
The ``lxml.objectify`` module implements a Python object API for XML.
|
7 |
+
It is based on `lxml.etree`.
|
8 |
+
"""
|
9 |
+
|
10 |
+
cimport cython
|
11 |
+
|
12 |
+
from lxml.includes.etreepublic cimport _Document, _Element, ElementBase, ElementClassLookup
|
13 |
+
from lxml.includes.etreepublic cimport elementFactory, import_lxml__etree, textOf, pyunicode
|
14 |
+
from lxml.includes.tree cimport const_xmlChar, _xcstr
|
15 |
+
from lxml cimport python
|
16 |
+
from lxml.includes cimport tree
|
17 |
+
|
18 |
+
cimport lxml.includes.etreepublic as cetree
|
19 |
+
cimport libc.string as cstring_h # not to be confused with stdlib 'string'
|
20 |
+
from libc.string cimport const_char
|
21 |
+
|
22 |
+
__all__ = ['BoolElement', 'DataElement', 'E', 'Element', 'ElementMaker',
|
23 |
+
'FloatElement', 'IntElement', 'NoneElement',
|
24 |
+
'NumberElement', 'ObjectPath', 'ObjectifiedDataElement',
|
25 |
+
'ObjectifiedElement', 'ObjectifyElementClassLookup',
|
26 |
+
'PYTYPE_ATTRIBUTE', 'PyType', 'StringElement', 'SubElement',
|
27 |
+
'XML', 'annotate', 'deannotate', 'dump', 'enable_recursive_str',
|
28 |
+
'fromstring', 'getRegisteredTypes', 'makeparser', 'parse',
|
29 |
+
'pyannotate', 'pytypename', 'set_default_parser',
|
30 |
+
'set_pytype_attribute_tag', 'xsiannotate']
|
31 |
+
|
32 |
+
cdef object etree
|
33 |
+
from lxml import etree
|
34 |
+
# initialize C-API of lxml.etree
|
35 |
+
import_lxml__etree()
|
36 |
+
|
37 |
+
__version__ = etree.__version__
|
38 |
+
|
39 |
+
cdef object _float_is_inf, _float_is_nan
|
40 |
+
from math import isinf as _float_is_inf, isnan as _float_is_nan
|
41 |
+
|
42 |
+
cdef object re
|
43 |
+
import re
|
44 |
+
|
45 |
+
cdef tuple IGNORABLE_ERRORS = (ValueError, TypeError)
|
46 |
+
cdef object is_special_method = re.compile('__.*__$').match
|
47 |
+
|
48 |
+
|
49 |
+
cdef object _typename(object t):
|
50 |
+
cdef const_char* c_name
|
51 |
+
c_name = python._fqtypename(t)
|
52 |
+
s = cstring_h.strrchr(c_name, c'.')
|
53 |
+
if s is not NULL:
|
54 |
+
c_name = s + 1
|
55 |
+
return pyunicode(<const_xmlChar*>c_name)
|
56 |
+
|
57 |
+
|
58 |
+
# namespace/name for "pytype" hint attribute
|
59 |
+
cdef object PYTYPE_NAMESPACE
|
60 |
+
cdef bytes PYTYPE_NAMESPACE_UTF8
|
61 |
+
cdef const_xmlChar* _PYTYPE_NAMESPACE
|
62 |
+
|
63 |
+
cdef object PYTYPE_ATTRIBUTE_NAME
|
64 |
+
cdef bytes PYTYPE_ATTRIBUTE_NAME_UTF8
|
65 |
+
cdef const_xmlChar* _PYTYPE_ATTRIBUTE_NAME
|
66 |
+
|
67 |
+
PYTYPE_ATTRIBUTE = None
|
68 |
+
|
69 |
+
cdef unicode TREE_PYTYPE_NAME = "TREE"
|
70 |
+
|
71 |
+
cdef tuple _unicodeAndUtf8(s):
|
72 |
+
return s, python.PyUnicode_AsUTF8String(s)
|
73 |
+
|
74 |
+
def set_pytype_attribute_tag(attribute_tag=None):
|
75 |
+
"""set_pytype_attribute_tag(attribute_tag=None)
|
76 |
+
Change name and namespace of the XML attribute that holds Python type
|
77 |
+
information.
|
78 |
+
|
79 |
+
Do not use this unless you know what you are doing.
|
80 |
+
|
81 |
+
Reset by calling without argument.
|
82 |
+
|
83 |
+
Default: "{http://codespeak.net/lxml/objectify/pytype}pytype"
|
84 |
+
"""
|
85 |
+
global PYTYPE_ATTRIBUTE, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME
|
86 |
+
global PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8
|
87 |
+
global PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8
|
88 |
+
if attribute_tag is None:
|
89 |
+
PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8 = \
|
90 |
+
_unicodeAndUtf8("http://codespeak.net/lxml/objectify/pytype")
|
91 |
+
PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8 = \
|
92 |
+
_unicodeAndUtf8("pytype")
|
93 |
+
else:
|
94 |
+
PYTYPE_NAMESPACE_UTF8, PYTYPE_ATTRIBUTE_NAME_UTF8 = \
|
95 |
+
cetree.getNsTag(attribute_tag)
|
96 |
+
PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8.decode('utf8')
|
97 |
+
PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8.decode('utf8')
|
98 |
+
|
99 |
+
_PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8
|
100 |
+
_PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8
|
101 |
+
PYTYPE_ATTRIBUTE = cetree.namespacedNameFromNsName(
|
102 |
+
_PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
103 |
+
|
104 |
+
set_pytype_attribute_tag()
|
105 |
+
|
106 |
+
|
107 |
+
# namespaces for XML Schema
|
108 |
+
cdef object XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8
|
109 |
+
XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8 = \
|
110 |
+
_unicodeAndUtf8("http://www.w3.org/2001/XMLSchema")
|
111 |
+
cdef const_xmlChar* _XML_SCHEMA_NS = _xcstr(XML_SCHEMA_NS_UTF8)
|
112 |
+
|
113 |
+
cdef object XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8
|
114 |
+
XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8 = \
|
115 |
+
_unicodeAndUtf8("http://www.w3.org/2001/XMLSchema-instance")
|
116 |
+
cdef const_xmlChar* _XML_SCHEMA_INSTANCE_NS = _xcstr(XML_SCHEMA_INSTANCE_NS_UTF8)
|
117 |
+
|
118 |
+
cdef object XML_SCHEMA_INSTANCE_NIL_ATTR = "{%s}nil" % XML_SCHEMA_INSTANCE_NS
|
119 |
+
cdef object XML_SCHEMA_INSTANCE_TYPE_ATTR = "{%s}type" % XML_SCHEMA_INSTANCE_NS
|
120 |
+
|
121 |
+
|
122 |
+
################################################################################
|
123 |
+
# Element class for the main API
|
124 |
+
|
125 |
+
cdef class ObjectifiedElement(ElementBase):
|
126 |
+
"""Main XML Element class.
|
127 |
+
|
128 |
+
Element children are accessed as object attributes. Multiple children
|
129 |
+
with the same name are available through a list index. Example::
|
130 |
+
|
131 |
+
>>> root = XML("<root><c1><c2>0</c2><c2>1</c2></c1></root>")
|
132 |
+
>>> second_c2 = root.c1.c2[1]
|
133 |
+
>>> print(second_c2.text)
|
134 |
+
1
|
135 |
+
|
136 |
+
Note that you cannot (and must not) instantiate this class or its
|
137 |
+
subclasses.
|
138 |
+
"""
|
139 |
+
def __iter__(self):
|
140 |
+
"""Iterate over self and all siblings with the same tag.
|
141 |
+
"""
|
142 |
+
parent = self.getparent()
|
143 |
+
if parent is None:
|
144 |
+
return iter([self])
|
145 |
+
return etree.ElementChildIterator(parent, tag=self.tag)
|
146 |
+
|
147 |
+
def __str__(self):
|
148 |
+
if __RECURSIVE_STR:
|
149 |
+
return _dump(self, 0)
|
150 |
+
else:
|
151 |
+
return textOf(self._c_node) or ''
|
152 |
+
|
153 |
+
# pickle support for objectified Element
|
154 |
+
def __reduce__(self):
|
155 |
+
return fromstring, (etree.tostring(self),)
|
156 |
+
|
157 |
+
@property
|
158 |
+
def text(self):
|
159 |
+
return textOf(self._c_node)
|
160 |
+
|
161 |
+
@property
|
162 |
+
def __dict__(self):
|
163 |
+
"""A fake implementation for __dict__ to support dir() etc.
|
164 |
+
|
165 |
+
Note that this only considers the first child with a given name.
|
166 |
+
"""
|
167 |
+
cdef _Element child
|
168 |
+
cdef dict children
|
169 |
+
c_ns = tree._getNs(self._c_node)
|
170 |
+
tag = "{%s}*" % pyunicode(c_ns) if c_ns is not NULL else None
|
171 |
+
children = {}
|
172 |
+
for child in etree.ElementChildIterator(self, tag=tag):
|
173 |
+
if c_ns is NULL and tree._getNs(child._c_node) is not NULL:
|
174 |
+
continue
|
175 |
+
name = pyunicode(child._c_node.name)
|
176 |
+
if name not in children:
|
177 |
+
children[name] = child
|
178 |
+
return children
|
179 |
+
|
180 |
+
def __len__(self):
|
181 |
+
"""Count self and siblings with the same tag.
|
182 |
+
"""
|
183 |
+
return _countSiblings(self._c_node)
|
184 |
+
|
185 |
+
def countchildren(self):
|
186 |
+
"""countchildren(self)
|
187 |
+
|
188 |
+
Return the number of children of this element, regardless of their
|
189 |
+
name.
|
190 |
+
"""
|
191 |
+
# copied from etree
|
192 |
+
cdef Py_ssize_t c
|
193 |
+
cdef tree.xmlNode* c_node
|
194 |
+
c = 0
|
195 |
+
c_node = self._c_node.children
|
196 |
+
while c_node is not NULL:
|
197 |
+
if tree._isElement(c_node):
|
198 |
+
c += 1
|
199 |
+
c_node = c_node.next
|
200 |
+
return c
|
201 |
+
|
202 |
+
def getchildren(self):
|
203 |
+
"""getchildren(self)
|
204 |
+
|
205 |
+
Returns a sequence of all direct children. The elements are
|
206 |
+
returned in document order.
|
207 |
+
"""
|
208 |
+
cdef tree.xmlNode* c_node
|
209 |
+
result = []
|
210 |
+
c_node = self._c_node.children
|
211 |
+
while c_node is not NULL:
|
212 |
+
if tree._isElement(c_node):
|
213 |
+
result.append(cetree.elementFactory(self._doc, c_node))
|
214 |
+
c_node = c_node.next
|
215 |
+
return result
|
216 |
+
|
217 |
+
def __getattr__(self, tag):
|
218 |
+
"""Return the (first) child with the given tag name. If no namespace
|
219 |
+
is provided, the child will be looked up in the same one as self.
|
220 |
+
"""
|
221 |
+
return _lookupChildOrRaise(self, tag)
|
222 |
+
|
223 |
+
def __setattr__(self, tag, value):
|
224 |
+
"""Set the value of the (first) child with the given tag name. If no
|
225 |
+
namespace is provided, the child will be looked up in the same one as
|
226 |
+
self.
|
227 |
+
"""
|
228 |
+
cdef _Element element
|
229 |
+
# properties are looked up /after/ __setattr__, so we must emulate them
|
230 |
+
if tag == 'text' or tag == 'pyval':
|
231 |
+
# read-only !
|
232 |
+
raise TypeError, f"attribute '{tag}' of '{_typename(self)}' objects is not writable"
|
233 |
+
elif tag == 'tail':
|
234 |
+
cetree.setTailText(self._c_node, value)
|
235 |
+
return
|
236 |
+
elif tag == 'tag':
|
237 |
+
ElementBase.tag.__set__(self, value)
|
238 |
+
return
|
239 |
+
elif tag == 'base':
|
240 |
+
ElementBase.base.__set__(self, value)
|
241 |
+
return
|
242 |
+
tag = _buildChildTag(self, tag)
|
243 |
+
element = _lookupChild(self, tag)
|
244 |
+
if element is None:
|
245 |
+
_appendValue(self, tag, value)
|
246 |
+
else:
|
247 |
+
_replaceElement(element, value)
|
248 |
+
|
249 |
+
def __delattr__(self, tag):
|
250 |
+
child = _lookupChildOrRaise(self, tag)
|
251 |
+
self.remove(child)
|
252 |
+
|
253 |
+
def addattr(self, tag, value):
|
254 |
+
"""addattr(self, tag, value)
|
255 |
+
|
256 |
+
Add a child value to the element.
|
257 |
+
|
258 |
+
As opposed to append(), it sets a data value, not an element.
|
259 |
+
"""
|
260 |
+
_appendValue(self, _buildChildTag(self, tag), value)
|
261 |
+
|
262 |
+
def __getitem__(self, key):
|
263 |
+
"""Return a sibling, counting from the first child of the parent. The
|
264 |
+
method behaves like both a dict and a sequence.
|
265 |
+
|
266 |
+
* If argument is an integer, returns the sibling at that position.
|
267 |
+
|
268 |
+
* If argument is a string, does the same as getattr(). This can be
|
269 |
+
used to provide namespaces for element lookup, or to look up
|
270 |
+
children with special names (``text`` etc.).
|
271 |
+
|
272 |
+
* If argument is a slice object, returns the matching slice.
|
273 |
+
"""
|
274 |
+
cdef tree.xmlNode* c_self_node
|
275 |
+
cdef tree.xmlNode* c_parent
|
276 |
+
cdef tree.xmlNode* c_node
|
277 |
+
cdef Py_ssize_t c_index
|
278 |
+
if python._isString(key):
|
279 |
+
return _lookupChildOrRaise(self, key)
|
280 |
+
elif isinstance(key, slice):
|
281 |
+
return list(self)[key]
|
282 |
+
# normal item access
|
283 |
+
c_index = key # raises TypeError if necessary
|
284 |
+
c_self_node = self._c_node
|
285 |
+
c_parent = c_self_node.parent
|
286 |
+
if c_parent is NULL:
|
287 |
+
if c_index == 0 or c_index == -1:
|
288 |
+
return self
|
289 |
+
raise IndexError, unicode(key)
|
290 |
+
if c_index < 0:
|
291 |
+
c_node = c_parent.last
|
292 |
+
else:
|
293 |
+
c_node = c_parent.children
|
294 |
+
c_node = _findFollowingSibling(
|
295 |
+
c_node, tree._getNs(c_self_node), c_self_node.name, c_index)
|
296 |
+
if c_node is NULL:
|
297 |
+
raise IndexError, unicode(key)
|
298 |
+
return elementFactory(self._doc, c_node)
|
299 |
+
|
300 |
+
def __setitem__(self, key, value):
|
301 |
+
"""Set the value of a sibling, counting from the first child of the
|
302 |
+
parent. Implements key assignment, item assignment and slice
|
303 |
+
assignment.
|
304 |
+
|
305 |
+
* If argument is an integer, sets the sibling at that position.
|
306 |
+
|
307 |
+
* If argument is a string, does the same as setattr(). This is used
|
308 |
+
to provide namespaces for element lookup.
|
309 |
+
|
310 |
+
* If argument is a sequence (list, tuple, etc.), assign the contained
|
311 |
+
items to the siblings.
|
312 |
+
"""
|
313 |
+
cdef _Element element
|
314 |
+
cdef tree.xmlNode* c_node
|
315 |
+
if python._isString(key):
|
316 |
+
key = _buildChildTag(self, key)
|
317 |
+
element = _lookupChild(self, key)
|
318 |
+
if element is None:
|
319 |
+
_appendValue(self, key, value)
|
320 |
+
else:
|
321 |
+
_replaceElement(element, value)
|
322 |
+
return
|
323 |
+
|
324 |
+
if self._c_node.parent is NULL:
|
325 |
+
# the 'root[i] = ...' case
|
326 |
+
raise TypeError, "assignment to root element is invalid"
|
327 |
+
|
328 |
+
if isinstance(key, slice):
|
329 |
+
# slice assignment
|
330 |
+
_setSlice(key, self, value)
|
331 |
+
else:
|
332 |
+
# normal index assignment
|
333 |
+
if key < 0:
|
334 |
+
c_node = self._c_node.parent.last
|
335 |
+
else:
|
336 |
+
c_node = self._c_node.parent.children
|
337 |
+
c_node = _findFollowingSibling(
|
338 |
+
c_node, tree._getNs(self._c_node), self._c_node.name, key)
|
339 |
+
if c_node is NULL:
|
340 |
+
raise IndexError, unicode(key)
|
341 |
+
element = elementFactory(self._doc, c_node)
|
342 |
+
_replaceElement(element, value)
|
343 |
+
|
344 |
+
def __delitem__(self, key):
|
345 |
+
parent = self.getparent()
|
346 |
+
if parent is None:
|
347 |
+
raise TypeError, "deleting items not supported by root element"
|
348 |
+
if isinstance(key, slice):
|
349 |
+
# slice deletion
|
350 |
+
del_items = list(self)[key]
|
351 |
+
remove = parent.remove
|
352 |
+
for el in del_items:
|
353 |
+
remove(el)
|
354 |
+
else:
|
355 |
+
# normal index deletion
|
356 |
+
sibling = self.__getitem__(key)
|
357 |
+
parent.remove(sibling)
|
358 |
+
|
359 |
+
def descendantpaths(self, prefix=None):
|
360 |
+
"""descendantpaths(self, prefix=None)
|
361 |
+
|
362 |
+
Returns a list of object path expressions for all descendants.
|
363 |
+
"""
|
364 |
+
if prefix is not None and not python._isString(prefix):
|
365 |
+
prefix = '.'.join(prefix)
|
366 |
+
return _build_descendant_paths(self._c_node, prefix)
|
367 |
+
|
368 |
+
|
369 |
+
cdef inline bint _tagMatches(tree.xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name):
|
370 |
+
if c_node.name != c_name:
|
371 |
+
return 0
|
372 |
+
if c_href == NULL:
|
373 |
+
return 1
|
374 |
+
c_node_href = tree._getNs(c_node)
|
375 |
+
if c_node_href == NULL:
|
376 |
+
return c_href[0] == c'\0'
|
377 |
+
return tree.xmlStrcmp(c_node_href, c_href) == 0
|
378 |
+
|
379 |
+
|
380 |
+
cdef Py_ssize_t _countSiblings(tree.xmlNode* c_start_node):
|
381 |
+
cdef tree.xmlNode* c_node
|
382 |
+
cdef Py_ssize_t count
|
383 |
+
c_tag = c_start_node.name
|
384 |
+
c_href = tree._getNs(c_start_node)
|
385 |
+
count = 1
|
386 |
+
c_node = c_start_node.next
|
387 |
+
while c_node is not NULL:
|
388 |
+
if c_node.type == tree.XML_ELEMENT_NODE and \
|
389 |
+
_tagMatches(c_node, c_href, c_tag):
|
390 |
+
count += 1
|
391 |
+
c_node = c_node.next
|
392 |
+
c_node = c_start_node.prev
|
393 |
+
while c_node is not NULL:
|
394 |
+
if c_node.type == tree.XML_ELEMENT_NODE and \
|
395 |
+
_tagMatches(c_node, c_href, c_tag):
|
396 |
+
count += 1
|
397 |
+
c_node = c_node.prev
|
398 |
+
return count
|
399 |
+
|
400 |
+
cdef tree.xmlNode* _findFollowingSibling(tree.xmlNode* c_node,
|
401 |
+
const_xmlChar* href, const_xmlChar* name,
|
402 |
+
Py_ssize_t index):
|
403 |
+
cdef tree.xmlNode* (*next)(tree.xmlNode*)
|
404 |
+
if index >= 0:
|
405 |
+
next = cetree.nextElement
|
406 |
+
else:
|
407 |
+
index = -1 - index
|
408 |
+
next = cetree.previousElement
|
409 |
+
while c_node is not NULL:
|
410 |
+
if c_node.type == tree.XML_ELEMENT_NODE and \
|
411 |
+
_tagMatches(c_node, href, name):
|
412 |
+
index = index - 1
|
413 |
+
if index < 0:
|
414 |
+
return c_node
|
415 |
+
c_node = next(c_node)
|
416 |
+
return NULL
|
417 |
+
|
418 |
+
cdef object _lookupChild(_Element parent, tag):
|
419 |
+
cdef tree.xmlNode* c_result
|
420 |
+
cdef tree.xmlNode* c_node
|
421 |
+
c_node = parent._c_node
|
422 |
+
ns, tag = cetree.getNsTagWithEmptyNs(tag)
|
423 |
+
c_tag = tree.xmlDictExists(
|
424 |
+
c_node.doc.dict, _xcstr(tag), python.PyBytes_GET_SIZE(tag))
|
425 |
+
if c_tag is NULL:
|
426 |
+
return None # not in the hash map => not in the tree
|
427 |
+
if ns is None:
|
428 |
+
# either inherit ns from parent or use empty (i.e. no) namespace
|
429 |
+
c_href = tree._getNs(c_node) or <const_xmlChar*>''
|
430 |
+
else:
|
431 |
+
c_href = _xcstr(ns)
|
432 |
+
c_result = _findFollowingSibling(c_node.children, c_href, c_tag, 0)
|
433 |
+
if c_result is NULL:
|
434 |
+
return None
|
435 |
+
return elementFactory(parent._doc, c_result)
|
436 |
+
|
437 |
+
cdef object _lookupChildOrRaise(_Element parent, tag):
|
438 |
+
element = _lookupChild(parent, tag)
|
439 |
+
if element is None:
|
440 |
+
raise AttributeError, "no such child: " + _buildChildTag(parent, tag)
|
441 |
+
return element
|
442 |
+
|
443 |
+
cdef object _buildChildTag(_Element parent, tag):
|
444 |
+
ns, tag = cetree.getNsTag(tag)
|
445 |
+
c_tag = _xcstr(tag)
|
446 |
+
c_href = tree._getNs(parent._c_node) if ns is None else _xcstr(ns)
|
447 |
+
return cetree.namespacedNameFromNsName(c_href, c_tag)
|
448 |
+
|
449 |
+
cdef _replaceElement(_Element element, value):
|
450 |
+
cdef _Element new_element
|
451 |
+
if isinstance(value, _Element):
|
452 |
+
# deep copy the new element
|
453 |
+
new_element = cetree.deepcopyNodeToDocument(
|
454 |
+
element._doc, (<_Element>value)._c_node)
|
455 |
+
new_element.tag = element.tag
|
456 |
+
elif isinstance(value, (list, tuple)):
|
457 |
+
element[:] = value
|
458 |
+
return
|
459 |
+
else:
|
460 |
+
new_element = element.makeelement(element.tag)
|
461 |
+
_setElementValue(new_element, value)
|
462 |
+
element.getparent().replace(element, new_element)
|
463 |
+
|
464 |
+
cdef _appendValue(_Element parent, tag, value):
|
465 |
+
cdef _Element new_element
|
466 |
+
if isinstance(value, _Element):
|
467 |
+
# deep copy the new element
|
468 |
+
new_element = cetree.deepcopyNodeToDocument(
|
469 |
+
parent._doc, (<_Element>value)._c_node)
|
470 |
+
new_element.tag = tag
|
471 |
+
cetree.appendChildToElement(parent, new_element)
|
472 |
+
elif isinstance(value, (list, tuple)):
|
473 |
+
for item in value:
|
474 |
+
_appendValue(parent, tag, item)
|
475 |
+
else:
|
476 |
+
new_element = cetree.makeElement(
|
477 |
+
tag, parent._doc, None, None, None, None, None)
|
478 |
+
_setElementValue(new_element, value)
|
479 |
+
cetree.appendChildToElement(parent, new_element)
|
480 |
+
|
481 |
+
cdef _setElementValue(_Element element, value):
|
482 |
+
if value is None:
|
483 |
+
cetree.setAttributeValue(
|
484 |
+
element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true")
|
485 |
+
elif isinstance(value, _Element):
|
486 |
+
_replaceElement(element, value)
|
487 |
+
return
|
488 |
+
else:
|
489 |
+
cetree.delAttributeFromNsName(
|
490 |
+
element._c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil")
|
491 |
+
if python._isString(value):
|
492 |
+
pytype_name = "str"
|
493 |
+
py_type = <PyType>_PYTYPE_DICT.get(pytype_name)
|
494 |
+
else:
|
495 |
+
pytype_name = _typename(value)
|
496 |
+
py_type = <PyType>_PYTYPE_DICT.get(pytype_name)
|
497 |
+
if py_type is not None:
|
498 |
+
value = py_type.stringify(value)
|
499 |
+
else:
|
500 |
+
value = unicode(value)
|
501 |
+
if py_type is not None:
|
502 |
+
cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name)
|
503 |
+
else:
|
504 |
+
cetree.delAttributeFromNsName(
|
505 |
+
element._c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
506 |
+
cetree.setNodeText(element._c_node, value)
|
507 |
+
|
508 |
+
cdef _setSlice(sliceobject, _Element target, items):
|
509 |
+
cdef _Element parent
|
510 |
+
cdef tree.xmlNode* c_node
|
511 |
+
cdef Py_ssize_t c_step, c_start, pos
|
512 |
+
# collect existing slice
|
513 |
+
if (<slice>sliceobject).step is None:
|
514 |
+
c_step = 1
|
515 |
+
else:
|
516 |
+
c_step = (<slice>sliceobject).step
|
517 |
+
if c_step == 0:
|
518 |
+
raise ValueError, "Invalid slice"
|
519 |
+
cdef list del_items = target[sliceobject]
|
520 |
+
|
521 |
+
# collect new values
|
522 |
+
new_items = []
|
523 |
+
tag = target.tag
|
524 |
+
for item in items:
|
525 |
+
if isinstance(item, _Element):
|
526 |
+
# deep copy the new element
|
527 |
+
new_element = cetree.deepcopyNodeToDocument(
|
528 |
+
target._doc, (<_Element>item)._c_node)
|
529 |
+
new_element.tag = tag
|
530 |
+
else:
|
531 |
+
new_element = cetree.makeElement(
|
532 |
+
tag, target._doc, None, None, None, None, None)
|
533 |
+
_setElementValue(new_element, item)
|
534 |
+
new_items.append(new_element)
|
535 |
+
|
536 |
+
# sanity check - raise what a list would raise
|
537 |
+
if c_step != 1 and len(del_items) != len(new_items):
|
538 |
+
raise ValueError, \
|
539 |
+
f"attempt to assign sequence of size {len(new_items)} to extended slice of size {len(del_items)}"
|
540 |
+
|
541 |
+
# replace existing items
|
542 |
+
pos = 0
|
543 |
+
parent = target.getparent()
|
544 |
+
replace = parent.replace
|
545 |
+
while pos < len(new_items) and pos < len(del_items):
|
546 |
+
replace(del_items[pos], new_items[pos])
|
547 |
+
pos += 1
|
548 |
+
# remove leftover items
|
549 |
+
if pos < len(del_items):
|
550 |
+
remove = parent.remove
|
551 |
+
while pos < len(del_items):
|
552 |
+
remove(del_items[pos])
|
553 |
+
pos += 1
|
554 |
+
# append remaining new items
|
555 |
+
if pos < len(new_items):
|
556 |
+
# the sanity check above guarantees (step == 1)
|
557 |
+
if pos > 0:
|
558 |
+
item = new_items[pos-1]
|
559 |
+
else:
|
560 |
+
if (<slice>sliceobject).start > 0:
|
561 |
+
c_node = parent._c_node.children
|
562 |
+
else:
|
563 |
+
c_node = parent._c_node.last
|
564 |
+
c_node = _findFollowingSibling(
|
565 |
+
c_node, tree._getNs(target._c_node), target._c_node.name,
|
566 |
+
(<slice>sliceobject).start - 1)
|
567 |
+
if c_node is NULL:
|
568 |
+
while pos < len(new_items):
|
569 |
+
cetree.appendChildToElement(parent, new_items[pos])
|
570 |
+
pos += 1
|
571 |
+
return
|
572 |
+
item = cetree.elementFactory(parent._doc, c_node)
|
573 |
+
while pos < len(new_items):
|
574 |
+
add = item.addnext
|
575 |
+
item = new_items[pos]
|
576 |
+
add(item)
|
577 |
+
pos += 1
|
578 |
+
|
579 |
+
################################################################################
|
580 |
+
# Data type support in subclasses
|
581 |
+
|
582 |
+
cdef class ObjectifiedDataElement(ObjectifiedElement):
|
583 |
+
"""This is the base class for all data type Elements. Subclasses should
|
584 |
+
override the 'pyval' property and possibly the __str__ method.
|
585 |
+
"""
|
586 |
+
@property
|
587 |
+
def pyval(self):
|
588 |
+
return textOf(self._c_node)
|
589 |
+
|
590 |
+
def __str__(self):
|
591 |
+
return textOf(self._c_node) or ''
|
592 |
+
|
593 |
+
def __repr__(self):
|
594 |
+
return textOf(self._c_node) or ''
|
595 |
+
|
596 |
+
def _setText(self, s):
|
597 |
+
"""For use in subclasses only. Don't use unless you know what you are
|
598 |
+
doing.
|
599 |
+
"""
|
600 |
+
cetree.setNodeText(self._c_node, s)
|
601 |
+
|
602 |
+
|
603 |
+
cdef class NumberElement(ObjectifiedDataElement):
|
604 |
+
cdef object _parse_value
|
605 |
+
|
606 |
+
def _setValueParser(self, function):
|
607 |
+
"""Set the function that parses the Python value from a string.
|
608 |
+
|
609 |
+
Do not use this unless you know what you are doing.
|
610 |
+
"""
|
611 |
+
self._parse_value = function
|
612 |
+
|
613 |
+
@property
|
614 |
+
def pyval(self):
|
615 |
+
return _parseNumber(self)
|
616 |
+
|
617 |
+
def __int__(self):
|
618 |
+
return int(_parseNumber(self))
|
619 |
+
|
620 |
+
def __float__(self):
|
621 |
+
return float(_parseNumber(self))
|
622 |
+
|
623 |
+
def __complex__(self):
|
624 |
+
return complex(_parseNumber(self))
|
625 |
+
|
626 |
+
def __str__(self):
|
627 |
+
return unicode(_parseNumber(self))
|
628 |
+
|
629 |
+
def __repr__(self):
|
630 |
+
return repr(_parseNumber(self))
|
631 |
+
|
632 |
+
def __oct__(self):
|
633 |
+
return oct(_parseNumber(self))
|
634 |
+
|
635 |
+
def __hex__(self):
|
636 |
+
return hex(_parseNumber(self))
|
637 |
+
|
638 |
+
def __richcmp__(self, other, int op):
|
639 |
+
return _richcmpPyvals(self, other, op)
|
640 |
+
|
641 |
+
def __hash__(self):
|
642 |
+
return hash(_parseNumber(self))
|
643 |
+
|
644 |
+
def __add__(self, other):
|
645 |
+
return _numericValueOf(self) + _numericValueOf(other)
|
646 |
+
|
647 |
+
def __radd__(self, other):
|
648 |
+
return _numericValueOf(other) + _numericValueOf(self)
|
649 |
+
|
650 |
+
def __sub__(self, other):
|
651 |
+
return _numericValueOf(self) - _numericValueOf(other)
|
652 |
+
|
653 |
+
def __rsub__(self, other):
|
654 |
+
return _numericValueOf(other) - _numericValueOf(self)
|
655 |
+
|
656 |
+
def __mul__(self, other):
|
657 |
+
return _numericValueOf(self) * _numericValueOf(other)
|
658 |
+
|
659 |
+
def __rmul__(self, other):
|
660 |
+
return _numericValueOf(other) * _numericValueOf(self)
|
661 |
+
|
662 |
+
def __div__(self, other):
|
663 |
+
return _numericValueOf(self) / _numericValueOf(other)
|
664 |
+
|
665 |
+
def __rdiv__(self, other):
|
666 |
+
return _numericValueOf(other) / _numericValueOf(self)
|
667 |
+
|
668 |
+
def __truediv__(self, other):
|
669 |
+
return _numericValueOf(self) / _numericValueOf(other)
|
670 |
+
|
671 |
+
def __rtruediv__(self, other):
|
672 |
+
return _numericValueOf(other) / _numericValueOf(self)
|
673 |
+
|
674 |
+
def __floordiv__(self, other):
|
675 |
+
return _numericValueOf(self) // _numericValueOf(other)
|
676 |
+
|
677 |
+
def __rfloordiv__(self, other):
|
678 |
+
return _numericValueOf(other) // _numericValueOf(self)
|
679 |
+
|
680 |
+
def __mod__(self, other):
|
681 |
+
return _numericValueOf(self) % _numericValueOf(other)
|
682 |
+
|
683 |
+
def __rmod__(self, other):
|
684 |
+
return _numericValueOf(other) % _numericValueOf(self)
|
685 |
+
|
686 |
+
def __divmod__(self, other):
|
687 |
+
return divmod(_numericValueOf(self), _numericValueOf(other))
|
688 |
+
|
689 |
+
def __rdivmod__(self, other):
|
690 |
+
return divmod(_numericValueOf(other), _numericValueOf(self))
|
691 |
+
|
692 |
+
def __pow__(self, other, modulo):
|
693 |
+
if modulo is None:
|
694 |
+
return _numericValueOf(self) ** _numericValueOf(other)
|
695 |
+
else:
|
696 |
+
return pow(_numericValueOf(self), _numericValueOf(other), modulo)
|
697 |
+
|
698 |
+
def __rpow__(self, other, modulo):
|
699 |
+
if modulo is None:
|
700 |
+
return _numericValueOf(other) ** _numericValueOf(self)
|
701 |
+
else:
|
702 |
+
return pow(_numericValueOf(other), _numericValueOf(self), modulo)
|
703 |
+
|
704 |
+
def __neg__(self):
|
705 |
+
return - _numericValueOf(self)
|
706 |
+
|
707 |
+
def __pos__(self):
|
708 |
+
return + _numericValueOf(self)
|
709 |
+
|
710 |
+
def __abs__(self):
|
711 |
+
return abs( _numericValueOf(self) )
|
712 |
+
|
713 |
+
def __bool__(self):
|
714 |
+
return bool(_numericValueOf(self))
|
715 |
+
|
716 |
+
def __invert__(self):
|
717 |
+
return ~ _numericValueOf(self)
|
718 |
+
|
719 |
+
def __lshift__(self, other):
|
720 |
+
return _numericValueOf(self) << _numericValueOf(other)
|
721 |
+
|
722 |
+
def __rlshift__(self, other):
|
723 |
+
return _numericValueOf(other) << _numericValueOf(self)
|
724 |
+
|
725 |
+
def __rshift__(self, other):
|
726 |
+
return _numericValueOf(self) >> _numericValueOf(other)
|
727 |
+
|
728 |
+
def __rrshift__(self, other):
|
729 |
+
return _numericValueOf(other) >> _numericValueOf(self)
|
730 |
+
|
731 |
+
def __and__(self, other):
|
732 |
+
return _numericValueOf(self) & _numericValueOf(other)
|
733 |
+
|
734 |
+
def __rand__(self, other):
|
735 |
+
return _numericValueOf(other) & _numericValueOf(self)
|
736 |
+
|
737 |
+
def __or__(self, other):
|
738 |
+
return _numericValueOf(self) | _numericValueOf(other)
|
739 |
+
|
740 |
+
def __ror__(self, other):
|
741 |
+
return _numericValueOf(other) | _numericValueOf(self)
|
742 |
+
|
743 |
+
def __xor__(self, other):
|
744 |
+
return _numericValueOf(self) ^ _numericValueOf(other)
|
745 |
+
|
746 |
+
def __rxor__(self, other):
|
747 |
+
return _numericValueOf(other) ^ _numericValueOf(self)
|
748 |
+
|
749 |
+
|
750 |
+
cdef class IntElement(NumberElement):
|
751 |
+
def _init(self):
|
752 |
+
self._parse_value = int
|
753 |
+
|
754 |
+
def __index__(self):
|
755 |
+
return int(_parseNumber(self))
|
756 |
+
|
757 |
+
|
758 |
+
cdef class FloatElement(NumberElement):
|
759 |
+
def _init(self):
|
760 |
+
self._parse_value = float
|
761 |
+
|
762 |
+
|
763 |
+
cdef class StringElement(ObjectifiedDataElement):
|
764 |
+
"""String data class.
|
765 |
+
|
766 |
+
Note that this class does *not* support the sequence protocol of strings:
|
767 |
+
len(), iter(), str_attr[0], str_attr[0:1], etc. are *not* supported.
|
768 |
+
Instead, use the .text attribute to get a 'real' string.
|
769 |
+
"""
|
770 |
+
@property
|
771 |
+
def pyval(self):
|
772 |
+
return textOf(self._c_node) or ''
|
773 |
+
|
774 |
+
def __repr__(self):
|
775 |
+
return repr(textOf(self._c_node) or '')
|
776 |
+
|
777 |
+
def strlen(self):
|
778 |
+
text = textOf(self._c_node)
|
779 |
+
if text is None:
|
780 |
+
return 0
|
781 |
+
else:
|
782 |
+
return len(text)
|
783 |
+
|
784 |
+
def __bool__(self):
|
785 |
+
return bool(textOf(self._c_node))
|
786 |
+
|
787 |
+
def __richcmp__(self, other, int op):
|
788 |
+
return _richcmpPyvals(self, other, op)
|
789 |
+
|
790 |
+
def __hash__(self):
|
791 |
+
return hash(textOf(self._c_node) or '')
|
792 |
+
|
793 |
+
def __add__(self, other):
|
794 |
+
text = _strValueOf(self)
|
795 |
+
other = _strValueOf(other)
|
796 |
+
return text + other
|
797 |
+
|
798 |
+
def __radd__(self, other):
|
799 |
+
text = _strValueOf(self)
|
800 |
+
other = _strValueOf(other)
|
801 |
+
return other + text
|
802 |
+
|
803 |
+
def __mul__(self, other):
|
804 |
+
if isinstance(self, StringElement):
|
805 |
+
return (textOf((<StringElement>self)._c_node) or '') * _numericValueOf(other)
|
806 |
+
elif isinstance(other, StringElement):
|
807 |
+
return _numericValueOf(self) * (textOf((<StringElement>other)._c_node) or '')
|
808 |
+
else:
|
809 |
+
return NotImplemented
|
810 |
+
|
811 |
+
def __rmul__(self, other):
|
812 |
+
return _numericValueOf(other) * (textOf((<StringElement>self)._c_node) or '')
|
813 |
+
|
814 |
+
def __mod__(self, other):
|
815 |
+
return (_strValueOf(self) or '') % other
|
816 |
+
|
817 |
+
def __int__(self):
|
818 |
+
return int(textOf(self._c_node))
|
819 |
+
|
820 |
+
def __float__(self):
|
821 |
+
return float(textOf(self._c_node))
|
822 |
+
|
823 |
+
def __complex__(self):
|
824 |
+
return complex(textOf(self._c_node))
|
825 |
+
|
826 |
+
|
827 |
+
cdef class NoneElement(ObjectifiedDataElement):
|
828 |
+
def __str__(self):
|
829 |
+
return "None"
|
830 |
+
|
831 |
+
def __repr__(self):
|
832 |
+
return "None"
|
833 |
+
|
834 |
+
def __bool__(self):
|
835 |
+
return False
|
836 |
+
|
837 |
+
def __richcmp__(self, other, int op):
|
838 |
+
if other is None or self is None:
|
839 |
+
return python.PyObject_RichCompare(None, None, op)
|
840 |
+
if isinstance(self, NoneElement):
|
841 |
+
return python.PyObject_RichCompare(None, other, op)
|
842 |
+
else:
|
843 |
+
return python.PyObject_RichCompare(self, None, op)
|
844 |
+
|
845 |
+
def __hash__(self):
|
846 |
+
return hash(None)
|
847 |
+
|
848 |
+
@property
|
849 |
+
def pyval(self):
|
850 |
+
return None
|
851 |
+
|
852 |
+
|
853 |
+
cdef class BoolElement(IntElement):
|
854 |
+
"""Boolean type base on string values: 'true' or 'false'.
|
855 |
+
|
856 |
+
Note that this inherits from IntElement to mimic the behaviour of
|
857 |
+
Python's bool type.
|
858 |
+
"""
|
859 |
+
def _init(self):
|
860 |
+
self._parse_value = _parseBool # wraps as Python callable
|
861 |
+
|
862 |
+
def __bool__(self):
|
863 |
+
return _parseBool(textOf(self._c_node))
|
864 |
+
|
865 |
+
def __int__(self):
|
866 |
+
return 0 + _parseBool(textOf(self._c_node))
|
867 |
+
|
868 |
+
def __float__(self):
|
869 |
+
return 0.0 + _parseBool(textOf(self._c_node))
|
870 |
+
|
871 |
+
def __richcmp__(self, other, int op):
|
872 |
+
return _richcmpPyvals(self, other, op)
|
873 |
+
|
874 |
+
def __hash__(self):
|
875 |
+
return hash(_parseBool(textOf(self._c_node)))
|
876 |
+
|
877 |
+
def __str__(self):
|
878 |
+
return unicode(_parseBool(textOf(self._c_node)))
|
879 |
+
|
880 |
+
def __repr__(self):
|
881 |
+
return repr(_parseBool(textOf(self._c_node)))
|
882 |
+
|
883 |
+
@property
|
884 |
+
def pyval(self):
|
885 |
+
return _parseBool(textOf(self._c_node))
|
886 |
+
|
887 |
+
|
888 |
+
cdef _checkBool(s):
|
889 |
+
cdef int value = -1
|
890 |
+
if s is not None:
|
891 |
+
value = __parseBoolAsInt(s)
|
892 |
+
if value == -1:
|
893 |
+
raise ValueError
|
894 |
+
|
895 |
+
|
896 |
+
cdef bint _parseBool(s) except -1:
|
897 |
+
cdef int value
|
898 |
+
if s is None:
|
899 |
+
return False
|
900 |
+
value = __parseBoolAsInt(s)
|
901 |
+
if value == -1:
|
902 |
+
raise ValueError, f"Invalid boolean value: '{s}'"
|
903 |
+
return value
|
904 |
+
|
905 |
+
|
906 |
+
cdef inline int __parseBoolAsInt(text) except -2:
|
907 |
+
if text == 'false':
|
908 |
+
return 0
|
909 |
+
elif text == 'true':
|
910 |
+
return 1
|
911 |
+
elif text == '0':
|
912 |
+
return 0
|
913 |
+
elif text == '1':
|
914 |
+
return 1
|
915 |
+
return -1
|
916 |
+
|
917 |
+
|
918 |
+
cdef object _parseNumber(NumberElement element):
|
919 |
+
return element._parse_value(textOf(element._c_node))
|
920 |
+
|
921 |
+
|
922 |
+
cdef enum NumberParserState:
|
923 |
+
NPS_SPACE_PRE = 0
|
924 |
+
NPS_SIGN = 1
|
925 |
+
NPS_DIGITS = 2
|
926 |
+
NPS_POINT_LEAD = 3
|
927 |
+
NPS_POINT = 4
|
928 |
+
NPS_FRACTION = 5
|
929 |
+
NPS_EXP = 6
|
930 |
+
NPS_EXP_SIGN = 7
|
931 |
+
NPS_DIGITS_EXP = 8
|
932 |
+
NPS_SPACE_TAIL = 9
|
933 |
+
NPS_INF1 = 20
|
934 |
+
NPS_INF2 = 21
|
935 |
+
NPS_INF3 = 22
|
936 |
+
NPS_NAN1 = 23
|
937 |
+
NPS_NAN2 = 24
|
938 |
+
NPS_NAN3 = 25
|
939 |
+
NPS_ERROR = 99
|
940 |
+
|
941 |
+
|
942 |
+
ctypedef fused bytes_unicode:
|
943 |
+
bytes
|
944 |
+
unicode
|
945 |
+
|
946 |
+
|
947 |
+
cdef _checkNumber(bytes_unicode s, bint allow_float):
|
948 |
+
cdef Py_UCS4 c
|
949 |
+
cdef NumberParserState state = NPS_SPACE_PRE
|
950 |
+
|
951 |
+
for c in s:
|
952 |
+
if c in '0123456789':
|
953 |
+
if state in (NPS_DIGITS, NPS_FRACTION, NPS_DIGITS_EXP):
|
954 |
+
pass
|
955 |
+
elif state in (NPS_SPACE_PRE, NPS_SIGN):
|
956 |
+
state = NPS_DIGITS
|
957 |
+
elif state in (NPS_POINT_LEAD, NPS_POINT):
|
958 |
+
state = NPS_FRACTION
|
959 |
+
elif state in (NPS_EXP, NPS_EXP_SIGN):
|
960 |
+
state = NPS_DIGITS_EXP
|
961 |
+
else:
|
962 |
+
state = NPS_ERROR
|
963 |
+
else:
|
964 |
+
if c == '.':
|
965 |
+
if state in (NPS_SPACE_PRE, NPS_SIGN):
|
966 |
+
state = NPS_POINT_LEAD
|
967 |
+
elif state == NPS_DIGITS:
|
968 |
+
state = NPS_POINT
|
969 |
+
else:
|
970 |
+
state = NPS_ERROR
|
971 |
+
if not allow_float:
|
972 |
+
state = NPS_ERROR
|
973 |
+
elif c in '-+':
|
974 |
+
if state == NPS_SPACE_PRE:
|
975 |
+
state = NPS_SIGN
|
976 |
+
elif state == NPS_EXP:
|
977 |
+
state = NPS_EXP_SIGN
|
978 |
+
else:
|
979 |
+
state = NPS_ERROR
|
980 |
+
elif c == 'E':
|
981 |
+
if state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION):
|
982 |
+
state = NPS_EXP
|
983 |
+
else:
|
984 |
+
state = NPS_ERROR
|
985 |
+
if not allow_float:
|
986 |
+
state = NPS_ERROR
|
987 |
+
# Allow INF and NaN. XMLSchema requires case, we don't, like Python.
|
988 |
+
elif c in 'iI':
|
989 |
+
state = NPS_INF1 if allow_float and state in (NPS_SPACE_PRE, NPS_SIGN) else NPS_ERROR
|
990 |
+
elif c in 'fF':
|
991 |
+
state = NPS_INF3 if state == NPS_INF2 else NPS_ERROR
|
992 |
+
elif c in 'aA':
|
993 |
+
state = NPS_NAN2 if state == NPS_NAN1 else NPS_ERROR
|
994 |
+
elif c in 'nN':
|
995 |
+
# Python also allows [+-]NaN, so let's accept that.
|
996 |
+
if state in (NPS_SPACE_PRE, NPS_SIGN):
|
997 |
+
state = NPS_NAN1 if allow_float else NPS_ERROR
|
998 |
+
elif state == NPS_NAN2:
|
999 |
+
state = NPS_NAN3
|
1000 |
+
elif state == NPS_INF1:
|
1001 |
+
state = NPS_INF2
|
1002 |
+
else:
|
1003 |
+
state = NPS_ERROR
|
1004 |
+
# Allow spaces around text values.
|
1005 |
+
else:
|
1006 |
+
if c.isspace() if (bytes_unicode is unicode) else c in b'\x09\x0a\x0b\x0c\x0d\x20':
|
1007 |
+
if state in (NPS_SPACE_PRE, NPS_SPACE_TAIL):
|
1008 |
+
pass
|
1009 |
+
elif state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3):
|
1010 |
+
state = NPS_SPACE_TAIL
|
1011 |
+
else:
|
1012 |
+
state = NPS_ERROR
|
1013 |
+
else:
|
1014 |
+
state = NPS_ERROR
|
1015 |
+
|
1016 |
+
if state == NPS_ERROR:
|
1017 |
+
break
|
1018 |
+
|
1019 |
+
if state not in (NPS_DIGITS, NPS_FRACTION, NPS_POINT, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3, NPS_SPACE_TAIL):
|
1020 |
+
raise ValueError
|
1021 |
+
|
1022 |
+
|
1023 |
+
cdef _checkInt(s):
|
1024 |
+
return _checkNumber(<unicode>s, allow_float=False)
|
1025 |
+
|
1026 |
+
|
1027 |
+
cdef _checkFloat(s):
|
1028 |
+
return _checkNumber(<unicode>s, allow_float=True)
|
1029 |
+
|
1030 |
+
|
1031 |
+
cdef object _strValueOf(obj):
|
1032 |
+
if python._isString(obj):
|
1033 |
+
return obj
|
1034 |
+
if isinstance(obj, _Element):
|
1035 |
+
return textOf((<_Element>obj)._c_node) or ''
|
1036 |
+
if obj is None:
|
1037 |
+
return ''
|
1038 |
+
return unicode(obj)
|
1039 |
+
|
1040 |
+
|
1041 |
+
cdef object _numericValueOf(obj):
|
1042 |
+
if isinstance(obj, NumberElement):
|
1043 |
+
return _parseNumber(<NumberElement>obj)
|
1044 |
+
try:
|
1045 |
+
# not always numeric, but Python will raise the right exception
|
1046 |
+
return obj.pyval
|
1047 |
+
except AttributeError:
|
1048 |
+
pass
|
1049 |
+
return obj
|
1050 |
+
|
1051 |
+
|
1052 |
+
cdef _richcmpPyvals(left, right, int op):
|
1053 |
+
left = getattr(left, 'pyval', left)
|
1054 |
+
right = getattr(right, 'pyval', right)
|
1055 |
+
return python.PyObject_RichCompare(left, right, op)
|
1056 |
+
|
1057 |
+
|
1058 |
+
################################################################################
|
1059 |
+
# Python type registry
|
1060 |
+
|
1061 |
+
cdef class PyType:
|
1062 |
+
"""PyType(self, name, type_check, type_class, stringify=None)
|
1063 |
+
User defined type.
|
1064 |
+
|
1065 |
+
Named type that contains a type check function, a type class that
|
1066 |
+
inherits from ObjectifiedDataElement and an optional "stringification"
|
1067 |
+
function. The type check must take a string as argument and raise
|
1068 |
+
ValueError or TypeError if it cannot handle the string value. It may be
|
1069 |
+
None in which case it is not considered for type guessing. For registered
|
1070 |
+
named types, the 'stringify' function (or unicode() if None) is used to
|
1071 |
+
convert a Python object with type name 'name' to the string representation
|
1072 |
+
stored in the XML tree.
|
1073 |
+
|
1074 |
+
Example::
|
1075 |
+
|
1076 |
+
PyType('int', int, MyIntClass).register()
|
1077 |
+
|
1078 |
+
Note that the order in which types are registered matters. The first
|
1079 |
+
matching type will be used.
|
1080 |
+
"""
|
1081 |
+
cdef readonly object name
|
1082 |
+
cdef readonly object type_check
|
1083 |
+
cdef readonly object stringify
|
1084 |
+
cdef object _type
|
1085 |
+
cdef list _schema_types
|
1086 |
+
def __init__(self, name, type_check, type_class, stringify=None):
|
1087 |
+
if isinstance(name, bytes):
|
1088 |
+
name = (<bytes>name).decode('ascii')
|
1089 |
+
elif not isinstance(name, unicode):
|
1090 |
+
raise TypeError, "Type name must be a string"
|
1091 |
+
if type_check is not None and not callable(type_check):
|
1092 |
+
raise TypeError, "Type check function must be callable (or None)"
|
1093 |
+
if name != TREE_PYTYPE_NAME and \
|
1094 |
+
not issubclass(type_class, ObjectifiedDataElement):
|
1095 |
+
raise TypeError, \
|
1096 |
+
"Data classes must inherit from ObjectifiedDataElement"
|
1097 |
+
self.name = name
|
1098 |
+
self._type = type_class
|
1099 |
+
self.type_check = type_check
|
1100 |
+
if stringify is None:
|
1101 |
+
stringify = unicode
|
1102 |
+
self.stringify = stringify
|
1103 |
+
self._schema_types = []
|
1104 |
+
|
1105 |
+
def __repr__(self):
|
1106 |
+
return "PyType(%s, %s)" % (self.name, self._type.__name__)
|
1107 |
+
|
1108 |
+
def register(self, before=None, after=None):
|
1109 |
+
"""register(self, before=None, after=None)
|
1110 |
+
|
1111 |
+
Register the type.
|
1112 |
+
|
1113 |
+
The additional keyword arguments 'before' and 'after' accept a
|
1114 |
+
sequence of type names that must appear before/after the new type in
|
1115 |
+
the type list. If any of them is not currently known, it is simply
|
1116 |
+
ignored. Raises ValueError if the dependencies cannot be fulfilled.
|
1117 |
+
"""
|
1118 |
+
if self.name == TREE_PYTYPE_NAME:
|
1119 |
+
raise ValueError, "Cannot register tree type"
|
1120 |
+
if self.type_check is not None:
|
1121 |
+
for item in _TYPE_CHECKS:
|
1122 |
+
if item[0] is self.type_check:
|
1123 |
+
_TYPE_CHECKS.remove(item)
|
1124 |
+
break
|
1125 |
+
entry = (self.type_check, self)
|
1126 |
+
first_pos = 0
|
1127 |
+
last_pos = -1
|
1128 |
+
if before or after:
|
1129 |
+
if before is None:
|
1130 |
+
before = ()
|
1131 |
+
elif after is None:
|
1132 |
+
after = ()
|
1133 |
+
for i, (check, pytype) in enumerate(_TYPE_CHECKS):
|
1134 |
+
if last_pos == -1 and pytype.name in before:
|
1135 |
+
last_pos = i
|
1136 |
+
if pytype.name in after:
|
1137 |
+
first_pos = i+1
|
1138 |
+
if last_pos == -1:
|
1139 |
+
_TYPE_CHECKS.append(entry)
|
1140 |
+
elif first_pos > last_pos:
|
1141 |
+
raise ValueError, "inconsistent before/after dependencies"
|
1142 |
+
else:
|
1143 |
+
_TYPE_CHECKS.insert(last_pos, entry)
|
1144 |
+
|
1145 |
+
_PYTYPE_DICT[self.name] = self
|
1146 |
+
for xs_type in self._schema_types:
|
1147 |
+
_SCHEMA_TYPE_DICT[xs_type] = self
|
1148 |
+
|
1149 |
+
def unregister(self):
|
1150 |
+
"unregister(self)"
|
1151 |
+
if _PYTYPE_DICT.get(self.name) is self:
|
1152 |
+
del _PYTYPE_DICT[self.name]
|
1153 |
+
for xs_type, pytype in list(_SCHEMA_TYPE_DICT.items()):
|
1154 |
+
if pytype is self:
|
1155 |
+
del _SCHEMA_TYPE_DICT[xs_type]
|
1156 |
+
if self.type_check is None:
|
1157 |
+
return
|
1158 |
+
try:
|
1159 |
+
_TYPE_CHECKS.remove( (self.type_check, self) )
|
1160 |
+
except ValueError:
|
1161 |
+
pass
|
1162 |
+
|
1163 |
+
property xmlSchemaTypes:
|
1164 |
+
"""The list of XML Schema datatypes this Python type maps to.
|
1165 |
+
|
1166 |
+
Note that this must be set before registering the type!
|
1167 |
+
"""
|
1168 |
+
def __get__(self):
|
1169 |
+
return self._schema_types
|
1170 |
+
def __set__(self, types):
|
1171 |
+
self._schema_types = list(map(unicode, types))
|
1172 |
+
|
1173 |
+
|
1174 |
+
cdef dict _PYTYPE_DICT = {}
|
1175 |
+
cdef dict _SCHEMA_TYPE_DICT = {}
|
1176 |
+
cdef list _TYPE_CHECKS = []
|
1177 |
+
|
1178 |
+
cdef unicode _xml_bool(value):
|
1179 |
+
return "true" if value else "false"
|
1180 |
+
|
1181 |
+
cdef unicode _xml_float(value):
|
1182 |
+
if _float_is_inf(value):
|
1183 |
+
if value > 0:
|
1184 |
+
return "INF"
|
1185 |
+
return "-INF"
|
1186 |
+
if _float_is_nan(value):
|
1187 |
+
return "NaN"
|
1188 |
+
return unicode(repr(value))
|
1189 |
+
|
1190 |
+
cdef _pytypename(obj):
|
1191 |
+
return "str" if python._isString(obj) else _typename(obj)
|
1192 |
+
|
1193 |
+
def pytypename(obj):
|
1194 |
+
"""pytypename(obj)
|
1195 |
+
|
1196 |
+
Find the name of the corresponding PyType for a Python object.
|
1197 |
+
"""
|
1198 |
+
return _pytypename(obj)
|
1199 |
+
|
1200 |
+
cdef _registerPyTypes():
|
1201 |
+
pytype = PyType('int', _checkInt, IntElement) # wraps functions for Python
|
1202 |
+
pytype.xmlSchemaTypes = ("integer", "int", "short", "byte", "unsignedShort",
|
1203 |
+
"unsignedByte", "nonPositiveInteger",
|
1204 |
+
"negativeInteger", "long", "nonNegativeInteger",
|
1205 |
+
"unsignedLong", "unsignedInt", "positiveInteger",)
|
1206 |
+
pytype.register()
|
1207 |
+
|
1208 |
+
# 'long' type just for backwards compatibility
|
1209 |
+
pytype = PyType('long', None, IntElement)
|
1210 |
+
pytype.register()
|
1211 |
+
|
1212 |
+
pytype = PyType('float', _checkFloat, FloatElement, _xml_float) # wraps functions for Python
|
1213 |
+
pytype.xmlSchemaTypes = ("double", "float")
|
1214 |
+
pytype.register()
|
1215 |
+
|
1216 |
+
pytype = PyType('bool', _checkBool, BoolElement, _xml_bool) # wraps functions for Python
|
1217 |
+
pytype.xmlSchemaTypes = ("boolean",)
|
1218 |
+
pytype.register()
|
1219 |
+
|
1220 |
+
pytype = PyType('str', None, StringElement)
|
1221 |
+
pytype.xmlSchemaTypes = ("string", "normalizedString", "token", "language",
|
1222 |
+
"Name", "NCName", "ID", "IDREF", "ENTITY",
|
1223 |
+
"NMTOKEN", )
|
1224 |
+
pytype.register()
|
1225 |
+
|
1226 |
+
# since lxml 2.0
|
1227 |
+
pytype = PyType('NoneType', None, NoneElement)
|
1228 |
+
pytype.register()
|
1229 |
+
|
1230 |
+
# backwards compatibility
|
1231 |
+
pytype = PyType('none', None, NoneElement)
|
1232 |
+
pytype.register()
|
1233 |
+
|
1234 |
+
# non-registered PyType for inner tree elements
|
1235 |
+
cdef PyType TREE_PYTYPE = PyType(TREE_PYTYPE_NAME, None, ObjectifiedElement)
|
1236 |
+
|
1237 |
+
_registerPyTypes()
|
1238 |
+
|
1239 |
+
def getRegisteredTypes():
|
1240 |
+
"""getRegisteredTypes()
|
1241 |
+
|
1242 |
+
Returns a list of the currently registered PyType objects.
|
1243 |
+
|
1244 |
+
To add a new type, retrieve this list and call unregister() for all
|
1245 |
+
entries. Then add the new type at a suitable position (possibly replacing
|
1246 |
+
an existing one) and call register() for all entries.
|
1247 |
+
|
1248 |
+
This is necessary if the new type interferes with the type check functions
|
1249 |
+
of existing ones (normally only int/float/bool) and must the tried before
|
1250 |
+
other types. To add a type that is not yet parsable by the current type
|
1251 |
+
check functions, you can simply register() it, which will append it to the
|
1252 |
+
end of the type list.
|
1253 |
+
"""
|
1254 |
+
cdef list types = []
|
1255 |
+
cdef set known = set()
|
1256 |
+
for check, pytype in _TYPE_CHECKS:
|
1257 |
+
name = pytype.name
|
1258 |
+
if name not in known:
|
1259 |
+
known.add(name)
|
1260 |
+
types.append(pytype)
|
1261 |
+
for pytype in _PYTYPE_DICT.values():
|
1262 |
+
name = pytype.name
|
1263 |
+
if name not in known:
|
1264 |
+
known.add(name)
|
1265 |
+
types.append(pytype)
|
1266 |
+
return types
|
1267 |
+
|
1268 |
+
cdef PyType _guessPyType(value, PyType defaulttype):
|
1269 |
+
if value is None:
|
1270 |
+
return None
|
1271 |
+
for type_check, tested_pytype in _TYPE_CHECKS:
|
1272 |
+
try:
|
1273 |
+
type_check(value)
|
1274 |
+
return <PyType>tested_pytype
|
1275 |
+
except IGNORABLE_ERRORS:
|
1276 |
+
# could not be parsed as the specified type => ignore
|
1277 |
+
pass
|
1278 |
+
return defaulttype
|
1279 |
+
|
1280 |
+
cdef object _guessElementClass(tree.xmlNode* c_node):
|
1281 |
+
value = textOf(c_node)
|
1282 |
+
if value is None:
|
1283 |
+
return None
|
1284 |
+
if value == '':
|
1285 |
+
return StringElement
|
1286 |
+
|
1287 |
+
for type_check, pytype in _TYPE_CHECKS:
|
1288 |
+
try:
|
1289 |
+
type_check(value)
|
1290 |
+
return (<PyType>pytype)._type
|
1291 |
+
except IGNORABLE_ERRORS:
|
1292 |
+
pass
|
1293 |
+
return None
|
1294 |
+
|
1295 |
+
################################################################################
|
1296 |
+
# adapted ElementMaker supports registered PyTypes
|
1297 |
+
|
1298 |
+
@cython.final
|
1299 |
+
@cython.internal
|
1300 |
+
cdef class _ObjectifyElementMakerCaller:
|
1301 |
+
cdef object _tag
|
1302 |
+
cdef object _nsmap
|
1303 |
+
cdef object _element_factory
|
1304 |
+
cdef bint _annotate
|
1305 |
+
|
1306 |
+
def __call__(self, *children, **attrib):
|
1307 |
+
"__call__(self, *children, **attrib)"
|
1308 |
+
cdef _ObjectifyElementMakerCaller elementMaker
|
1309 |
+
cdef _Element element
|
1310 |
+
cdef _Element childElement
|
1311 |
+
cdef bint has_children
|
1312 |
+
cdef bint has_string_value
|
1313 |
+
if self._element_factory is None:
|
1314 |
+
element = _makeElement(self._tag, None, attrib, self._nsmap)
|
1315 |
+
else:
|
1316 |
+
element = self._element_factory(self._tag, attrib, self._nsmap)
|
1317 |
+
|
1318 |
+
pytype_name = None
|
1319 |
+
has_children = False
|
1320 |
+
has_string_value = False
|
1321 |
+
for child in children:
|
1322 |
+
if child is None:
|
1323 |
+
if len(children) == 1:
|
1324 |
+
cetree.setAttributeValue(
|
1325 |
+
element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true")
|
1326 |
+
elif python._isString(child):
|
1327 |
+
_add_text(element, child)
|
1328 |
+
has_string_value = True
|
1329 |
+
elif isinstance(child, _Element):
|
1330 |
+
cetree.appendChildToElement(element, <_Element>child)
|
1331 |
+
has_children = True
|
1332 |
+
elif isinstance(child, _ObjectifyElementMakerCaller):
|
1333 |
+
elementMaker = <_ObjectifyElementMakerCaller>child
|
1334 |
+
if elementMaker._element_factory is None:
|
1335 |
+
cetree.makeSubElement(element, elementMaker._tag,
|
1336 |
+
None, None, None, None)
|
1337 |
+
else:
|
1338 |
+
childElement = elementMaker._element_factory(
|
1339 |
+
elementMaker._tag)
|
1340 |
+
cetree.appendChildToElement(element, childElement)
|
1341 |
+
has_children = True
|
1342 |
+
elif isinstance(child, dict):
|
1343 |
+
for name, value in child.items():
|
1344 |
+
# keyword arguments in attrib take precedence
|
1345 |
+
if name in attrib:
|
1346 |
+
continue
|
1347 |
+
pytype = _PYTYPE_DICT.get(_typename(value))
|
1348 |
+
if pytype is not None:
|
1349 |
+
value = (<PyType>pytype).stringify(value)
|
1350 |
+
elif not python._isString(value):
|
1351 |
+
value = unicode(value)
|
1352 |
+
cetree.setAttributeValue(element, name, value)
|
1353 |
+
else:
|
1354 |
+
if pytype_name is not None:
|
1355 |
+
# concatenation always makes the result a string
|
1356 |
+
has_string_value = True
|
1357 |
+
pytype_name = _typename(child)
|
1358 |
+
pytype = _PYTYPE_DICT.get(_typename(child))
|
1359 |
+
if pytype is not None:
|
1360 |
+
_add_text(element, (<PyType>pytype).stringify(child))
|
1361 |
+
else:
|
1362 |
+
has_string_value = True
|
1363 |
+
child = unicode(child)
|
1364 |
+
_add_text(element, child)
|
1365 |
+
|
1366 |
+
if self._annotate and not has_children:
|
1367 |
+
if has_string_value:
|
1368 |
+
cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, "str")
|
1369 |
+
elif pytype_name is not None:
|
1370 |
+
cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name)
|
1371 |
+
|
1372 |
+
return element
|
1373 |
+
|
1374 |
+
cdef _add_text(_Element elem, text):
|
1375 |
+
# add text to the tree in construction, either as element text or
|
1376 |
+
# tail text, depending on the current tree state
|
1377 |
+
cdef tree.xmlNode* c_child
|
1378 |
+
c_child = cetree.findChildBackwards(elem._c_node, 0)
|
1379 |
+
if c_child is not NULL:
|
1380 |
+
old = cetree.tailOf(c_child)
|
1381 |
+
if old is not None:
|
1382 |
+
text = old + text
|
1383 |
+
cetree.setTailText(c_child, text)
|
1384 |
+
else:
|
1385 |
+
old = cetree.textOf(elem._c_node)
|
1386 |
+
if old is not None:
|
1387 |
+
text = old + text
|
1388 |
+
cetree.setNodeText(elem._c_node, text)
|
1389 |
+
|
1390 |
+
cdef class ElementMaker:
|
1391 |
+
"""ElementMaker(self, namespace=None, nsmap=None, annotate=True, makeelement=None)
|
1392 |
+
|
1393 |
+
An ElementMaker that can be used for constructing trees.
|
1394 |
+
|
1395 |
+
Example::
|
1396 |
+
|
1397 |
+
>>> M = ElementMaker(annotate=False)
|
1398 |
+
>>> attributes = {'class': 'par'}
|
1399 |
+
>>> html = M.html( M.body( M.p('hello', attributes, M.br, 'objectify', style="font-weight: bold") ) )
|
1400 |
+
|
1401 |
+
>>> from lxml.etree import tostring
|
1402 |
+
>>> print(tostring(html, method='html').decode('ascii'))
|
1403 |
+
<html><body><p style="font-weight: bold" class="par">hello<br>objectify</p></body></html>
|
1404 |
+
|
1405 |
+
To create tags that are not valid Python identifiers, call the factory
|
1406 |
+
directly and pass the tag name as first argument::
|
1407 |
+
|
1408 |
+
>>> root = M('tricky-tag', 'some text')
|
1409 |
+
>>> print(root.tag)
|
1410 |
+
tricky-tag
|
1411 |
+
>>> print(root.text)
|
1412 |
+
some text
|
1413 |
+
|
1414 |
+
Note that this module has a predefined ElementMaker instance called ``E``.
|
1415 |
+
"""
|
1416 |
+
cdef object _makeelement
|
1417 |
+
cdef object _namespace
|
1418 |
+
cdef object _nsmap
|
1419 |
+
cdef bint _annotate
|
1420 |
+
cdef dict _cache
|
1421 |
+
def __init__(self, *, namespace=None, nsmap=None, annotate=True,
|
1422 |
+
makeelement=None):
|
1423 |
+
if nsmap is None:
|
1424 |
+
nsmap = _DEFAULT_NSMAP if annotate else {}
|
1425 |
+
self._nsmap = nsmap
|
1426 |
+
self._namespace = None if namespace is None else "{%s}" % namespace
|
1427 |
+
self._annotate = annotate
|
1428 |
+
if makeelement is not None:
|
1429 |
+
if not callable(makeelement):
|
1430 |
+
raise TypeError(
|
1431 |
+
f"argument of 'makeelement' parameter must be callable, got {type(makeelement)}")
|
1432 |
+
self._makeelement = makeelement
|
1433 |
+
else:
|
1434 |
+
self._makeelement = None
|
1435 |
+
self._cache = {}
|
1436 |
+
|
1437 |
+
@cython.final
|
1438 |
+
cdef _build_element_maker(self, tag, bint caching):
|
1439 |
+
cdef _ObjectifyElementMakerCaller element_maker
|
1440 |
+
element_maker = _ObjectifyElementMakerCaller.__new__(_ObjectifyElementMakerCaller)
|
1441 |
+
if self._namespace is not None and tag[0] != "{":
|
1442 |
+
element_maker._tag = self._namespace + tag
|
1443 |
+
else:
|
1444 |
+
element_maker._tag = tag
|
1445 |
+
element_maker._nsmap = self._nsmap
|
1446 |
+
element_maker._annotate = self._annotate
|
1447 |
+
element_maker._element_factory = self._makeelement
|
1448 |
+
if caching:
|
1449 |
+
if len(self._cache) > 200:
|
1450 |
+
self._cache.clear()
|
1451 |
+
self._cache[tag] = element_maker
|
1452 |
+
return element_maker
|
1453 |
+
|
1454 |
+
def __getattr__(self, tag):
|
1455 |
+
element_maker = self._cache.get(tag)
|
1456 |
+
if element_maker is None:
|
1457 |
+
return self._build_element_maker(tag, caching=True)
|
1458 |
+
return element_maker
|
1459 |
+
|
1460 |
+
def __call__(self, tag, *args, **kwargs):
|
1461 |
+
element_maker = self._cache.get(tag)
|
1462 |
+
if element_maker is None:
|
1463 |
+
element_maker = self._build_element_maker(
|
1464 |
+
tag, caching=not is_special_method(tag))
|
1465 |
+
return element_maker(*args, **kwargs)
|
1466 |
+
|
1467 |
+
################################################################################
|
1468 |
+
# Recursive element dumping
|
1469 |
+
|
1470 |
+
cdef bint __RECURSIVE_STR = 0 # default: off
|
1471 |
+
|
1472 |
+
def enable_recursive_str(on=True):
|
1473 |
+
"""enable_recursive_str(on=True)
|
1474 |
+
|
1475 |
+
Enable a recursively generated tree representation for str(element),
|
1476 |
+
based on objectify.dump(element).
|
1477 |
+
"""
|
1478 |
+
global __RECURSIVE_STR
|
1479 |
+
__RECURSIVE_STR = on
|
1480 |
+
|
1481 |
+
def dump(_Element element not None):
|
1482 |
+
"""dump(_Element element not None)
|
1483 |
+
|
1484 |
+
Return a recursively generated string representation of an element.
|
1485 |
+
"""
|
1486 |
+
return _dump(element, 0)
|
1487 |
+
|
1488 |
+
cdef object _dump(_Element element, int indent):
|
1489 |
+
indentstr = " " * indent
|
1490 |
+
if isinstance(element, ObjectifiedDataElement):
|
1491 |
+
value = repr(element)
|
1492 |
+
else:
|
1493 |
+
value = textOf(element._c_node)
|
1494 |
+
if value is not None:
|
1495 |
+
if not value.strip():
|
1496 |
+
value = None
|
1497 |
+
else:
|
1498 |
+
value = repr(value)
|
1499 |
+
result = f"{indentstr}{element.tag} = {value} [{_typename(element)}]\n"
|
1500 |
+
xsi_ns = "{%s}" % XML_SCHEMA_INSTANCE_NS
|
1501 |
+
pytype_ns = "{%s}" % PYTYPE_NAMESPACE
|
1502 |
+
for name, value in sorted(cetree.iterattributes(element, 3)):
|
1503 |
+
if '{' in name:
|
1504 |
+
if name == PYTYPE_ATTRIBUTE:
|
1505 |
+
if value == TREE_PYTYPE_NAME:
|
1506 |
+
continue
|
1507 |
+
else:
|
1508 |
+
name = name.replace(pytype_ns, 'py:')
|
1509 |
+
name = name.replace(xsi_ns, 'xsi:')
|
1510 |
+
result += f"{indentstr} * {name} = {value!r}\n"
|
1511 |
+
|
1512 |
+
indent += 1
|
1513 |
+
for child in element.iterchildren():
|
1514 |
+
result += _dump(child, indent)
|
1515 |
+
if indent == 1:
|
1516 |
+
return result[:-1] # strip last '\n'
|
1517 |
+
else:
|
1518 |
+
return result
|
1519 |
+
|
1520 |
+
|
1521 |
+
################################################################################
|
1522 |
+
# Pickle support for objectified ElementTree
|
1523 |
+
|
1524 |
+
def __unpickleElementTree(data):
|
1525 |
+
return etree.ElementTree(fromstring(data))
|
1526 |
+
|
1527 |
+
cdef _setupPickle(elementTreeReduceFunction):
|
1528 |
+
import copyreg
|
1529 |
+
copyreg.pickle(etree._ElementTree,
|
1530 |
+
elementTreeReduceFunction, __unpickleElementTree)
|
1531 |
+
|
1532 |
+
def pickleReduceElementTree(obj):
|
1533 |
+
return __unpickleElementTree, (etree.tostring(obj),)
|
1534 |
+
|
1535 |
+
_setupPickle(pickleReduceElementTree)
|
1536 |
+
del pickleReduceElementTree
|
1537 |
+
|
1538 |
+
################################################################################
|
1539 |
+
# Element class lookup
|
1540 |
+
|
1541 |
+
cdef class ObjectifyElementClassLookup(ElementClassLookup):
|
1542 |
+
"""ObjectifyElementClassLookup(self, tree_class=None, empty_data_class=None)
|
1543 |
+
Element class lookup method that uses the objectify classes.
|
1544 |
+
"""
|
1545 |
+
cdef object empty_data_class
|
1546 |
+
cdef object tree_class
|
1547 |
+
def __init__(self, tree_class=None, empty_data_class=None):
|
1548 |
+
"""Lookup mechanism for objectify.
|
1549 |
+
|
1550 |
+
The default Element classes can be replaced by passing subclasses of
|
1551 |
+
ObjectifiedElement and ObjectifiedDataElement as keyword arguments.
|
1552 |
+
'tree_class' defines inner tree classes (defaults to
|
1553 |
+
ObjectifiedElement), 'empty_data_class' defines the default class for
|
1554 |
+
empty data elements (defaults to StringElement).
|
1555 |
+
"""
|
1556 |
+
self._lookup_function = _lookupElementClass
|
1557 |
+
if tree_class is None:
|
1558 |
+
tree_class = ObjectifiedElement
|
1559 |
+
self.tree_class = tree_class
|
1560 |
+
if empty_data_class is None:
|
1561 |
+
empty_data_class = StringElement
|
1562 |
+
self.empty_data_class = empty_data_class
|
1563 |
+
|
1564 |
+
cdef object _lookupElementClass(state, _Document doc, tree.xmlNode* c_node):
|
1565 |
+
cdef ObjectifyElementClassLookup lookup
|
1566 |
+
lookup = <ObjectifyElementClassLookup>state
|
1567 |
+
# if element has children => no data class
|
1568 |
+
if cetree.hasChild(c_node):
|
1569 |
+
return lookup.tree_class
|
1570 |
+
|
1571 |
+
# if element is defined as xsi:nil, return NoneElement class
|
1572 |
+
if "true" == cetree.attributeValueFromNsName(
|
1573 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil"):
|
1574 |
+
return NoneElement
|
1575 |
+
|
1576 |
+
# check for Python type hint
|
1577 |
+
value = cetree.attributeValueFromNsName(
|
1578 |
+
c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
1579 |
+
if value is not None:
|
1580 |
+
if value == TREE_PYTYPE_NAME:
|
1581 |
+
return lookup.tree_class
|
1582 |
+
py_type = <PyType>_PYTYPE_DICT.get(value)
|
1583 |
+
if py_type is not None:
|
1584 |
+
return py_type._type
|
1585 |
+
# unknown 'pyval' => try to figure it out ourself, just go on
|
1586 |
+
|
1587 |
+
# check for XML Schema type hint
|
1588 |
+
value = cetree.attributeValueFromNsName(
|
1589 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
|
1590 |
+
|
1591 |
+
if value is not None:
|
1592 |
+
schema_type = <PyType>_SCHEMA_TYPE_DICT.get(value)
|
1593 |
+
if schema_type is None and ':' in value:
|
1594 |
+
prefix, value = value.split(':', 1)
|
1595 |
+
schema_type = <PyType>_SCHEMA_TYPE_DICT.get(value)
|
1596 |
+
if schema_type is not None:
|
1597 |
+
return schema_type._type
|
1598 |
+
|
1599 |
+
# otherwise determine class based on text content type
|
1600 |
+
el_class = _guessElementClass(c_node)
|
1601 |
+
if el_class is not None:
|
1602 |
+
return el_class
|
1603 |
+
|
1604 |
+
# if element is a root node => default to tree node
|
1605 |
+
if c_node.parent is NULL or not tree._isElement(c_node.parent):
|
1606 |
+
return lookup.tree_class
|
1607 |
+
|
1608 |
+
return lookup.empty_data_class
|
1609 |
+
|
1610 |
+
|
1611 |
+
################################################################################
|
1612 |
+
# Type annotations
|
1613 |
+
|
1614 |
+
cdef PyType _check_type(tree.xmlNode* c_node, PyType pytype):
|
1615 |
+
if pytype is None:
|
1616 |
+
return None
|
1617 |
+
value = textOf(c_node)
|
1618 |
+
try:
|
1619 |
+
pytype.type_check(value)
|
1620 |
+
return pytype
|
1621 |
+
except IGNORABLE_ERRORS:
|
1622 |
+
# could not be parsed as the specified type => ignore
|
1623 |
+
pass
|
1624 |
+
return None
|
1625 |
+
|
1626 |
+
def pyannotate(element_or_tree, *, ignore_old=False, ignore_xsi=False,
|
1627 |
+
empty_pytype=None):
|
1628 |
+
"""pyannotate(element_or_tree, ignore_old=False, ignore_xsi=False, empty_pytype=None)
|
1629 |
+
|
1630 |
+
Recursively annotates the elements of an XML tree with 'pytype'
|
1631 |
+
attributes.
|
1632 |
+
|
1633 |
+
If the 'ignore_old' keyword argument is True (the default), current 'pytype'
|
1634 |
+
attributes will be ignored and replaced. Otherwise, they will be checked
|
1635 |
+
and only replaced if they no longer fit the current text value.
|
1636 |
+
|
1637 |
+
Setting the keyword argument ``ignore_xsi`` to True makes the function
|
1638 |
+
additionally ignore existing ``xsi:type`` annotations. The default is to
|
1639 |
+
use them as a type hint.
|
1640 |
+
|
1641 |
+
The default annotation of empty elements can be set with the
|
1642 |
+
``empty_pytype`` keyword argument. The default is not to annotate empty
|
1643 |
+
elements. Pass 'str', for example, to make string values the default.
|
1644 |
+
"""
|
1645 |
+
cdef _Element element
|
1646 |
+
element = cetree.rootNodeOrRaise(element_or_tree)
|
1647 |
+
_annotate(element, 0, 1, ignore_xsi, ignore_old, None, empty_pytype)
|
1648 |
+
|
1649 |
+
def xsiannotate(element_or_tree, *, ignore_old=False, ignore_pytype=False,
|
1650 |
+
empty_type=None):
|
1651 |
+
"""xsiannotate(element_or_tree, ignore_old=False, ignore_pytype=False, empty_type=None)
|
1652 |
+
|
1653 |
+
Recursively annotates the elements of an XML tree with 'xsi:type'
|
1654 |
+
attributes.
|
1655 |
+
|
1656 |
+
If the 'ignore_old' keyword argument is True (the default), current
|
1657 |
+
'xsi:type' attributes will be ignored and replaced. Otherwise, they will be
|
1658 |
+
checked and only replaced if they no longer fit the current text value.
|
1659 |
+
|
1660 |
+
Note that the mapping from Python types to XSI types is usually ambiguous.
|
1661 |
+
Currently, only the first XSI type name in the corresponding PyType
|
1662 |
+
definition will be used for annotation. Thus, you should consider naming
|
1663 |
+
the widest type first if you define additional types.
|
1664 |
+
|
1665 |
+
Setting the keyword argument ``ignore_pytype`` to True makes the function
|
1666 |
+
additionally ignore existing ``pytype`` annotations. The default is to
|
1667 |
+
use them as a type hint.
|
1668 |
+
|
1669 |
+
The default annotation of empty elements can be set with the
|
1670 |
+
``empty_type`` keyword argument. The default is not to annotate empty
|
1671 |
+
elements. Pass 'string', for example, to make string values the default.
|
1672 |
+
"""
|
1673 |
+
cdef _Element element
|
1674 |
+
element = cetree.rootNodeOrRaise(element_or_tree)
|
1675 |
+
_annotate(element, 1, 0, ignore_old, ignore_pytype, empty_type, None)
|
1676 |
+
|
1677 |
+
def annotate(element_or_tree, *, ignore_old=True, ignore_xsi=False,
|
1678 |
+
empty_pytype=None, empty_type=None, annotate_xsi=0,
|
1679 |
+
annotate_pytype=1):
|
1680 |
+
"""annotate(element_or_tree, ignore_old=True, ignore_xsi=False, empty_pytype=None, empty_type=None, annotate_xsi=0, annotate_pytype=1)
|
1681 |
+
|
1682 |
+
Recursively annotates the elements of an XML tree with 'xsi:type'
|
1683 |
+
and/or 'py:pytype' attributes.
|
1684 |
+
|
1685 |
+
If the 'ignore_old' keyword argument is True (the default), current
|
1686 |
+
'py:pytype' attributes will be ignored for the type annotation. Set to False
|
1687 |
+
if you want reuse existing 'py:pytype' information (iff appropriate for the
|
1688 |
+
element text value).
|
1689 |
+
|
1690 |
+
If the 'ignore_xsi' keyword argument is False (the default), existing
|
1691 |
+
'xsi:type' attributes will be used for the type annotation, if they fit the
|
1692 |
+
element text values.
|
1693 |
+
|
1694 |
+
Note that the mapping from Python types to XSI types is usually ambiguous.
|
1695 |
+
Currently, only the first XSI type name in the corresponding PyType
|
1696 |
+
definition will be used for annotation. Thus, you should consider naming
|
1697 |
+
the widest type first if you define additional types.
|
1698 |
+
|
1699 |
+
The default 'py:pytype' annotation of empty elements can be set with the
|
1700 |
+
``empty_pytype`` keyword argument. Pass 'str', for example, to make
|
1701 |
+
string values the default.
|
1702 |
+
|
1703 |
+
The default 'xsi:type' annotation of empty elements can be set with the
|
1704 |
+
``empty_type`` keyword argument. The default is not to annotate empty
|
1705 |
+
elements. Pass 'string', for example, to make string values the default.
|
1706 |
+
|
1707 |
+
The keyword arguments 'annotate_xsi' (default: 0) and 'annotate_pytype'
|
1708 |
+
(default: 1) control which kind(s) of annotation to use.
|
1709 |
+
"""
|
1710 |
+
cdef _Element element
|
1711 |
+
element = cetree.rootNodeOrRaise(element_or_tree)
|
1712 |
+
_annotate(element, annotate_xsi, annotate_pytype, ignore_xsi,
|
1713 |
+
ignore_old, empty_type, empty_pytype)
|
1714 |
+
|
1715 |
+
|
1716 |
+
cdef _annotate(_Element element, bint annotate_xsi, bint annotate_pytype,
|
1717 |
+
bint ignore_xsi, bint ignore_pytype,
|
1718 |
+
empty_type_name, empty_pytype_name):
|
1719 |
+
cdef _Document doc
|
1720 |
+
cdef tree.xmlNode* c_node
|
1721 |
+
cdef PyType empty_pytype, StrType, NoneType
|
1722 |
+
|
1723 |
+
if not annotate_xsi and not annotate_pytype:
|
1724 |
+
return
|
1725 |
+
|
1726 |
+
if empty_type_name is not None:
|
1727 |
+
if isinstance(empty_type_name, bytes):
|
1728 |
+
empty_type_name = (<bytes>empty_type_name).decode("ascii")
|
1729 |
+
empty_pytype = <PyType>_SCHEMA_TYPE_DICT.get(empty_type_name)
|
1730 |
+
elif empty_pytype_name is not None:
|
1731 |
+
if isinstance(empty_pytype_name, bytes):
|
1732 |
+
empty_pytype_name = (<bytes>empty_pytype_name).decode("ascii")
|
1733 |
+
empty_pytype = <PyType>_PYTYPE_DICT.get(empty_pytype_name)
|
1734 |
+
else:
|
1735 |
+
empty_pytype = None
|
1736 |
+
|
1737 |
+
StrType = <PyType>_PYTYPE_DICT.get('str')
|
1738 |
+
NoneType = <PyType>_PYTYPE_DICT.get('NoneType')
|
1739 |
+
|
1740 |
+
doc = element._doc
|
1741 |
+
c_node = element._c_node
|
1742 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
|
1743 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
1744 |
+
_annotate_element(c_node, doc, annotate_xsi, annotate_pytype,
|
1745 |
+
ignore_xsi, ignore_pytype,
|
1746 |
+
empty_type_name, empty_pytype, StrType, NoneType)
|
1747 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
1748 |
+
|
1749 |
+
cdef int _annotate_element(tree.xmlNode* c_node, _Document doc,
|
1750 |
+
bint annotate_xsi, bint annotate_pytype,
|
1751 |
+
bint ignore_xsi, bint ignore_pytype,
|
1752 |
+
empty_type_name, PyType empty_pytype,
|
1753 |
+
PyType StrType, PyType NoneType) except -1:
|
1754 |
+
cdef tree.xmlNs* c_ns
|
1755 |
+
cdef PyType pytype = None
|
1756 |
+
typename = None
|
1757 |
+
istree = 0
|
1758 |
+
|
1759 |
+
# if element is defined as xsi:nil, represent it as None
|
1760 |
+
if cetree.attributeValueFromNsName(
|
1761 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil") == "true":
|
1762 |
+
pytype = NoneType
|
1763 |
+
|
1764 |
+
if pytype is None and not ignore_xsi:
|
1765 |
+
# check that old xsi type value is valid
|
1766 |
+
typename = cetree.attributeValueFromNsName(
|
1767 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
|
1768 |
+
if typename is not None:
|
1769 |
+
pytype = <PyType>_SCHEMA_TYPE_DICT.get(typename)
|
1770 |
+
if pytype is None and ':' in typename:
|
1771 |
+
prefix, typename = typename.split(':', 1)
|
1772 |
+
pytype = <PyType>_SCHEMA_TYPE_DICT.get(typename)
|
1773 |
+
if pytype is not None and pytype is not StrType:
|
1774 |
+
# StrType does not have a typecheck but is the default
|
1775 |
+
# anyway, so just accept it if given as type
|
1776 |
+
# information
|
1777 |
+
pytype = _check_type(c_node, pytype)
|
1778 |
+
if pytype is None:
|
1779 |
+
typename = None
|
1780 |
+
|
1781 |
+
if pytype is None and not ignore_pytype:
|
1782 |
+
# check that old pytype value is valid
|
1783 |
+
old_pytypename = cetree.attributeValueFromNsName(
|
1784 |
+
c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
1785 |
+
if old_pytypename is not None:
|
1786 |
+
if old_pytypename == TREE_PYTYPE_NAME:
|
1787 |
+
if not cetree.hasChild(c_node):
|
1788 |
+
# only case where we should keep it,
|
1789 |
+
# everything else is clear enough
|
1790 |
+
pytype = TREE_PYTYPE
|
1791 |
+
else:
|
1792 |
+
if old_pytypename == 'none':
|
1793 |
+
# transition from lxml 1.x
|
1794 |
+
old_pytypename = "NoneType"
|
1795 |
+
pytype = <PyType>_PYTYPE_DICT.get(old_pytypename)
|
1796 |
+
if pytype is not None and pytype is not StrType:
|
1797 |
+
# StrType does not have a typecheck but is the
|
1798 |
+
# default anyway, so just accept it if given as
|
1799 |
+
# type information
|
1800 |
+
pytype = _check_type(c_node, pytype)
|
1801 |
+
|
1802 |
+
if pytype is None:
|
1803 |
+
# try to guess type
|
1804 |
+
if not cetree.hasChild(c_node):
|
1805 |
+
# element has no children => data class
|
1806 |
+
pytype = _guessPyType(textOf(c_node), StrType)
|
1807 |
+
else:
|
1808 |
+
istree = 1
|
1809 |
+
|
1810 |
+
if pytype is None:
|
1811 |
+
# use default type for empty elements
|
1812 |
+
if cetree.hasText(c_node):
|
1813 |
+
pytype = StrType
|
1814 |
+
else:
|
1815 |
+
pytype = empty_pytype
|
1816 |
+
if typename is None:
|
1817 |
+
typename = empty_type_name
|
1818 |
+
|
1819 |
+
if pytype is not None:
|
1820 |
+
if typename is None:
|
1821 |
+
if not istree:
|
1822 |
+
if pytype._schema_types:
|
1823 |
+
# pytype->xsi:type is a 1:n mapping
|
1824 |
+
# simply take the first
|
1825 |
+
typename = pytype._schema_types[0]
|
1826 |
+
elif typename not in pytype._schema_types:
|
1827 |
+
typename = pytype._schema_types[0]
|
1828 |
+
|
1829 |
+
if annotate_xsi:
|
1830 |
+
if typename is None or istree:
|
1831 |
+
cetree.delAttributeFromNsName(
|
1832 |
+
c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
|
1833 |
+
else:
|
1834 |
+
# update or create attribute
|
1835 |
+
typename_utf8 = cetree.utf8(typename)
|
1836 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1837 |
+
doc, c_node, _XML_SCHEMA_NS, <unsigned char*>'xsd')
|
1838 |
+
if c_ns is not NULL:
|
1839 |
+
if b':' in typename_utf8:
|
1840 |
+
prefix, name = typename_utf8.split(b':', 1)
|
1841 |
+
if c_ns.prefix is NULL or c_ns.prefix[0] == c'\0':
|
1842 |
+
typename_utf8 = name
|
1843 |
+
elif tree.xmlStrcmp(_xcstr(prefix), c_ns.prefix) != 0:
|
1844 |
+
typename_utf8 = (<unsigned char*>c_ns.prefix) + b':' + name
|
1845 |
+
elif c_ns.prefix is not NULL and c_ns.prefix[0] != c'\0':
|
1846 |
+
typename_utf8 = (<unsigned char*>c_ns.prefix) + b':' + typename_utf8
|
1847 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1848 |
+
doc, c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>'xsi')
|
1849 |
+
tree.xmlSetNsProp(c_node, c_ns, <unsigned char*>"type", _xcstr(typename_utf8))
|
1850 |
+
|
1851 |
+
if annotate_pytype:
|
1852 |
+
if pytype is None:
|
1853 |
+
# delete attribute if it exists
|
1854 |
+
cetree.delAttributeFromNsName(
|
1855 |
+
c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
|
1856 |
+
else:
|
1857 |
+
# update or create attribute
|
1858 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1859 |
+
doc, c_node, _PYTYPE_NAMESPACE, <unsigned char*>'py')
|
1860 |
+
pytype_name = cetree.utf8(pytype.name)
|
1861 |
+
tree.xmlSetNsProp(c_node, c_ns, _PYTYPE_ATTRIBUTE_NAME,
|
1862 |
+
_xcstr(pytype_name))
|
1863 |
+
if pytype is NoneType:
|
1864 |
+
c_ns = cetree.findOrBuildNodeNsPrefix(
|
1865 |
+
doc, c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>'xsi')
|
1866 |
+
tree.xmlSetNsProp(c_node, c_ns, <unsigned char*>"nil", <unsigned char*>"true")
|
1867 |
+
|
1868 |
+
return 0
|
1869 |
+
|
1870 |
+
cdef object _strip_attributes = etree.strip_attributes
|
1871 |
+
cdef object _cleanup_namespaces = etree.cleanup_namespaces
|
1872 |
+
|
1873 |
+
def deannotate(element_or_tree, *, bint pytype=True, bint xsi=True,
|
1874 |
+
bint xsi_nil=False, bint cleanup_namespaces=False):
|
1875 |
+
"""deannotate(element_or_tree, pytype=True, xsi=True, xsi_nil=False, cleanup_namespaces=False)
|
1876 |
+
|
1877 |
+
Recursively de-annotate the elements of an XML tree by removing 'py:pytype'
|
1878 |
+
and/or 'xsi:type' attributes and/or 'xsi:nil' attributes.
|
1879 |
+
|
1880 |
+
If the 'pytype' keyword argument is True (the default), 'py:pytype'
|
1881 |
+
attributes will be removed. If the 'xsi' keyword argument is True (the
|
1882 |
+
default), 'xsi:type' attributes will be removed.
|
1883 |
+
If the 'xsi_nil' keyword argument is True (default: False), 'xsi:nil'
|
1884 |
+
attributes will be removed.
|
1885 |
+
|
1886 |
+
Note that this does not touch the namespace declarations by
|
1887 |
+
default. If you want to remove unused namespace declarations from
|
1888 |
+
the tree, pass the option ``cleanup_namespaces=True``.
|
1889 |
+
"""
|
1890 |
+
cdef list attribute_names = []
|
1891 |
+
|
1892 |
+
if pytype:
|
1893 |
+
attribute_names.append(PYTYPE_ATTRIBUTE)
|
1894 |
+
if xsi:
|
1895 |
+
attribute_names.append(XML_SCHEMA_INSTANCE_TYPE_ATTR)
|
1896 |
+
if xsi_nil:
|
1897 |
+
attribute_names.append(XML_SCHEMA_INSTANCE_NIL_ATTR)
|
1898 |
+
|
1899 |
+
_strip_attributes(element_or_tree, *attribute_names)
|
1900 |
+
if cleanup_namespaces:
|
1901 |
+
_cleanup_namespaces(element_or_tree)
|
1902 |
+
|
1903 |
+
################################################################################
|
1904 |
+
# Module level parser setup
|
1905 |
+
|
1906 |
+
cdef object __DEFAULT_PARSER
|
1907 |
+
__DEFAULT_PARSER = etree.XMLParser(remove_blank_text=True)
|
1908 |
+
__DEFAULT_PARSER.set_element_class_lookup( ObjectifyElementClassLookup() )
|
1909 |
+
|
1910 |
+
cdef object objectify_parser
|
1911 |
+
objectify_parser = __DEFAULT_PARSER
|
1912 |
+
|
1913 |
+
def set_default_parser(new_parser = None):
|
1914 |
+
"""set_default_parser(new_parser = None)
|
1915 |
+
|
1916 |
+
Replace the default parser used by objectify's Element() and
|
1917 |
+
fromstring() functions.
|
1918 |
+
|
1919 |
+
The new parser must be an etree.XMLParser.
|
1920 |
+
|
1921 |
+
Call without arguments to reset to the original parser.
|
1922 |
+
"""
|
1923 |
+
global objectify_parser
|
1924 |
+
if new_parser is None:
|
1925 |
+
objectify_parser = __DEFAULT_PARSER
|
1926 |
+
elif isinstance(new_parser, etree.XMLParser):
|
1927 |
+
objectify_parser = new_parser
|
1928 |
+
else:
|
1929 |
+
raise TypeError, "parser must inherit from lxml.etree.XMLParser"
|
1930 |
+
|
1931 |
+
def makeparser(**kw):
|
1932 |
+
"""makeparser(remove_blank_text=True, **kw)
|
1933 |
+
|
1934 |
+
Create a new XML parser for objectify trees.
|
1935 |
+
|
1936 |
+
You can pass all keyword arguments that are supported by
|
1937 |
+
``etree.XMLParser()``. Note that this parser defaults to removing
|
1938 |
+
blank text. You can disable this by passing the
|
1939 |
+
``remove_blank_text`` boolean keyword option yourself.
|
1940 |
+
"""
|
1941 |
+
if 'remove_blank_text' not in kw:
|
1942 |
+
kw['remove_blank_text'] = True
|
1943 |
+
parser = etree.XMLParser(**kw)
|
1944 |
+
parser.set_element_class_lookup( ObjectifyElementClassLookup() )
|
1945 |
+
return parser
|
1946 |
+
|
1947 |
+
cdef _Element _makeElement(tag, text, attrib, nsmap):
|
1948 |
+
return cetree.makeElement(tag, None, objectify_parser, text, None, attrib, nsmap)
|
1949 |
+
|
1950 |
+
################################################################################
|
1951 |
+
# Module level factory functions
|
1952 |
+
|
1953 |
+
cdef object _fromstring
|
1954 |
+
_fromstring = etree.fromstring
|
1955 |
+
|
1956 |
+
SubElement = etree.SubElement
|
1957 |
+
|
1958 |
+
def fromstring(xml, parser=None, *, base_url=None):
|
1959 |
+
"""fromstring(xml, parser=None, base_url=None)
|
1960 |
+
|
1961 |
+
Objectify specific version of the lxml.etree fromstring() function
|
1962 |
+
that uses the objectify parser.
|
1963 |
+
|
1964 |
+
You can pass a different parser as second argument.
|
1965 |
+
|
1966 |
+
The ``base_url`` keyword argument allows to set the original base URL of
|
1967 |
+
the document to support relative Paths when looking up external entities
|
1968 |
+
(DTD, XInclude, ...).
|
1969 |
+
"""
|
1970 |
+
if parser is None:
|
1971 |
+
parser = objectify_parser
|
1972 |
+
return _fromstring(xml, parser, base_url=base_url)
|
1973 |
+
|
1974 |
+
def XML(xml, parser=None, *, base_url=None):
|
1975 |
+
"""XML(xml, parser=None, base_url=None)
|
1976 |
+
|
1977 |
+
Objectify specific version of the lxml.etree XML() literal factory
|
1978 |
+
that uses the objectify parser.
|
1979 |
+
|
1980 |
+
You can pass a different parser as second argument.
|
1981 |
+
|
1982 |
+
The ``base_url`` keyword argument allows to set the original base URL of
|
1983 |
+
the document to support relative Paths when looking up external entities
|
1984 |
+
(DTD, XInclude, ...).
|
1985 |
+
"""
|
1986 |
+
if parser is None:
|
1987 |
+
parser = objectify_parser
|
1988 |
+
return _fromstring(xml, parser, base_url=base_url)
|
1989 |
+
|
1990 |
+
cdef object _parse
|
1991 |
+
_parse = etree.parse
|
1992 |
+
|
1993 |
+
def parse(f, parser=None, *, base_url=None):
|
1994 |
+
"""parse(f, parser=None, base_url=None)
|
1995 |
+
|
1996 |
+
Parse a file or file-like object with the objectify parser.
|
1997 |
+
|
1998 |
+
You can pass a different parser as second argument.
|
1999 |
+
|
2000 |
+
The ``base_url`` keyword allows setting a URL for the document
|
2001 |
+
when parsing from a file-like object. This is needed when looking
|
2002 |
+
up external entities (DTD, XInclude, ...) with relative paths.
|
2003 |
+
"""
|
2004 |
+
if parser is None:
|
2005 |
+
parser = objectify_parser
|
2006 |
+
return _parse(f, parser, base_url=base_url)
|
2007 |
+
|
2008 |
+
cdef dict _DEFAULT_NSMAP = {
|
2009 |
+
"py" : PYTYPE_NAMESPACE,
|
2010 |
+
"xsi" : XML_SCHEMA_INSTANCE_NS,
|
2011 |
+
"xsd" : XML_SCHEMA_NS
|
2012 |
+
}
|
2013 |
+
|
2014 |
+
E = ElementMaker()
|
2015 |
+
|
2016 |
+
def Element(_tag, attrib=None, nsmap=None, *, _pytype=None, **_attributes):
|
2017 |
+
"""Element(_tag, attrib=None, nsmap=None, _pytype=None, **_attributes)
|
2018 |
+
|
2019 |
+
Objectify specific version of the lxml.etree Element() factory that
|
2020 |
+
always creates a structural (tree) element.
|
2021 |
+
|
2022 |
+
NOTE: requires parser based element class lookup activated in lxml.etree!
|
2023 |
+
"""
|
2024 |
+
if attrib is not None:
|
2025 |
+
if _attributes:
|
2026 |
+
attrib = dict(attrib)
|
2027 |
+
attrib.update(_attributes)
|
2028 |
+
_attributes = attrib
|
2029 |
+
if _pytype is None:
|
2030 |
+
_pytype = TREE_PYTYPE_NAME
|
2031 |
+
if nsmap is None:
|
2032 |
+
nsmap = _DEFAULT_NSMAP
|
2033 |
+
_attributes[PYTYPE_ATTRIBUTE] = _pytype
|
2034 |
+
return _makeElement(_tag, None, _attributes, nsmap)
|
2035 |
+
|
2036 |
+
def DataElement(_value, attrib=None, nsmap=None, *, _pytype=None, _xsi=None,
|
2037 |
+
**_attributes):
|
2038 |
+
"""DataElement(_value, attrib=None, nsmap=None, _pytype=None, _xsi=None, **_attributes)
|
2039 |
+
|
2040 |
+
Create a new element from a Python value and XML attributes taken from
|
2041 |
+
keyword arguments or a dictionary passed as second argument.
|
2042 |
+
|
2043 |
+
Automatically adds a 'pytype' attribute for the Python type of the value,
|
2044 |
+
if the type can be identified. If '_pytype' or '_xsi' are among the
|
2045 |
+
keyword arguments, they will be used instead.
|
2046 |
+
|
2047 |
+
If the _value argument is an ObjectifiedDataElement instance, its py:pytype,
|
2048 |
+
xsi:type and other attributes and nsmap are reused unless they are redefined
|
2049 |
+
in attrib and/or keyword arguments.
|
2050 |
+
"""
|
2051 |
+
if nsmap is None:
|
2052 |
+
nsmap = _DEFAULT_NSMAP
|
2053 |
+
if attrib is not None and attrib:
|
2054 |
+
if _attributes:
|
2055 |
+
attrib = dict(attrib)
|
2056 |
+
attrib.update(_attributes)
|
2057 |
+
_attributes = attrib
|
2058 |
+
if isinstance(_value, ObjectifiedElement):
|
2059 |
+
if _pytype is None:
|
2060 |
+
if _xsi is None and not _attributes and nsmap is _DEFAULT_NSMAP:
|
2061 |
+
# special case: no change!
|
2062 |
+
return _value.__copy__()
|
2063 |
+
if isinstance(_value, ObjectifiedDataElement):
|
2064 |
+
# reuse existing nsmap unless redefined in nsmap parameter
|
2065 |
+
temp = _value.nsmap
|
2066 |
+
if temp is not None and temp:
|
2067 |
+
temp = dict(temp)
|
2068 |
+
temp.update(nsmap)
|
2069 |
+
nsmap = temp
|
2070 |
+
# reuse existing attributes unless redefined in attrib/_attributes
|
2071 |
+
temp = _value.attrib
|
2072 |
+
if temp is not None and temp:
|
2073 |
+
temp = dict(temp)
|
2074 |
+
temp.update(_attributes)
|
2075 |
+
_attributes = temp
|
2076 |
+
# reuse existing xsi:type or py:pytype attributes, unless provided as
|
2077 |
+
# arguments
|
2078 |
+
if _xsi is None and _pytype is None:
|
2079 |
+
_xsi = _attributes.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
|
2080 |
+
_pytype = _attributes.get(PYTYPE_ATTRIBUTE)
|
2081 |
+
|
2082 |
+
if _xsi is not None:
|
2083 |
+
if ':' in _xsi:
|
2084 |
+
prefix, name = _xsi.split(':', 1)
|
2085 |
+
ns = nsmap.get(prefix)
|
2086 |
+
if ns != XML_SCHEMA_NS:
|
2087 |
+
raise ValueError, "XSD types require the XSD namespace"
|
2088 |
+
elif nsmap is _DEFAULT_NSMAP:
|
2089 |
+
name = _xsi
|
2090 |
+
_xsi = 'xsd:' + _xsi
|
2091 |
+
else:
|
2092 |
+
name = _xsi
|
2093 |
+
for prefix, ns in nsmap.items():
|
2094 |
+
if ns == XML_SCHEMA_NS:
|
2095 |
+
if prefix is not None and prefix:
|
2096 |
+
_xsi = prefix + ':' + _xsi
|
2097 |
+
break
|
2098 |
+
else:
|
2099 |
+
raise ValueError, "XSD types require the XSD namespace"
|
2100 |
+
_attributes[XML_SCHEMA_INSTANCE_TYPE_ATTR] = _xsi
|
2101 |
+
if _pytype is None:
|
2102 |
+
# allow using unregistered or even wrong xsi:type names
|
2103 |
+
py_type = <PyType>_SCHEMA_TYPE_DICT.get(_xsi)
|
2104 |
+
if py_type is None:
|
2105 |
+
py_type = <PyType>_SCHEMA_TYPE_DICT.get(name)
|
2106 |
+
if py_type is not None:
|
2107 |
+
_pytype = py_type.name
|
2108 |
+
|
2109 |
+
if _pytype is None:
|
2110 |
+
_pytype = _pytypename(_value)
|
2111 |
+
|
2112 |
+
if _value is None and _pytype != "str":
|
2113 |
+
_pytype = _pytype or "NoneType"
|
2114 |
+
strval = None
|
2115 |
+
elif python._isString(_value):
|
2116 |
+
strval = _value
|
2117 |
+
elif isinstance(_value, bool):
|
2118 |
+
if _value:
|
2119 |
+
strval = "true"
|
2120 |
+
else:
|
2121 |
+
strval = "false"
|
2122 |
+
else:
|
2123 |
+
py_type = <PyType>_PYTYPE_DICT.get(_pytype)
|
2124 |
+
stringify = unicode if py_type is None else py_type.stringify
|
2125 |
+
strval = stringify(_value)
|
2126 |
+
|
2127 |
+
if _pytype is not None:
|
2128 |
+
if _pytype == "NoneType" or _pytype == "none":
|
2129 |
+
strval = None
|
2130 |
+
_attributes[XML_SCHEMA_INSTANCE_NIL_ATTR] = "true"
|
2131 |
+
else:
|
2132 |
+
# check if type information from arguments is valid
|
2133 |
+
py_type = <PyType>_PYTYPE_DICT.get(_pytype)
|
2134 |
+
if py_type is not None:
|
2135 |
+
if py_type.type_check is not None:
|
2136 |
+
py_type.type_check(strval)
|
2137 |
+
_attributes[PYTYPE_ATTRIBUTE] = _pytype
|
2138 |
+
|
2139 |
+
return _makeElement("value", strval, _attributes, nsmap)
|
2140 |
+
|
2141 |
+
|
2142 |
+
################################################################################
|
2143 |
+
# ObjectPath
|
2144 |
+
|
2145 |
+
include "objectpath.pxi"
|
env-llmeval/lib/python3.10/site-packages/lxml/objectpath.pxi
ADDED
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
################################################################################
|
2 |
+
# ObjectPath
|
3 |
+
|
4 |
+
ctypedef struct _ObjectPath:
|
5 |
+
const_xmlChar* href
|
6 |
+
const_xmlChar* name
|
7 |
+
Py_ssize_t index
|
8 |
+
|
9 |
+
|
10 |
+
cdef object _NO_DEFAULT = object()
|
11 |
+
|
12 |
+
|
13 |
+
cdef class ObjectPath:
|
14 |
+
"""ObjectPath(path)
|
15 |
+
Immutable object that represents a compiled object path.
|
16 |
+
|
17 |
+
Example for a path: 'root.child[1].{other}child[25]'
|
18 |
+
"""
|
19 |
+
cdef readonly object find
|
20 |
+
cdef list _path
|
21 |
+
cdef object _path_str
|
22 |
+
cdef _ObjectPath* _c_path
|
23 |
+
cdef Py_ssize_t _path_len
|
24 |
+
def __init__(self, path):
|
25 |
+
if python._isString(path):
|
26 |
+
self._path = _parse_object_path_string(path)
|
27 |
+
self._path_str = path
|
28 |
+
else:
|
29 |
+
self._path = _parse_object_path_list(path)
|
30 |
+
self._path_str = '.'.join(path)
|
31 |
+
self._path_len = len(self._path)
|
32 |
+
self._c_path = _build_object_path_segments(self._path)
|
33 |
+
self.find = self.__call__
|
34 |
+
|
35 |
+
def __dealloc__(self):
|
36 |
+
if self._c_path is not NULL:
|
37 |
+
python.lxml_free(self._c_path)
|
38 |
+
|
39 |
+
def __str__(self):
|
40 |
+
return self._path_str
|
41 |
+
|
42 |
+
def __call__(self, _Element root not None, *_default):
|
43 |
+
"""Follow the attribute path in the object structure and return the
|
44 |
+
target attribute value.
|
45 |
+
|
46 |
+
If it it not found, either returns a default value (if one was passed
|
47 |
+
as second argument) or raises AttributeError.
|
48 |
+
"""
|
49 |
+
if _default:
|
50 |
+
if len(_default) > 1:
|
51 |
+
raise TypeError, "invalid number of arguments: needs one or two"
|
52 |
+
default = _default[0]
|
53 |
+
else:
|
54 |
+
default = _NO_DEFAULT
|
55 |
+
return _find_object_path(root, self._c_path, self._path_len, default)
|
56 |
+
|
57 |
+
def hasattr(self, _Element root not None):
|
58 |
+
"hasattr(self, root)"
|
59 |
+
try:
|
60 |
+
_find_object_path(root, self._c_path, self._path_len, _NO_DEFAULT)
|
61 |
+
except AttributeError:
|
62 |
+
return False
|
63 |
+
return True
|
64 |
+
|
65 |
+
def setattr(self, _Element root not None, value):
|
66 |
+
"""setattr(self, root, value)
|
67 |
+
|
68 |
+
Set the value of the target element in a subtree.
|
69 |
+
|
70 |
+
If any of the children on the path does not exist, it is created.
|
71 |
+
"""
|
72 |
+
_create_object_path(root, self._c_path, self._path_len, 1, value)
|
73 |
+
|
74 |
+
def addattr(self, _Element root not None, value):
|
75 |
+
"""addattr(self, root, value)
|
76 |
+
|
77 |
+
Append a value to the target element in a subtree.
|
78 |
+
|
79 |
+
If any of the children on the path does not exist, it is created.
|
80 |
+
"""
|
81 |
+
_create_object_path(root, self._c_path, self._path_len, 0, value)
|
82 |
+
|
83 |
+
|
84 |
+
cdef object __MATCH_PATH_SEGMENT = re.compile(
|
85 |
+
r"(\.?)\s*(?:\{([^}]*)\})?\s*([^.{}\[\]\s]+)\s*(?:\[\s*([-0-9]+)\s*\])?",
|
86 |
+
re.U).match
|
87 |
+
|
88 |
+
cdef tuple _RELATIVE_PATH_SEGMENT = (None, None, 0)
|
89 |
+
|
90 |
+
|
91 |
+
cdef list _parse_object_path_string(_path):
|
92 |
+
"""Parse object path string into a (ns, name, index) list.
|
93 |
+
"""
|
94 |
+
cdef bint has_dot
|
95 |
+
cdef unicode path
|
96 |
+
new_path = []
|
97 |
+
if isinstance(_path, bytes):
|
98 |
+
path = (<bytes>_path).decode('ascii')
|
99 |
+
elif type(_path) is not unicode:
|
100 |
+
path = unicode(_path)
|
101 |
+
else:
|
102 |
+
path = _path
|
103 |
+
path = path.strip()
|
104 |
+
if path == '.':
|
105 |
+
return [_RELATIVE_PATH_SEGMENT]
|
106 |
+
path_pos = 0
|
107 |
+
while path:
|
108 |
+
match = __MATCH_PATH_SEGMENT(path, path_pos)
|
109 |
+
if match is None:
|
110 |
+
break
|
111 |
+
|
112 |
+
dot, ns, name, index = match.groups()
|
113 |
+
index = int(index) if index else 0
|
114 |
+
has_dot = dot == '.'
|
115 |
+
if not new_path:
|
116 |
+
if has_dot:
|
117 |
+
# path '.child' => ignore root
|
118 |
+
new_path.append(_RELATIVE_PATH_SEGMENT)
|
119 |
+
elif index:
|
120 |
+
raise ValueError, "index not allowed on root node"
|
121 |
+
elif not has_dot:
|
122 |
+
raise ValueError, "invalid path"
|
123 |
+
if ns is not None:
|
124 |
+
ns = python.PyUnicode_AsUTF8String(ns)
|
125 |
+
name = python.PyUnicode_AsUTF8String(name)
|
126 |
+
new_path.append( (ns, name, index) )
|
127 |
+
|
128 |
+
path_pos = match.end()
|
129 |
+
if not new_path or len(path) > path_pos:
|
130 |
+
raise ValueError, "invalid path"
|
131 |
+
return new_path
|
132 |
+
|
133 |
+
|
134 |
+
cdef list _parse_object_path_list(path):
|
135 |
+
"""Parse object path sequence into a (ns, name, index) list.
|
136 |
+
"""
|
137 |
+
new_path = []
|
138 |
+
for item in path:
|
139 |
+
item = item.strip()
|
140 |
+
if not new_path and item == '':
|
141 |
+
# path '.child' => ignore root
|
142 |
+
ns = name = None
|
143 |
+
index = 0
|
144 |
+
else:
|
145 |
+
ns, name = cetree.getNsTag(item)
|
146 |
+
c_name = _xcstr(name)
|
147 |
+
index_pos = tree.xmlStrchr(c_name, c'[')
|
148 |
+
if index_pos is NULL:
|
149 |
+
index = 0
|
150 |
+
else:
|
151 |
+
index_end = tree.xmlStrchr(index_pos + 1, c']')
|
152 |
+
if index_end is NULL:
|
153 |
+
raise ValueError, "index must be enclosed in []"
|
154 |
+
index = int(index_pos[1:index_end - index_pos])
|
155 |
+
if not new_path and index != 0:
|
156 |
+
raise ValueError, "index not allowed on root node"
|
157 |
+
name = <bytes>c_name[:index_pos - c_name]
|
158 |
+
new_path.append( (ns, name, index) )
|
159 |
+
if not new_path:
|
160 |
+
raise ValueError, "invalid path"
|
161 |
+
return new_path
|
162 |
+
|
163 |
+
|
164 |
+
cdef _ObjectPath* _build_object_path_segments(list path_list) except NULL:
|
165 |
+
cdef _ObjectPath* c_path
|
166 |
+
cdef _ObjectPath* c_path_segments
|
167 |
+
c_path_segments = <_ObjectPath*>python.lxml_malloc(len(path_list), sizeof(_ObjectPath))
|
168 |
+
if c_path_segments is NULL:
|
169 |
+
raise MemoryError()
|
170 |
+
c_path = c_path_segments
|
171 |
+
for href, name, index in path_list:
|
172 |
+
c_path[0].href = _xcstr(href) if href is not None else NULL
|
173 |
+
c_path[0].name = _xcstr(name) if name is not None else NULL
|
174 |
+
c_path[0].index = index
|
175 |
+
c_path += 1
|
176 |
+
return c_path_segments
|
177 |
+
|
178 |
+
|
179 |
+
cdef _find_object_path(_Element root, _ObjectPath* c_path, Py_ssize_t c_path_len, default_value):
|
180 |
+
"""Follow the path to find the target element.
|
181 |
+
"""
|
182 |
+
cdef tree.xmlNode* c_node
|
183 |
+
cdef Py_ssize_t c_index
|
184 |
+
c_node = root._c_node
|
185 |
+
c_name = c_path[0].name
|
186 |
+
c_href = c_path[0].href
|
187 |
+
if c_href is NULL or c_href[0] == c'\0':
|
188 |
+
c_href = tree._getNs(c_node)
|
189 |
+
if not cetree.tagMatches(c_node, c_href, c_name):
|
190 |
+
if default_value is not _NO_DEFAULT:
|
191 |
+
return default_value
|
192 |
+
else:
|
193 |
+
raise ValueError(
|
194 |
+
f"root element does not match: need {cetree.namespacedNameFromNsName(c_href, c_name)}, got {root.tag}")
|
195 |
+
|
196 |
+
while c_node is not NULL:
|
197 |
+
c_path_len -= 1
|
198 |
+
if c_path_len <= 0:
|
199 |
+
break
|
200 |
+
|
201 |
+
c_path += 1
|
202 |
+
if c_path[0].href is not NULL:
|
203 |
+
c_href = c_path[0].href # otherwise: keep parent namespace
|
204 |
+
c_name = tree.xmlDictExists(c_node.doc.dict, c_path[0].name, -1)
|
205 |
+
if c_name is NULL:
|
206 |
+
c_name = c_path[0].name
|
207 |
+
c_node = NULL
|
208 |
+
break
|
209 |
+
c_index = c_path[0].index
|
210 |
+
c_node = c_node.last if c_index < 0 else c_node.children
|
211 |
+
c_node = _findFollowingSibling(c_node, c_href, c_name, c_index)
|
212 |
+
|
213 |
+
if c_node is not NULL:
|
214 |
+
return cetree.elementFactory(root._doc, c_node)
|
215 |
+
elif default_value is not _NO_DEFAULT:
|
216 |
+
return default_value
|
217 |
+
else:
|
218 |
+
tag = cetree.namespacedNameFromNsName(c_href, c_name)
|
219 |
+
raise AttributeError, f"no such child: {tag}"
|
220 |
+
|
221 |
+
|
222 |
+
cdef _create_object_path(_Element root, _ObjectPath* c_path,
|
223 |
+
Py_ssize_t c_path_len, int replace, value):
|
224 |
+
"""Follow the path to find the target element, build the missing children
|
225 |
+
as needed and set the target element to 'value'. If replace is true, an
|
226 |
+
existing value is replaced, otherwise the new value is added.
|
227 |
+
"""
|
228 |
+
cdef _Element child
|
229 |
+
cdef tree.xmlNode* c_node
|
230 |
+
cdef tree.xmlNode* c_child
|
231 |
+
cdef Py_ssize_t c_index
|
232 |
+
if c_path_len == 1:
|
233 |
+
raise TypeError, "cannot update root node"
|
234 |
+
|
235 |
+
c_node = root._c_node
|
236 |
+
c_name = c_path[0].name
|
237 |
+
c_href = c_path[0].href
|
238 |
+
if c_href is NULL or c_href[0] == c'\0':
|
239 |
+
c_href = tree._getNs(c_node)
|
240 |
+
if not cetree.tagMatches(c_node, c_href, c_name):
|
241 |
+
raise ValueError(
|
242 |
+
f"root element does not match: need {cetree.namespacedNameFromNsName(c_href, c_name)}, got {root.tag}")
|
243 |
+
|
244 |
+
while c_path_len > 1:
|
245 |
+
c_path_len -= 1
|
246 |
+
c_path += 1
|
247 |
+
if c_path[0].href is not NULL:
|
248 |
+
c_href = c_path[0].href # otherwise: keep parent namespace
|
249 |
+
c_index = c_path[0].index
|
250 |
+
c_name = tree.xmlDictExists(c_node.doc.dict, c_path[0].name, -1)
|
251 |
+
if c_name is NULL:
|
252 |
+
c_name = c_path[0].name
|
253 |
+
c_child = NULL
|
254 |
+
else:
|
255 |
+
c_child = c_node.last if c_index < 0 else c_node.children
|
256 |
+
c_child = _findFollowingSibling(c_child, c_href, c_name, c_index)
|
257 |
+
|
258 |
+
if c_child is not NULL:
|
259 |
+
c_node = c_child
|
260 |
+
elif c_index != 0:
|
261 |
+
raise TypeError, "creating indexed path attributes is not supported"
|
262 |
+
elif c_path_len == 1:
|
263 |
+
_appendValue(cetree.elementFactory(root._doc, c_node),
|
264 |
+
cetree.namespacedNameFromNsName(c_href, c_name),
|
265 |
+
value)
|
266 |
+
return
|
267 |
+
else:
|
268 |
+
child = cetree.makeSubElement(
|
269 |
+
cetree.elementFactory(root._doc, c_node),
|
270 |
+
cetree.namespacedNameFromNsName(c_href, c_name),
|
271 |
+
None, None, None, None)
|
272 |
+
c_node = child._c_node
|
273 |
+
|
274 |
+
# if we get here, the entire path was already there
|
275 |
+
if replace:
|
276 |
+
element = cetree.elementFactory(root._doc, c_node)
|
277 |
+
_replaceElement(element, value)
|
278 |
+
else:
|
279 |
+
_appendValue(cetree.elementFactory(root._doc, c_node.parent),
|
280 |
+
cetree.namespacedName(c_node), value)
|
281 |
+
|
282 |
+
|
283 |
+
cdef list _build_descendant_paths(tree.xmlNode* c_node, prefix_string):
|
284 |
+
"""Returns a list of all descendant paths.
|
285 |
+
"""
|
286 |
+
cdef list path, path_list
|
287 |
+
tag = cetree.namespacedName(c_node)
|
288 |
+
if prefix_string:
|
289 |
+
if prefix_string[-1] != '.':
|
290 |
+
prefix_string += '.'
|
291 |
+
prefix_string = prefix_string + tag
|
292 |
+
else:
|
293 |
+
prefix_string = tag
|
294 |
+
path = [prefix_string]
|
295 |
+
path_list = []
|
296 |
+
_recursive_build_descendant_paths(c_node, path, path_list)
|
297 |
+
return path_list
|
298 |
+
|
299 |
+
|
300 |
+
cdef int _recursive_build_descendant_paths(tree.xmlNode* c_node,
|
301 |
+
list path, list path_list) except -1:
|
302 |
+
"""Fills the list 'path_list' with all descendant paths, initial prefix
|
303 |
+
being in the list 'path'.
|
304 |
+
"""
|
305 |
+
cdef tree.xmlNode* c_child
|
306 |
+
tags = {}
|
307 |
+
path_list.append('.'.join(path))
|
308 |
+
c_href = tree._getNs(c_node)
|
309 |
+
c_child = c_node.children
|
310 |
+
while c_child is not NULL:
|
311 |
+
while c_child.type != tree.XML_ELEMENT_NODE:
|
312 |
+
c_child = c_child.next
|
313 |
+
if c_child is NULL:
|
314 |
+
return 0
|
315 |
+
if c_href is tree._getNs(c_child):
|
316 |
+
tag = pyunicode(c_child.name)
|
317 |
+
elif c_href is not NULL and tree._getNs(c_child) is NULL:
|
318 |
+
# special case: parent has namespace, child does not
|
319 |
+
tag = '{}' + pyunicode(c_child.name)
|
320 |
+
else:
|
321 |
+
tag = cetree.namespacedName(c_child)
|
322 |
+
count = tags.get(tag)
|
323 |
+
if count is None:
|
324 |
+
tags[tag] = 1
|
325 |
+
else:
|
326 |
+
tags[tag] = count + 1
|
327 |
+
tag += f'[{count}]'
|
328 |
+
path.append(tag)
|
329 |
+
_recursive_build_descendant_paths(c_child, path, path_list)
|
330 |
+
del path[-1]
|
331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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 class HTMLParser(_FeedParser):
|
1751 |
+
"""HTMLParser(self, encoding=None, remove_blank_text=False, \
|
1752 |
+
remove_comments=False, remove_pis=False, strip_cdata=True, \
|
1753 |
+
no_network=True, target=None, schema: XMLSchema =None, \
|
1754 |
+
recover=True, compact=True, collect_ids=True, huge_tree=False)
|
1755 |
+
|
1756 |
+
The HTML parser.
|
1757 |
+
|
1758 |
+
This parser allows reading HTML into a normal XML tree. By
|
1759 |
+
default, it can read broken (non well-formed) HTML, depending on
|
1760 |
+
the capabilities of libxml2. Use the 'recover' option to switch
|
1761 |
+
this off.
|
1762 |
+
|
1763 |
+
Available boolean keyword arguments:
|
1764 |
+
|
1765 |
+
- recover - try hard to parse through broken HTML (default: True)
|
1766 |
+
- no_network - prevent network access for related files (default: True)
|
1767 |
+
- remove_blank_text - discard empty text nodes that are ignorable (i.e. not actual text content)
|
1768 |
+
- remove_comments - discard comments
|
1769 |
+
- remove_pis - discard processing instructions
|
1770 |
+
- strip_cdata - replace CDATA sections by normal text content (default: True)
|
1771 |
+
- compact - save memory for short text content (default: True)
|
1772 |
+
- default_doctype - add a default doctype even if it is not found in the HTML (default: True)
|
1773 |
+
- collect_ids - use a hash table of XML IDs for fast access (default: True)
|
1774 |
+
- huge_tree - disable security restrictions and support very deep trees
|
1775 |
+
and very long text content (only affects libxml2 2.7+)
|
1776 |
+
|
1777 |
+
Other keyword arguments:
|
1778 |
+
|
1779 |
+
- encoding - override the document encoding (note: libiconv encoding name)
|
1780 |
+
- target - a parser target object that will receive the parse events
|
1781 |
+
- schema - an XMLSchema to validate against
|
1782 |
+
|
1783 |
+
Note that you should avoid sharing parsers between threads for performance
|
1784 |
+
reasons.
|
1785 |
+
"""
|
1786 |
+
def __init__(self, *, encoding=None, remove_blank_text=False,
|
1787 |
+
remove_comments=False, remove_pis=False, strip_cdata=True,
|
1788 |
+
no_network=True, target=None, XMLSchema schema=None,
|
1789 |
+
recover=True, compact=True, default_doctype=True,
|
1790 |
+
collect_ids=True, huge_tree=False):
|
1791 |
+
cdef int parse_options
|
1792 |
+
parse_options = _HTML_DEFAULT_PARSE_OPTIONS
|
1793 |
+
if remove_blank_text:
|
1794 |
+
parse_options = parse_options | htmlparser.HTML_PARSE_NOBLANKS
|
1795 |
+
if not recover:
|
1796 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_RECOVER
|
1797 |
+
if not no_network:
|
1798 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_NONET
|
1799 |
+
if not compact:
|
1800 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_COMPACT
|
1801 |
+
if not default_doctype:
|
1802 |
+
parse_options = parse_options ^ htmlparser.HTML_PARSE_NODEFDTD
|
1803 |
+
if huge_tree:
|
1804 |
+
parse_options = parse_options | xmlparser.XML_PARSE_HUGE
|
1805 |
+
|
1806 |
+
_BaseParser.__init__(self, parse_options, True, schema,
|
1807 |
+
remove_comments, remove_pis, strip_cdata,
|
1808 |
+
collect_ids, target, encoding)
|
1809 |
+
|
1810 |
+
|
1811 |
+
cdef HTMLParser __DEFAULT_HTML_PARSER
|
1812 |
+
__DEFAULT_HTML_PARSER = HTMLParser()
|
1813 |
+
|
1814 |
+
|
1815 |
+
cdef class HTMLPullParser(HTMLParser):
|
1816 |
+
"""HTMLPullParser(self, events=None, *, tag=None, base_url=None, **kwargs)
|
1817 |
+
|
1818 |
+
HTML parser that collects parse events in an iterator.
|
1819 |
+
|
1820 |
+
The collected events are the same as for iterparse(), but the
|
1821 |
+
parser itself is non-blocking in the sense that it receives
|
1822 |
+
data chunks incrementally through its .feed() method, instead
|
1823 |
+
of reading them directly from a file(-like) object all by itself.
|
1824 |
+
|
1825 |
+
By default, it collects Element end events. To change that,
|
1826 |
+
pass any subset of the available events into the ``events``
|
1827 |
+
argument: ``'start'``, ``'end'``, ``'start-ns'``,
|
1828 |
+
``'end-ns'``, ``'comment'``, ``'pi'``.
|
1829 |
+
|
1830 |
+
To support loading external dependencies relative to the input
|
1831 |
+
source, you can pass the ``base_url``.
|
1832 |
+
"""
|
1833 |
+
def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
|
1834 |
+
HTMLParser.__init__(self, **kwargs)
|
1835 |
+
if events is None:
|
1836 |
+
events = ('end',)
|
1837 |
+
self._setBaseURL(base_url)
|
1838 |
+
self._collectEvents(events, tag)
|
1839 |
+
|
1840 |
+
def read_events(self):
|
1841 |
+
return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
|
1842 |
+
|
1843 |
+
|
1844 |
+
############################################################
|
1845 |
+
## helper functions for document creation
|
1846 |
+
############################################################
|
1847 |
+
|
1848 |
+
cdef xmlDoc* _parseDoc(text, filename, _BaseParser parser) except NULL:
|
1849 |
+
cdef char* c_filename
|
1850 |
+
cdef char* c_text
|
1851 |
+
cdef Py_ssize_t c_len
|
1852 |
+
if parser is None:
|
1853 |
+
parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
|
1854 |
+
if not filename:
|
1855 |
+
c_filename = NULL
|
1856 |
+
else:
|
1857 |
+
filename_utf = _encodeFilenameUTF8(filename)
|
1858 |
+
c_filename = _cstr(filename_utf)
|
1859 |
+
if isinstance(text, unicode):
|
1860 |
+
if python.PyUnicode_IS_READY(text):
|
1861 |
+
# PEP-393 Unicode string
|
1862 |
+
c_len = python.PyUnicode_GET_LENGTH(text) * python.PyUnicode_KIND(text)
|
1863 |
+
else:
|
1864 |
+
# old Py_UNICODE string
|
1865 |
+
c_len = python.PyUnicode_GET_DATA_SIZE(text)
|
1866 |
+
if c_len > limits.INT_MAX:
|
1867 |
+
return (<_BaseParser>parser)._parseDocFromFilelike(
|
1868 |
+
StringIO(text), filename, None)
|
1869 |
+
return (<_BaseParser>parser)._parseUnicodeDoc(text, c_filename)
|
1870 |
+
else:
|
1871 |
+
c_len = python.PyBytes_GET_SIZE(text)
|
1872 |
+
if c_len > limits.INT_MAX:
|
1873 |
+
return (<_BaseParser>parser)._parseDocFromFilelike(
|
1874 |
+
BytesIO(text), filename, None)
|
1875 |
+
c_text = _cstr(text)
|
1876 |
+
return (<_BaseParser>parser)._parseDoc(c_text, c_len, c_filename)
|
1877 |
+
|
1878 |
+
cdef xmlDoc* _parseDocFromFile(filename8, _BaseParser parser) except NULL:
|
1879 |
+
if parser is None:
|
1880 |
+
parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
|
1881 |
+
return (<_BaseParser>parser)._parseDocFromFile(_cstr(filename8))
|
1882 |
+
|
1883 |
+
cdef xmlDoc* _parseDocFromFilelike(source, filename,
|
1884 |
+
_BaseParser parser) except NULL:
|
1885 |
+
if parser is None:
|
1886 |
+
parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
|
1887 |
+
return (<_BaseParser>parser)._parseDocFromFilelike(source, filename, None)
|
1888 |
+
|
1889 |
+
cdef xmlDoc* _newXMLDoc() except NULL:
|
1890 |
+
cdef xmlDoc* result
|
1891 |
+
result = tree.xmlNewDoc(NULL)
|
1892 |
+
if result is NULL:
|
1893 |
+
raise MemoryError()
|
1894 |
+
if result.encoding is NULL:
|
1895 |
+
result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
|
1896 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1897 |
+
return result
|
1898 |
+
|
1899 |
+
cdef xmlDoc* _newHTMLDoc() except NULL:
|
1900 |
+
cdef xmlDoc* result
|
1901 |
+
result = tree.htmlNewDoc(NULL, NULL)
|
1902 |
+
if result is NULL:
|
1903 |
+
raise MemoryError()
|
1904 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1905 |
+
return result
|
1906 |
+
|
1907 |
+
cdef xmlDoc* _copyDoc(xmlDoc* c_doc, int recursive) except NULL:
|
1908 |
+
cdef xmlDoc* result
|
1909 |
+
if recursive:
|
1910 |
+
with nogil:
|
1911 |
+
result = tree.xmlCopyDoc(c_doc, recursive)
|
1912 |
+
else:
|
1913 |
+
result = tree.xmlCopyDoc(c_doc, 0)
|
1914 |
+
if result is NULL:
|
1915 |
+
raise MemoryError()
|
1916 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1917 |
+
return result
|
1918 |
+
|
1919 |
+
cdef xmlDoc* _copyDocRoot(xmlDoc* c_doc, xmlNode* c_new_root) except NULL:
|
1920 |
+
"Recursively copy the document and make c_new_root the new root node."
|
1921 |
+
cdef xmlDoc* result
|
1922 |
+
cdef xmlNode* c_node
|
1923 |
+
result = tree.xmlCopyDoc(c_doc, 0) # non recursive
|
1924 |
+
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
|
1925 |
+
with nogil:
|
1926 |
+
c_node = tree.xmlDocCopyNode(c_new_root, result, 1) # recursive
|
1927 |
+
if c_node is NULL:
|
1928 |
+
raise MemoryError()
|
1929 |
+
tree.xmlDocSetRootElement(result, c_node)
|
1930 |
+
_copyTail(c_new_root.next, c_node)
|
1931 |
+
return result
|
1932 |
+
|
1933 |
+
cdef xmlNode* _copyNodeToDoc(xmlNode* c_node, xmlDoc* c_doc) except NULL:
|
1934 |
+
"Recursively copy the element into the document. c_doc is not modified."
|
1935 |
+
cdef xmlNode* c_root
|
1936 |
+
c_root = tree.xmlDocCopyNode(c_node, c_doc, 1) # recursive
|
1937 |
+
if c_root is NULL:
|
1938 |
+
raise MemoryError()
|
1939 |
+
_copyTail(c_node.next, c_root)
|
1940 |
+
return c_root
|
1941 |
+
|
1942 |
+
|
1943 |
+
############################################################
|
1944 |
+
## API level helper functions for _Document creation
|
1945 |
+
############################################################
|
1946 |
+
|
1947 |
+
cdef _Document _parseDocument(source, _BaseParser parser, base_url):
|
1948 |
+
cdef _Document doc
|
1949 |
+
source = _getFSPathOrObject(source)
|
1950 |
+
if _isString(source):
|
1951 |
+
# parse the file directly from the filesystem
|
1952 |
+
doc = _parseDocumentFromURL(_encodeFilename(source), parser)
|
1953 |
+
# fix base URL if requested
|
1954 |
+
if base_url is not None:
|
1955 |
+
base_url = _encodeFilenameUTF8(base_url)
|
1956 |
+
if doc._c_doc.URL is not NULL:
|
1957 |
+
tree.xmlFree(<char*>doc._c_doc.URL)
|
1958 |
+
doc._c_doc.URL = tree.xmlStrdup(_xcstr(base_url))
|
1959 |
+
return doc
|
1960 |
+
|
1961 |
+
if base_url is not None:
|
1962 |
+
url = base_url
|
1963 |
+
else:
|
1964 |
+
url = _getFilenameForFile(source)
|
1965 |
+
|
1966 |
+
if hasattr(source, 'getvalue') and hasattr(source, 'tell'):
|
1967 |
+
# StringIO - reading from start?
|
1968 |
+
if source.tell() == 0:
|
1969 |
+
return _parseMemoryDocument(source.getvalue(), url, parser)
|
1970 |
+
|
1971 |
+
# Support for file-like objects (urlgrabber.urlopen, ...)
|
1972 |
+
if hasattr(source, 'read'):
|
1973 |
+
return _parseFilelikeDocument(source, url, parser)
|
1974 |
+
|
1975 |
+
raise TypeError, f"cannot parse from '{python._fqtypename(source).decode('UTF-8')}'"
|
1976 |
+
|
1977 |
+
cdef _Document _parseDocumentFromURL(url, _BaseParser parser):
|
1978 |
+
c_doc = _parseDocFromFile(url, parser)
|
1979 |
+
return _documentFactory(c_doc, parser)
|
1980 |
+
|
1981 |
+
cdef _Document _parseMemoryDocument(text, url, _BaseParser parser):
|
1982 |
+
if isinstance(text, unicode):
|
1983 |
+
if _hasEncodingDeclaration(text):
|
1984 |
+
raise ValueError(
|
1985 |
+
"Unicode strings with encoding declaration are not supported. "
|
1986 |
+
"Please use bytes input or XML fragments without declaration.")
|
1987 |
+
elif not isinstance(text, bytes):
|
1988 |
+
raise ValueError, "can only parse strings"
|
1989 |
+
c_doc = _parseDoc(text, url, parser)
|
1990 |
+
return _documentFactory(c_doc, parser)
|
1991 |
+
|
1992 |
+
cdef _Document _parseFilelikeDocument(source, url, _BaseParser parser):
|
1993 |
+
c_doc = _parseDocFromFilelike(source, url, parser)
|
1994 |
+
return _documentFactory(c_doc, parser)
|
env-llmeval/lib/python3.10/site-packages/lxml/parsertarget.pxi
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Parser target context (ET target interface)
|
2 |
+
|
3 |
+
cdef object inspect_getargspec
|
4 |
+
try:
|
5 |
+
from inspect import getfullargspec as inspect_getargspec
|
6 |
+
except ImportError:
|
7 |
+
from inspect import getargspec as inspect_getargspec
|
8 |
+
|
9 |
+
|
10 |
+
class _TargetParserResult(Exception):
|
11 |
+
# Admittedly, this is somewhat ugly, but it's the easiest way
|
12 |
+
# to push the Python level parser result through the parser
|
13 |
+
# machinery towards the API level functions
|
14 |
+
def __init__(self, result):
|
15 |
+
self.result = result
|
16 |
+
|
17 |
+
|
18 |
+
@cython.final
|
19 |
+
@cython.internal
|
20 |
+
cdef class _PythonSaxParserTarget(_SaxParserTarget):
|
21 |
+
cdef object _target_start
|
22 |
+
cdef object _target_end
|
23 |
+
cdef object _target_data
|
24 |
+
cdef object _target_start_ns
|
25 |
+
cdef object _target_end_ns
|
26 |
+
cdef object _target_doctype
|
27 |
+
cdef object _target_pi
|
28 |
+
cdef object _target_comment
|
29 |
+
cdef bint _start_takes_nsmap
|
30 |
+
|
31 |
+
def __cinit__(self, target):
|
32 |
+
cdef int event_filter
|
33 |
+
event_filter = 0
|
34 |
+
self._start_takes_nsmap = 0
|
35 |
+
try:
|
36 |
+
self._target_start = target.start
|
37 |
+
if self._target_start is not None:
|
38 |
+
event_filter |= SAX_EVENT_START
|
39 |
+
except AttributeError:
|
40 |
+
pass
|
41 |
+
else:
|
42 |
+
try:
|
43 |
+
arguments = inspect_getargspec(self._target_start)
|
44 |
+
if len(arguments[0]) > 3 or arguments[1] is not None:
|
45 |
+
self._start_takes_nsmap = 1
|
46 |
+
except TypeError:
|
47 |
+
pass
|
48 |
+
try:
|
49 |
+
self._target_end = target.end
|
50 |
+
if self._target_end is not None:
|
51 |
+
event_filter |= SAX_EVENT_END
|
52 |
+
except AttributeError:
|
53 |
+
pass
|
54 |
+
try:
|
55 |
+
self._target_start_ns = target.start_ns
|
56 |
+
if self._target_start_ns is not None:
|
57 |
+
event_filter |= SAX_EVENT_START_NS
|
58 |
+
except AttributeError:
|
59 |
+
pass
|
60 |
+
try:
|
61 |
+
self._target_end_ns = target.end_ns
|
62 |
+
if self._target_end_ns is not None:
|
63 |
+
event_filter |= SAX_EVENT_END_NS
|
64 |
+
except AttributeError:
|
65 |
+
pass
|
66 |
+
try:
|
67 |
+
self._target_data = target.data
|
68 |
+
if self._target_data is not None:
|
69 |
+
event_filter |= SAX_EVENT_DATA
|
70 |
+
except AttributeError:
|
71 |
+
pass
|
72 |
+
try:
|
73 |
+
self._target_doctype = target.doctype
|
74 |
+
if self._target_doctype is not None:
|
75 |
+
event_filter |= SAX_EVENT_DOCTYPE
|
76 |
+
except AttributeError:
|
77 |
+
pass
|
78 |
+
try:
|
79 |
+
self._target_pi = target.pi
|
80 |
+
if self._target_pi is not None:
|
81 |
+
event_filter |= SAX_EVENT_PI
|
82 |
+
except AttributeError:
|
83 |
+
pass
|
84 |
+
try:
|
85 |
+
self._target_comment = target.comment
|
86 |
+
if self._target_comment is not None:
|
87 |
+
event_filter |= SAX_EVENT_COMMENT
|
88 |
+
except AttributeError:
|
89 |
+
pass
|
90 |
+
self._sax_event_filter = event_filter
|
91 |
+
|
92 |
+
cdef _handleSaxStart(self, tag, attrib, nsmap):
|
93 |
+
if self._start_takes_nsmap:
|
94 |
+
return self._target_start(tag, attrib, nsmap)
|
95 |
+
else:
|
96 |
+
return self._target_start(tag, attrib)
|
97 |
+
|
98 |
+
cdef _handleSaxEnd(self, tag):
|
99 |
+
return self._target_end(tag)
|
100 |
+
|
101 |
+
cdef _handleSaxStartNs(self, prefix, uri):
|
102 |
+
return self._target_start_ns(prefix, uri)
|
103 |
+
|
104 |
+
cdef _handleSaxEndNs(self, prefix):
|
105 |
+
return self._target_end_ns(prefix)
|
106 |
+
|
107 |
+
cdef int _handleSaxData(self, data) except -1:
|
108 |
+
self._target_data(data)
|
109 |
+
|
110 |
+
cdef int _handleSaxDoctype(self, root_tag, public_id, system_id) except -1:
|
111 |
+
self._target_doctype(root_tag, public_id, system_id)
|
112 |
+
|
113 |
+
cdef _handleSaxPi(self, target, data):
|
114 |
+
return self._target_pi(target, data)
|
115 |
+
|
116 |
+
cdef _handleSaxComment(self, comment):
|
117 |
+
return self._target_comment(comment)
|
118 |
+
|
119 |
+
|
120 |
+
@cython.final
|
121 |
+
@cython.internal
|
122 |
+
@cython.no_gc_clear # Required because parent class uses it - Cython bug.
|
123 |
+
cdef class _TargetParserContext(_SaxParserContext):
|
124 |
+
"""This class maps SAX2 events to the ET parser target interface.
|
125 |
+
"""
|
126 |
+
cdef object _python_target
|
127 |
+
cdef int _setTarget(self, target) except -1:
|
128 |
+
self._python_target = target
|
129 |
+
if not isinstance(target, _SaxParserTarget) or \
|
130 |
+
hasattr(target, '__dict__'):
|
131 |
+
target = _PythonSaxParserTarget(target)
|
132 |
+
self._setSaxParserTarget(target)
|
133 |
+
return 0
|
134 |
+
|
135 |
+
cdef _ParserContext _copy(self):
|
136 |
+
cdef _TargetParserContext context
|
137 |
+
context = _ParserContext._copy(self)
|
138 |
+
context._setTarget(self._python_target)
|
139 |
+
return context
|
140 |
+
|
141 |
+
cdef void _cleanupTargetParserContext(self, xmlDoc* result) noexcept:
|
142 |
+
if self._c_ctxt.myDoc is not NULL:
|
143 |
+
if self._c_ctxt.myDoc is not result and \
|
144 |
+
self._c_ctxt.myDoc._private is NULL:
|
145 |
+
# no _Document proxy => orphen
|
146 |
+
tree.xmlFreeDoc(self._c_ctxt.myDoc)
|
147 |
+
self._c_ctxt.myDoc = NULL
|
148 |
+
|
149 |
+
cdef object _handleParseResult(self, _BaseParser parser, xmlDoc* result,
|
150 |
+
filename):
|
151 |
+
cdef bint recover
|
152 |
+
recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
|
153 |
+
try:
|
154 |
+
if self._has_raised():
|
155 |
+
self._cleanupTargetParserContext(result)
|
156 |
+
self._raise_if_stored()
|
157 |
+
if not self._c_ctxt.wellFormed and not recover:
|
158 |
+
_raiseParseError(self._c_ctxt, filename, self._error_log)
|
159 |
+
except:
|
160 |
+
self._python_target.close()
|
161 |
+
raise
|
162 |
+
return self._python_target.close()
|
163 |
+
|
164 |
+
cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser,
|
165 |
+
xmlDoc* result, filename) except NULL:
|
166 |
+
cdef bint recover
|
167 |
+
recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
|
168 |
+
if result is not NULL and result._private is NULL:
|
169 |
+
# no _Document proxy => orphen
|
170 |
+
tree.xmlFreeDoc(result)
|
171 |
+
try:
|
172 |
+
self._cleanupTargetParserContext(result)
|
173 |
+
self._raise_if_stored()
|
174 |
+
if not self._c_ctxt.wellFormed and not recover:
|
175 |
+
_raiseParseError(self._c_ctxt, filename, self._error_log)
|
176 |
+
except:
|
177 |
+
self._python_target.close()
|
178 |
+
raise
|
179 |
+
parse_result = self._python_target.close()
|
180 |
+
raise _TargetParserResult(parse_result)
|
env-llmeval/lib/python3.10/site-packages/lxml/proxy.pxi
ADDED
@@ -0,0 +1,619 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Proxy functions and low level node allocation stuff
|
2 |
+
|
3 |
+
# Proxies represent elements, their reference is stored in the C
|
4 |
+
# structure of the respective node to avoid multiple instantiation of
|
5 |
+
# the Python class.
|
6 |
+
|
7 |
+
@cython.linetrace(False)
|
8 |
+
@cython.profile(False)
|
9 |
+
cdef inline _Element getProxy(xmlNode* c_node):
|
10 |
+
"""Get a proxy for a given node.
|
11 |
+
"""
|
12 |
+
#print "getProxy for:", <int>c_node
|
13 |
+
if c_node is not NULL and c_node._private is not NULL:
|
14 |
+
return <_Element>c_node._private
|
15 |
+
else:
|
16 |
+
return None
|
17 |
+
|
18 |
+
|
19 |
+
@cython.linetrace(False)
|
20 |
+
@cython.profile(False)
|
21 |
+
cdef inline bint hasProxy(xmlNode* c_node):
|
22 |
+
if c_node._private is NULL:
|
23 |
+
return False
|
24 |
+
return True
|
25 |
+
|
26 |
+
|
27 |
+
@cython.linetrace(False)
|
28 |
+
@cython.profile(False)
|
29 |
+
cdef inline int _registerProxy(_Element proxy, _Document doc,
|
30 |
+
xmlNode* c_node) except -1:
|
31 |
+
"""Register a proxy and type for the node it's proxying for.
|
32 |
+
"""
|
33 |
+
#print "registering for:", <int>proxy._c_node
|
34 |
+
assert not hasProxy(c_node), "double registering proxy!"
|
35 |
+
proxy._doc = doc
|
36 |
+
proxy._c_node = c_node
|
37 |
+
c_node._private = <void*>proxy
|
38 |
+
return 0
|
39 |
+
|
40 |
+
|
41 |
+
@cython.linetrace(False)
|
42 |
+
@cython.profile(False)
|
43 |
+
cdef inline int _unregisterProxy(_Element proxy) except -1:
|
44 |
+
"""Unregister a proxy for the node it's proxying for.
|
45 |
+
"""
|
46 |
+
cdef xmlNode* c_node = proxy._c_node
|
47 |
+
assert c_node._private is <void*>proxy, "Tried to unregister unknown proxy"
|
48 |
+
c_node._private = NULL
|
49 |
+
return 0
|
50 |
+
|
51 |
+
|
52 |
+
################################################################################
|
53 |
+
# temporarily make a node the root node of its document
|
54 |
+
|
55 |
+
cdef xmlDoc* _fakeRootDoc(xmlDoc* c_base_doc, xmlNode* c_node) except NULL:
|
56 |
+
return _plainFakeRootDoc(c_base_doc, c_node, 1)
|
57 |
+
|
58 |
+
cdef xmlDoc* _plainFakeRootDoc(xmlDoc* c_base_doc, xmlNode* c_node,
|
59 |
+
bint with_siblings) except NULL:
|
60 |
+
# build a temporary document that has the given node as root node
|
61 |
+
# note that copy and original must not be modified during its lifetime!!
|
62 |
+
# always call _destroyFakeDoc() after use!
|
63 |
+
cdef xmlNode* c_child
|
64 |
+
cdef xmlNode* c_root
|
65 |
+
cdef xmlNode* c_new_root
|
66 |
+
cdef xmlDoc* c_doc
|
67 |
+
if with_siblings or (c_node.prev is NULL and c_node.next is NULL):
|
68 |
+
c_root = tree.xmlDocGetRootElement(c_base_doc)
|
69 |
+
if c_root is c_node:
|
70 |
+
# already the root node, no siblings
|
71 |
+
return c_base_doc
|
72 |
+
|
73 |
+
c_doc = _copyDoc(c_base_doc, 0) # non recursive!
|
74 |
+
c_new_root = tree.xmlDocCopyNode(c_node, c_doc, 2) # non recursive!
|
75 |
+
tree.xmlDocSetRootElement(c_doc, c_new_root)
|
76 |
+
_copyParentNamespaces(c_node, c_new_root)
|
77 |
+
|
78 |
+
c_new_root.children = c_node.children
|
79 |
+
c_new_root.last = c_node.last
|
80 |
+
c_new_root.next = c_new_root.prev = NULL
|
81 |
+
|
82 |
+
# store original node
|
83 |
+
c_doc._private = c_node
|
84 |
+
|
85 |
+
# divert parent pointers of children
|
86 |
+
c_child = c_new_root.children
|
87 |
+
while c_child is not NULL:
|
88 |
+
c_child.parent = c_new_root
|
89 |
+
c_child = c_child.next
|
90 |
+
|
91 |
+
c_doc.children = c_new_root
|
92 |
+
return c_doc
|
93 |
+
|
94 |
+
cdef void _destroyFakeDoc(xmlDoc* c_base_doc, xmlDoc* c_doc) noexcept:
|
95 |
+
# delete a temporary document
|
96 |
+
cdef xmlNode* c_child
|
97 |
+
cdef xmlNode* c_parent
|
98 |
+
cdef xmlNode* c_root
|
99 |
+
if c_doc is c_base_doc:
|
100 |
+
return
|
101 |
+
c_root = tree.xmlDocGetRootElement(c_doc)
|
102 |
+
|
103 |
+
# restore parent pointers of children
|
104 |
+
c_parent = <xmlNode*>c_doc._private
|
105 |
+
c_child = c_root.children
|
106 |
+
while c_child is not NULL:
|
107 |
+
c_child.parent = c_parent
|
108 |
+
c_child = c_child.next
|
109 |
+
|
110 |
+
# prevent recursive removal of children
|
111 |
+
c_root.children = c_root.last = NULL
|
112 |
+
tree.xmlFreeDoc(c_doc)
|
113 |
+
|
114 |
+
cdef _Element _fakeDocElementFactory(_Document doc, xmlNode* c_element):
|
115 |
+
"""Special element factory for cases where we need to create a fake
|
116 |
+
root document, but still need to instantiate arbitrary nodes from
|
117 |
+
it. If we instantiate the fake root node, things will turn bad
|
118 |
+
when it's destroyed.
|
119 |
+
|
120 |
+
Instead, if we are asked to instantiate the fake root node, we
|
121 |
+
instantiate the original node instead.
|
122 |
+
"""
|
123 |
+
if c_element.doc is not doc._c_doc:
|
124 |
+
if c_element.doc._private is not NULL:
|
125 |
+
if c_element is c_element.doc.children:
|
126 |
+
c_element = <xmlNode*>c_element.doc._private
|
127 |
+
#assert c_element.type == tree.XML_ELEMENT_NODE
|
128 |
+
return _elementFactory(doc, c_element)
|
129 |
+
|
130 |
+
################################################################################
|
131 |
+
# support for freeing tree elements when proxy objects are destroyed
|
132 |
+
|
133 |
+
cdef int attemptDeallocation(xmlNode* c_node) noexcept:
|
134 |
+
"""Attempt deallocation of c_node (or higher up in tree).
|
135 |
+
"""
|
136 |
+
cdef xmlNode* c_top
|
137 |
+
# could be we actually aren't referring to the tree at all
|
138 |
+
if c_node is NULL:
|
139 |
+
#print "not freeing, node is NULL"
|
140 |
+
return 0
|
141 |
+
c_top = getDeallocationTop(c_node)
|
142 |
+
if c_top is not NULL:
|
143 |
+
#print "freeing:", c_top.name
|
144 |
+
_removeText(c_top.next) # tail
|
145 |
+
tree.xmlFreeNode(c_top)
|
146 |
+
return 1
|
147 |
+
return 0
|
148 |
+
|
149 |
+
cdef xmlNode* getDeallocationTop(xmlNode* c_node) noexcept:
|
150 |
+
"""Return the top of the tree that can be deallocated, or NULL.
|
151 |
+
"""
|
152 |
+
cdef xmlNode* c_next
|
153 |
+
#print "trying to do deallocating:", c_node.type
|
154 |
+
if hasProxy(c_node):
|
155 |
+
#print "Not freeing: proxies still exist"
|
156 |
+
return NULL
|
157 |
+
while c_node.parent is not NULL:
|
158 |
+
c_node = c_node.parent
|
159 |
+
#print "checking:", c_current.type
|
160 |
+
if c_node.type == tree.XML_DOCUMENT_NODE or \
|
161 |
+
c_node.type == tree.XML_HTML_DOCUMENT_NODE:
|
162 |
+
#print "not freeing: still in doc"
|
163 |
+
return NULL
|
164 |
+
# if we're still attached to the document, don't deallocate
|
165 |
+
if hasProxy(c_node):
|
166 |
+
#print "Not freeing: proxies still exist"
|
167 |
+
return NULL
|
168 |
+
# see whether we have children to deallocate
|
169 |
+
if not canDeallocateChildNodes(c_node):
|
170 |
+
return NULL
|
171 |
+
# see whether we have siblings to deallocate
|
172 |
+
c_next = c_node.prev
|
173 |
+
while c_next:
|
174 |
+
if _isElement(c_next):
|
175 |
+
if hasProxy(c_next) or not canDeallocateChildNodes(c_next):
|
176 |
+
return NULL
|
177 |
+
c_next = c_next.prev
|
178 |
+
c_next = c_node.next
|
179 |
+
while c_next:
|
180 |
+
if _isElement(c_next):
|
181 |
+
if hasProxy(c_next) or not canDeallocateChildNodes(c_next):
|
182 |
+
return NULL
|
183 |
+
c_next = c_next.next
|
184 |
+
return c_node
|
185 |
+
|
186 |
+
cdef int canDeallocateChildNodes(xmlNode* c_parent) noexcept:
|
187 |
+
cdef xmlNode* c_node
|
188 |
+
c_node = c_parent.children
|
189 |
+
tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_parent, c_node, 1)
|
190 |
+
if hasProxy(c_node):
|
191 |
+
return 0
|
192 |
+
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
|
193 |
+
return 1
|
194 |
+
|
195 |
+
################################################################################
|
196 |
+
# fix _Document references and namespaces when a node changes documents
|
197 |
+
|
198 |
+
cdef void _copyParentNamespaces(xmlNode* c_from_node, xmlNode* c_to_node) noexcept nogil:
|
199 |
+
"""Copy the namespaces of all ancestors of c_from_node to c_to_node.
|
200 |
+
"""
|
201 |
+
cdef xmlNode* c_parent
|
202 |
+
cdef xmlNs* c_ns
|
203 |
+
cdef xmlNs* c_new_ns
|
204 |
+
cdef int prefix_known
|
205 |
+
c_parent = c_from_node.parent
|
206 |
+
while c_parent and (tree._isElementOrXInclude(c_parent) or
|
207 |
+
c_parent.type == tree.XML_DOCUMENT_NODE):
|
208 |
+
c_new_ns = c_parent.nsDef
|
209 |
+
while c_new_ns:
|
210 |
+
# libxml2 will check if the prefix is already defined
|
211 |
+
tree.xmlNewNs(c_to_node, c_new_ns.href, c_new_ns.prefix)
|
212 |
+
c_new_ns = c_new_ns.next
|
213 |
+
c_parent = c_parent.parent
|
214 |
+
|
215 |
+
|
216 |
+
ctypedef struct _ns_update_map:
|
217 |
+
xmlNs* old
|
218 |
+
xmlNs* new
|
219 |
+
|
220 |
+
|
221 |
+
ctypedef struct _nscache:
|
222 |
+
_ns_update_map* ns_map
|
223 |
+
size_t size
|
224 |
+
size_t last
|
225 |
+
|
226 |
+
|
227 |
+
cdef int _growNsCache(_nscache* c_ns_cache) except -1:
|
228 |
+
cdef _ns_update_map* ns_map_ptr
|
229 |
+
if c_ns_cache.size == 0:
|
230 |
+
c_ns_cache.size = 20
|
231 |
+
else:
|
232 |
+
c_ns_cache.size *= 2
|
233 |
+
ns_map_ptr = <_ns_update_map*> python.lxml_realloc(
|
234 |
+
c_ns_cache.ns_map, c_ns_cache.size, sizeof(_ns_update_map))
|
235 |
+
if not ns_map_ptr:
|
236 |
+
python.lxml_free(c_ns_cache.ns_map)
|
237 |
+
c_ns_cache.ns_map = NULL
|
238 |
+
raise MemoryError()
|
239 |
+
c_ns_cache.ns_map = ns_map_ptr
|
240 |
+
return 0
|
241 |
+
|
242 |
+
|
243 |
+
cdef inline int _appendToNsCache(_nscache* c_ns_cache,
|
244 |
+
xmlNs* c_old_ns, xmlNs* c_new_ns) except -1:
|
245 |
+
if c_ns_cache.last >= c_ns_cache.size:
|
246 |
+
_growNsCache(c_ns_cache)
|
247 |
+
c_ns_cache.ns_map[c_ns_cache.last] = _ns_update_map(old=c_old_ns, new=c_new_ns)
|
248 |
+
c_ns_cache.last += 1
|
249 |
+
|
250 |
+
|
251 |
+
cdef int _stripRedundantNamespaceDeclarations(xmlNode* c_element, _nscache* c_ns_cache,
|
252 |
+
xmlNs** c_del_ns_list) except -1:
|
253 |
+
"""Removes namespace declarations from an element that are already
|
254 |
+
defined in its parents. Does not free the xmlNs's, just prepends
|
255 |
+
them to the c_del_ns_list.
|
256 |
+
"""
|
257 |
+
cdef xmlNs* c_ns
|
258 |
+
cdef xmlNs* c_ns_next
|
259 |
+
cdef xmlNs** c_nsdef
|
260 |
+
# use a xmlNs** to handle assignments to "c_element.nsDef" correctly
|
261 |
+
c_nsdef = &c_element.nsDef
|
262 |
+
while c_nsdef[0] is not NULL:
|
263 |
+
c_ns = tree.xmlSearchNsByHref(
|
264 |
+
c_element.doc, c_element.parent, c_nsdef[0].href)
|
265 |
+
if c_ns is NULL:
|
266 |
+
# new namespace href => keep and cache the ns declaration
|
267 |
+
_appendToNsCache(c_ns_cache, c_nsdef[0], c_nsdef[0])
|
268 |
+
c_nsdef = &c_nsdef[0].next
|
269 |
+
else:
|
270 |
+
# known namespace href => cache mapping and strip old ns
|
271 |
+
_appendToNsCache(c_ns_cache, c_nsdef[0], c_ns)
|
272 |
+
# cut out c_nsdef.next and prepend it to garbage chain
|
273 |
+
c_ns_next = c_nsdef[0].next
|
274 |
+
c_nsdef[0].next = c_del_ns_list[0]
|
275 |
+
c_del_ns_list[0] = c_nsdef[0]
|
276 |
+
c_nsdef[0] = c_ns_next
|
277 |
+
return 0
|
278 |
+
|
279 |
+
|
280 |
+
cdef void _cleanUpFromNamespaceAdaptation(xmlNode* c_start_node,
|
281 |
+
_nscache* c_ns_cache, xmlNs* c_del_ns_list) noexcept:
|
282 |
+
# Try to recover from exceptions with really bad timing. We were in the middle
|
283 |
+
# of ripping out xmlNS-es and likely ran out of memory. Try to fix up the tree
|
284 |
+
# by re-adding the original xmlNs declarations (which might still be used in some
|
285 |
+
# places).
|
286 |
+
if c_ns_cache.ns_map:
|
287 |
+
python.lxml_free(c_ns_cache.ns_map)
|
288 |
+
if c_del_ns_list:
|
289 |
+
if not c_start_node.nsDef:
|
290 |
+
c_start_node.nsDef = c_del_ns_list
|
291 |
+
else:
|
292 |
+
c_ns = c_start_node.nsDef
|
293 |
+
while c_ns.next:
|
294 |
+
c_ns = c_ns.next
|
295 |
+
c_ns.next = c_del_ns_list
|
296 |
+
|
297 |
+
|
298 |
+
cdef int moveNodeToDocument(_Document doc, xmlDoc* c_source_doc,
|
299 |
+
xmlNode* c_element) except -1:
|
300 |
+
"""Fix the xmlNs pointers of a node and its subtree that were moved.
|
301 |
+
|
302 |
+
Originally copied from libxml2's xmlReconciliateNs(). Expects
|
303 |
+
libxml2 doc pointers of node to be correct already, but fixes
|
304 |
+
_Document references.
|
305 |
+
|
306 |
+
For each node in the subtree, we do this:
|
307 |
+
|
308 |
+
1) Remove redundant declarations of namespace that are already
|
309 |
+
defined in its parents.
|
310 |
+
|
311 |
+
2) Replace namespaces that are *not* defined on the node or its
|
312 |
+
parents by the equivalent namespace declarations that *are*
|
313 |
+
defined on the node or its parents (possibly using a different
|
314 |
+
prefix). If a namespace is unknown, declare a new one on the
|
315 |
+
node.
|
316 |
+
|
317 |
+
3) Reassign the names of tags and attribute from the dict of the
|
318 |
+
target document *iff* it is different from the dict used in the
|
319 |
+
source subtree.
|
320 |
+
|
321 |
+
4) Set the Document reference to the new Document (if different).
|
322 |
+
This is done on backtracking to keep the original Document
|
323 |
+
alive as long as possible, until all its elements are updated.
|
324 |
+
|
325 |
+
Note that the namespace declarations are removed from the tree in
|
326 |
+
step 1), but freed only after the complete subtree was traversed
|
327 |
+
and all occurrences were replaced by tree-internal pointers.
|
328 |
+
"""
|
329 |
+
cdef xmlNode* c_start_node
|
330 |
+
cdef xmlNode* c_node
|
331 |
+
cdef xmlDoc* c_doc = doc._c_doc
|
332 |
+
cdef tree.xmlAttr* c_attr
|
333 |
+
cdef char* c_name
|
334 |
+
cdef _nscache c_ns_cache = [NULL, 0, 0]
|
335 |
+
cdef xmlNs* c_del_ns_list = NULL
|
336 |
+
cdef proxy_count = 0
|
337 |
+
|
338 |
+
if not tree._isElementOrXInclude(c_element):
|
339 |
+
return 0
|
340 |
+
|
341 |
+
c_start_node = c_element
|
342 |
+
|
343 |
+
tree.BEGIN_FOR_EACH_FROM(c_element, c_element, 1)
|
344 |
+
if tree._isElementOrXInclude(c_element):
|
345 |
+
if hasProxy(c_element):
|
346 |
+
proxy_count += 1
|
347 |
+
|
348 |
+
# 1) cut out namespaces defined here that are already known by
|
349 |
+
# the ancestors
|
350 |
+
if c_element.nsDef is not NULL:
|
351 |
+
try:
|
352 |
+
_stripRedundantNamespaceDeclarations(c_element, &c_ns_cache, &c_del_ns_list)
|
353 |
+
except:
|
354 |
+
_cleanUpFromNamespaceAdaptation(c_start_node, &c_ns_cache, c_del_ns_list)
|
355 |
+
raise
|
356 |
+
|
357 |
+
# 2) make sure the namespaces of an element and its attributes
|
358 |
+
# are declared in this document (i.e. on the node or its parents)
|
359 |
+
if c_element.ns is not NULL:
|
360 |
+
_fixCNs(doc, c_start_node, c_element, &c_ns_cache, c_del_ns_list)
|
361 |
+
|
362 |
+
c_node = <xmlNode*>c_element.properties
|
363 |
+
while c_node is not NULL:
|
364 |
+
if c_node.ns is not NULL:
|
365 |
+
_fixCNs(doc, c_start_node, c_node, &c_ns_cache, c_del_ns_list)
|
366 |
+
c_node = c_node.next
|
367 |
+
|
368 |
+
tree.END_FOR_EACH_FROM(c_element)
|
369 |
+
|
370 |
+
# free now unused namespace declarations
|
371 |
+
if c_del_ns_list is not NULL:
|
372 |
+
tree.xmlFreeNsList(c_del_ns_list)
|
373 |
+
|
374 |
+
# cleanup
|
375 |
+
if c_ns_cache.ns_map is not NULL:
|
376 |
+
python.lxml_free(c_ns_cache.ns_map)
|
377 |
+
|
378 |
+
# 3) fix the names in the tree if we moved it from a different thread
|
379 |
+
if doc._c_doc.dict is not c_source_doc.dict:
|
380 |
+
fixThreadDictNames(c_start_node, c_source_doc.dict, doc._c_doc.dict)
|
381 |
+
|
382 |
+
# 4) fix _Document references
|
383 |
+
# (and potentially deallocate the source document)
|
384 |
+
if proxy_count > 0:
|
385 |
+
if proxy_count == 1 and c_start_node._private is not NULL:
|
386 |
+
proxy = getProxy(c_start_node)
|
387 |
+
if proxy is not None:
|
388 |
+
if proxy._doc is not doc:
|
389 |
+
proxy._doc = doc
|
390 |
+
else:
|
391 |
+
fixElementDocument(c_start_node, doc, proxy_count)
|
392 |
+
else:
|
393 |
+
fixElementDocument(c_start_node, doc, proxy_count)
|
394 |
+
|
395 |
+
return 0
|
396 |
+
|
397 |
+
|
398 |
+
cdef void _setTreeDoc(xmlNode* c_node, xmlDoc* c_doc) noexcept:
|
399 |
+
"""Adaptation of 'xmlSetTreeDoc()' that deep-fixes the document links iteratively.
|
400 |
+
It avoids https://gitlab.gnome.org/GNOME/libxml2/issues/42
|
401 |
+
"""
|
402 |
+
tree.BEGIN_FOR_EACH_FROM(c_node, c_node, 1)
|
403 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
404 |
+
c_attr = <tree.xmlAttr*>c_node.properties
|
405 |
+
while c_attr:
|
406 |
+
if c_attr.atype == tree.XML_ATTRIBUTE_ID:
|
407 |
+
tree.xmlRemoveID(c_node.doc, c_attr)
|
408 |
+
c_attr.doc = c_doc
|
409 |
+
_fixDocChildren(c_attr.children, c_doc)
|
410 |
+
c_attr = c_attr.next
|
411 |
+
# Set doc link for all nodes, not only elements.
|
412 |
+
c_node.doc = c_doc
|
413 |
+
tree.END_FOR_EACH_FROM(c_node)
|
414 |
+
|
415 |
+
|
416 |
+
cdef inline void _fixDocChildren(xmlNode* c_child, xmlDoc* c_doc) noexcept:
|
417 |
+
while c_child:
|
418 |
+
c_child.doc = c_doc
|
419 |
+
if c_child.children:
|
420 |
+
_fixDocChildren(c_child.children, c_doc)
|
421 |
+
c_child = c_child.next
|
422 |
+
|
423 |
+
|
424 |
+
cdef int _fixCNs(_Document doc, xmlNode* c_start_node, xmlNode* c_node,
|
425 |
+
_nscache* c_ns_cache, xmlNs* c_del_ns_list) except -1:
|
426 |
+
cdef xmlNs* c_ns = NULL
|
427 |
+
cdef bint is_prefixed_attr = (c_node.type == tree.XML_ATTRIBUTE_NODE and c_node.ns.prefix)
|
428 |
+
|
429 |
+
for ns_map in c_ns_cache.ns_map[:c_ns_cache.last]:
|
430 |
+
if c_node.ns is ns_map.old:
|
431 |
+
if is_prefixed_attr and not ns_map.new.prefix:
|
432 |
+
# avoid dropping prefix from attributes
|
433 |
+
continue
|
434 |
+
c_ns = ns_map.new
|
435 |
+
break
|
436 |
+
|
437 |
+
if c_ns:
|
438 |
+
c_node.ns = c_ns
|
439 |
+
else:
|
440 |
+
# not in cache or not acceptable
|
441 |
+
# => find a replacement from this document
|
442 |
+
try:
|
443 |
+
c_ns = doc._findOrBuildNodeNs(
|
444 |
+
c_start_node, c_node.ns.href, c_node.ns.prefix,
|
445 |
+
c_node.type == tree.XML_ATTRIBUTE_NODE)
|
446 |
+
c_node.ns = c_ns
|
447 |
+
_appendToNsCache(c_ns_cache, c_node.ns, c_ns)
|
448 |
+
except:
|
449 |
+
_cleanUpFromNamespaceAdaptation(c_start_node, c_ns_cache, c_del_ns_list)
|
450 |
+
raise
|
451 |
+
return 0
|
452 |
+
|
453 |
+
|
454 |
+
cdef int fixElementDocument(xmlNode* c_element, _Document doc,
|
455 |
+
size_t proxy_count) except -1:
|
456 |
+
cdef xmlNode* c_node = c_element
|
457 |
+
cdef _Element proxy = None # init-to-None required due to fake-loop below
|
458 |
+
tree.BEGIN_FOR_EACH_FROM(c_element, c_node, 1)
|
459 |
+
if c_node._private is not NULL:
|
460 |
+
proxy = getProxy(c_node)
|
461 |
+
if proxy is not None:
|
462 |
+
if proxy._doc is not doc:
|
463 |
+
proxy._doc = doc
|
464 |
+
proxy_count -= 1
|
465 |
+
if proxy_count == 0:
|
466 |
+
return 0
|
467 |
+
tree.END_FOR_EACH_FROM(c_node)
|
468 |
+
|
469 |
+
|
470 |
+
cdef void fixThreadDictNames(xmlNode* c_element,
|
471 |
+
tree.xmlDict* c_src_dict,
|
472 |
+
tree.xmlDict* c_dict) noexcept nogil:
|
473 |
+
# re-assign the names of tags and attributes
|
474 |
+
#
|
475 |
+
# this should only be called when the element is based on a
|
476 |
+
# different libxml2 tag name dictionary
|
477 |
+
if c_element.type == tree.XML_DOCUMENT_NODE or \
|
478 |
+
c_element.type == tree.XML_HTML_DOCUMENT_NODE:
|
479 |
+
# may define "xml" namespace
|
480 |
+
fixThreadDictNsForNode(c_element, c_src_dict, c_dict)
|
481 |
+
if c_element.doc.extSubset:
|
482 |
+
fixThreadDictNamesForDtd(c_element.doc.extSubset, c_src_dict, c_dict)
|
483 |
+
if c_element.doc.intSubset:
|
484 |
+
fixThreadDictNamesForDtd(c_element.doc.intSubset, c_src_dict, c_dict)
|
485 |
+
c_element = c_element.children
|
486 |
+
while c_element is not NULL:
|
487 |
+
fixThreadDictNamesForNode(c_element, c_src_dict, c_dict)
|
488 |
+
c_element = c_element.next
|
489 |
+
elif tree._isElementOrXInclude(c_element):
|
490 |
+
fixThreadDictNamesForNode(c_element, c_src_dict, c_dict)
|
491 |
+
|
492 |
+
|
493 |
+
cdef inline void _fixThreadDictPtr(const_xmlChar** c_ptr,
|
494 |
+
tree.xmlDict* c_src_dict,
|
495 |
+
tree.xmlDict* c_dict) noexcept nogil:
|
496 |
+
c_str = c_ptr[0]
|
497 |
+
if c_str and c_src_dict and tree.xmlDictOwns(c_src_dict, c_str):
|
498 |
+
# return value can be NULL on memory error, but we don't handle that here
|
499 |
+
c_str = tree.xmlDictLookup(c_dict, c_str, -1)
|
500 |
+
if c_str:
|
501 |
+
c_ptr[0] = c_str
|
502 |
+
|
503 |
+
|
504 |
+
cdef void fixThreadDictNamesForNode(xmlNode* c_element,
|
505 |
+
tree.xmlDict* c_src_dict,
|
506 |
+
tree.xmlDict* c_dict) noexcept nogil:
|
507 |
+
cdef xmlNode* c_node = c_element
|
508 |
+
tree.BEGIN_FOR_EACH_FROM(c_element, c_node, 1)
|
509 |
+
if c_node.type in (tree.XML_ELEMENT_NODE, tree.XML_XINCLUDE_START):
|
510 |
+
fixThreadDictNamesForAttributes(
|
511 |
+
c_node.properties, c_src_dict, c_dict)
|
512 |
+
fixThreadDictNsForNode(c_node, c_src_dict, c_dict)
|
513 |
+
_fixThreadDictPtr(&c_node.name, c_src_dict, c_dict)
|
514 |
+
elif c_node.type == tree.XML_TEXT_NODE:
|
515 |
+
# libxml2's SAX2 parser interns some indentation space
|
516 |
+
fixThreadDictContentForNode(c_node, c_src_dict, c_dict)
|
517 |
+
elif c_node.type == tree.XML_COMMENT_NODE:
|
518 |
+
pass # don't touch c_node.name
|
519 |
+
else:
|
520 |
+
_fixThreadDictPtr(&c_node.name, c_src_dict, c_dict)
|
521 |
+
tree.END_FOR_EACH_FROM(c_node)
|
522 |
+
|
523 |
+
|
524 |
+
cdef inline void fixThreadDictNamesForAttributes(tree.xmlAttr* c_attr,
|
525 |
+
tree.xmlDict* c_src_dict,
|
526 |
+
tree.xmlDict* c_dict) noexcept nogil:
|
527 |
+
cdef xmlNode* c_child
|
528 |
+
cdef xmlNode* c_node = <xmlNode*>c_attr
|
529 |
+
while c_node is not NULL:
|
530 |
+
if c_node.type not in (tree.XML_TEXT_NODE, tree.XML_COMMENT_NODE):
|
531 |
+
_fixThreadDictPtr(&c_node.name, c_src_dict, c_dict)
|
532 |
+
# libxml2 keeps some (!) attribute values in the dict
|
533 |
+
c_child = c_node.children
|
534 |
+
while c_child is not NULL:
|
535 |
+
fixThreadDictContentForNode(c_child, c_src_dict, c_dict)
|
536 |
+
c_child = c_child.next
|
537 |
+
c_node = c_node.next
|
538 |
+
|
539 |
+
|
540 |
+
cdef inline void fixThreadDictContentForNode(xmlNode* c_node,
|
541 |
+
tree.xmlDict* c_src_dict,
|
542 |
+
tree.xmlDict* c_dict) noexcept nogil:
|
543 |
+
if c_node.content is not NULL and \
|
544 |
+
c_node.content is not <xmlChar*>&c_node.properties:
|
545 |
+
if tree.xmlDictOwns(c_src_dict, c_node.content):
|
546 |
+
# result can be NULL on memory error, but we don't handle that here
|
547 |
+
c_node.content = <xmlChar*>tree.xmlDictLookup(c_dict, c_node.content, -1)
|
548 |
+
|
549 |
+
|
550 |
+
cdef inline void fixThreadDictNsForNode(xmlNode* c_node,
|
551 |
+
tree.xmlDict* c_src_dict,
|
552 |
+
tree.xmlDict* c_dict) noexcept nogil:
|
553 |
+
cdef xmlNs* c_ns = c_node.nsDef
|
554 |
+
while c_ns is not NULL:
|
555 |
+
_fixThreadDictPtr(&c_ns.href, c_src_dict, c_dict)
|
556 |
+
_fixThreadDictPtr(&c_ns.prefix, c_src_dict, c_dict)
|
557 |
+
c_ns = c_ns.next
|
558 |
+
|
559 |
+
|
560 |
+
cdef void fixThreadDictNamesForDtd(tree.xmlDtd* c_dtd,
|
561 |
+
tree.xmlDict* c_src_dict,
|
562 |
+
tree.xmlDict* c_dict) noexcept nogil:
|
563 |
+
cdef xmlNode* c_node
|
564 |
+
cdef tree.xmlElement* c_element
|
565 |
+
cdef tree.xmlAttribute* c_attribute
|
566 |
+
cdef tree.xmlEntity* c_entity
|
567 |
+
|
568 |
+
c_node = c_dtd.children
|
569 |
+
while c_node:
|
570 |
+
if c_node.type == tree.XML_ELEMENT_DECL:
|
571 |
+
c_element = <tree.xmlElement*>c_node
|
572 |
+
if c_element.content:
|
573 |
+
_fixThreadDictPtr(&c_element.content.name, c_src_dict, c_dict)
|
574 |
+
_fixThreadDictPtr(&c_element.content.prefix, c_src_dict, c_dict)
|
575 |
+
c_attribute = c_element.attributes
|
576 |
+
while c_attribute:
|
577 |
+
_fixThreadDictPtr(&c_attribute.defaultValue, c_src_dict, c_dict)
|
578 |
+
_fixThreadDictPtr(&c_attribute.name, c_src_dict, c_dict)
|
579 |
+
_fixThreadDictPtr(&c_attribute.prefix, c_src_dict, c_dict)
|
580 |
+
_fixThreadDictPtr(&c_attribute.elem, c_src_dict, c_dict)
|
581 |
+
c_attribute = c_attribute.nexth
|
582 |
+
elif c_node.type == tree.XML_ENTITY_DECL:
|
583 |
+
c_entity = <tree.xmlEntity*>c_node
|
584 |
+
_fixThreadDictPtr(&c_entity.name, c_src_dict, c_dict)
|
585 |
+
_fixThreadDictPtr(&c_entity.ExternalID, c_src_dict, c_dict)
|
586 |
+
_fixThreadDictPtr(&c_entity.SystemID, c_src_dict, c_dict)
|
587 |
+
_fixThreadDictPtr(<const_xmlChar**>&c_entity.content, c_src_dict, c_dict)
|
588 |
+
c_node = c_node.next
|
589 |
+
|
590 |
+
|
591 |
+
################################################################################
|
592 |
+
# adopt an xmlDoc from an external libxml2 document source
|
593 |
+
|
594 |
+
cdef _Document _adoptForeignDoc(xmlDoc* c_doc, _BaseParser parser=None, bint is_owned=True):
|
595 |
+
"""Convert and wrap an externally produced xmlDoc for use in lxml.
|
596 |
+
Assures that all '_private' pointers are NULL to prevent accidental
|
597 |
+
dereference into lxml proxy objects.
|
598 |
+
"""
|
599 |
+
if c_doc is NULL:
|
600 |
+
raise ValueError("Illegal document provided: NULL")
|
601 |
+
if c_doc.type not in (tree.XML_DOCUMENT_NODE, tree.XML_HTML_DOCUMENT_NODE):
|
602 |
+
doc_type = c_doc.type
|
603 |
+
if is_owned:
|
604 |
+
tree.xmlFreeDoc(c_doc)
|
605 |
+
raise ValueError(f"Illegal document provided: expected XML or HTML, found {doc_type}")
|
606 |
+
|
607 |
+
cdef xmlNode* c_node = <xmlNode*>c_doc
|
608 |
+
|
609 |
+
if is_owned:
|
610 |
+
tree.BEGIN_FOR_EACH_FROM(<xmlNode*>c_doc, c_node, 1)
|
611 |
+
c_node._private = NULL
|
612 |
+
tree.END_FOR_EACH_FROM(c_node)
|
613 |
+
else:
|
614 |
+
# create a fresh copy that lxml owns
|
615 |
+
c_doc = tree.xmlCopyDoc(c_doc, 1)
|
616 |
+
if c_doc is NULL:
|
617 |
+
raise MemoryError()
|
618 |
+
|
619 |
+
return _documentFactory(c_doc, parser)
|
env-llmeval/lib/python3.10/site-packages/lxml/readonlytree.pxi
ADDED
@@ -0,0 +1,565 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# read-only tree implementation
|
2 |
+
|
3 |
+
@cython.internal
|
4 |
+
cdef class _ReadOnlyProxy:
|
5 |
+
"A read-only proxy class suitable for PIs/Comments (for internal use only!)."
|
6 |
+
cdef bint _free_after_use
|
7 |
+
cdef xmlNode* _c_node
|
8 |
+
cdef _ReadOnlyProxy _source_proxy
|
9 |
+
cdef list _dependent_proxies
|
10 |
+
def __cinit__(self):
|
11 |
+
self._c_node = NULL
|
12 |
+
self._free_after_use = 0
|
13 |
+
|
14 |
+
cdef int _assertNode(self) except -1:
|
15 |
+
"""This is our way of saying: this proxy is invalid!
|
16 |
+
"""
|
17 |
+
if not self._c_node:
|
18 |
+
raise ReferenceError("Proxy invalidated!")
|
19 |
+
return 0
|
20 |
+
|
21 |
+
cdef int _raise_unsupported_type(self) except -1:
|
22 |
+
raise TypeError(f"Unsupported node type: {self._c_node.type}")
|
23 |
+
|
24 |
+
cdef void free_after_use(self) noexcept:
|
25 |
+
"""Should the xmlNode* be freed when releasing the proxy?
|
26 |
+
"""
|
27 |
+
self._free_after_use = 1
|
28 |
+
|
29 |
+
@property
|
30 |
+
def tag(self):
|
31 |
+
"""Element tag
|
32 |
+
"""
|
33 |
+
self._assertNode()
|
34 |
+
if self._c_node.type == tree.XML_ELEMENT_NODE:
|
35 |
+
return _namespacedName(self._c_node)
|
36 |
+
elif self._c_node.type == tree.XML_PI_NODE:
|
37 |
+
return ProcessingInstruction
|
38 |
+
elif self._c_node.type == tree.XML_COMMENT_NODE:
|
39 |
+
return Comment
|
40 |
+
elif self._c_node.type == tree.XML_ENTITY_REF_NODE:
|
41 |
+
return Entity
|
42 |
+
else:
|
43 |
+
self._raise_unsupported_type()
|
44 |
+
|
45 |
+
@property
|
46 |
+
def text(self):
|
47 |
+
"""Text before the first subelement. This is either a string or
|
48 |
+
the value None, if there was no text.
|
49 |
+
"""
|
50 |
+
self._assertNode()
|
51 |
+
if self._c_node.type == tree.XML_ELEMENT_NODE:
|
52 |
+
return _collectText(self._c_node.children)
|
53 |
+
elif self._c_node.type in (tree.XML_PI_NODE,
|
54 |
+
tree.XML_COMMENT_NODE):
|
55 |
+
if self._c_node.content is NULL:
|
56 |
+
return ''
|
57 |
+
else:
|
58 |
+
return funicode(self._c_node.content)
|
59 |
+
elif self._c_node.type == tree.XML_ENTITY_REF_NODE:
|
60 |
+
return f'&{funicode(self._c_node.name)};'
|
61 |
+
else:
|
62 |
+
self._raise_unsupported_type()
|
63 |
+
|
64 |
+
@property
|
65 |
+
def tail(self):
|
66 |
+
"""Text after this element's end tag, but before the next sibling
|
67 |
+
element's start tag. This is either a string or the value None, if
|
68 |
+
there was no text.
|
69 |
+
"""
|
70 |
+
self._assertNode()
|
71 |
+
return _collectText(self._c_node.next)
|
72 |
+
|
73 |
+
@property
|
74 |
+
def sourceline(self):
|
75 |
+
"""Original line number as found by the parser or None if unknown.
|
76 |
+
"""
|
77 |
+
cdef long line
|
78 |
+
self._assertNode()
|
79 |
+
line = tree.xmlGetLineNo(self._c_node)
|
80 |
+
if line > 0:
|
81 |
+
return line
|
82 |
+
else:
|
83 |
+
return None
|
84 |
+
|
85 |
+
def __repr__(self):
|
86 |
+
self._assertNode()
|
87 |
+
if self._c_node.type == tree.XML_ELEMENT_NODE:
|
88 |
+
return "<Element %s at 0x%x>" % (self.tag, id(self))
|
89 |
+
elif self._c_node.type == tree.XML_COMMENT_NODE:
|
90 |
+
return "<!--%s-->" % self.text
|
91 |
+
elif self._c_node.type == tree.XML_ENTITY_NODE:
|
92 |
+
return "&%s;" % funicode(self._c_node.name)
|
93 |
+
elif self._c_node.type == tree.XML_PI_NODE:
|
94 |
+
text = self.text
|
95 |
+
if text:
|
96 |
+
return "<?%s %s?>" % (self.target, text)
|
97 |
+
else:
|
98 |
+
return "<?%s?>" % self.target
|
99 |
+
else:
|
100 |
+
self._raise_unsupported_type()
|
101 |
+
|
102 |
+
def __getitem__(self, x):
|
103 |
+
"""Returns the subelement at the given position or the requested
|
104 |
+
slice.
|
105 |
+
"""
|
106 |
+
cdef xmlNode* c_node = NULL
|
107 |
+
cdef Py_ssize_t step = 0, slicelength = 0
|
108 |
+
cdef Py_ssize_t c, i
|
109 |
+
cdef _node_to_node_function next_element
|
110 |
+
cdef list result
|
111 |
+
self._assertNode()
|
112 |
+
if isinstance(x, slice):
|
113 |
+
# slicing
|
114 |
+
if _isFullSlice(<slice>x):
|
115 |
+
return _collectChildren(self)
|
116 |
+
_findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
|
117 |
+
if c_node is NULL:
|
118 |
+
return []
|
119 |
+
if step > 0:
|
120 |
+
next_element = _nextElement
|
121 |
+
else:
|
122 |
+
step = -step
|
123 |
+
next_element = _previousElement
|
124 |
+
result = []
|
125 |
+
c = 0
|
126 |
+
while c_node is not NULL and c < slicelength:
|
127 |
+
result.append(_newReadOnlyProxy(self._source_proxy, c_node))
|
128 |
+
result.append(_elementFactory(self._doc, c_node))
|
129 |
+
c = c + 1
|
130 |
+
for i from 0 <= i < step:
|
131 |
+
c_node = next_element(c_node)
|
132 |
+
return result
|
133 |
+
else:
|
134 |
+
# indexing
|
135 |
+
c_node = _findChild(self._c_node, x)
|
136 |
+
if c_node is NULL:
|
137 |
+
raise IndexError, "list index out of range"
|
138 |
+
return _newReadOnlyProxy(self._source_proxy, c_node)
|
139 |
+
|
140 |
+
def __len__(self):
|
141 |
+
"""Returns the number of subelements.
|
142 |
+
"""
|
143 |
+
cdef Py_ssize_t c
|
144 |
+
cdef xmlNode* c_node
|
145 |
+
self._assertNode()
|
146 |
+
c = 0
|
147 |
+
c_node = self._c_node.children
|
148 |
+
while c_node is not NULL:
|
149 |
+
if tree._isElement(c_node):
|
150 |
+
c = c + 1
|
151 |
+
c_node = c_node.next
|
152 |
+
return c
|
153 |
+
|
154 |
+
def __bool__(self):
|
155 |
+
cdef xmlNode* c_node
|
156 |
+
self._assertNode()
|
157 |
+
c_node = _findChildBackwards(self._c_node, 0)
|
158 |
+
return c_node != NULL
|
159 |
+
|
160 |
+
def __deepcopy__(self, memo):
|
161 |
+
"__deepcopy__(self, memo)"
|
162 |
+
return self.__copy__()
|
163 |
+
|
164 |
+
cpdef __copy__(self):
|
165 |
+
"__copy__(self)"
|
166 |
+
cdef xmlDoc* c_doc
|
167 |
+
cdef xmlNode* c_node
|
168 |
+
cdef _Document new_doc
|
169 |
+
if self._c_node is NULL:
|
170 |
+
return self
|
171 |
+
c_doc = _copyDocRoot(self._c_node.doc, self._c_node) # recursive
|
172 |
+
new_doc = _documentFactory(c_doc, None)
|
173 |
+
root = new_doc.getroot()
|
174 |
+
if root is not None:
|
175 |
+
return root
|
176 |
+
# Comment/PI
|
177 |
+
c_node = c_doc.children
|
178 |
+
while c_node is not NULL and c_node.type != self._c_node.type:
|
179 |
+
c_node = c_node.next
|
180 |
+
if c_node is NULL:
|
181 |
+
return None
|
182 |
+
return _elementFactory(new_doc, c_node)
|
183 |
+
|
184 |
+
def __iter__(self):
|
185 |
+
return iter(self.getchildren())
|
186 |
+
|
187 |
+
def iterchildren(self, tag=None, *, reversed=False):
|
188 |
+
"""iterchildren(self, tag=None, reversed=False)
|
189 |
+
|
190 |
+
Iterate over the children of this element.
|
191 |
+
"""
|
192 |
+
children = self.getchildren()
|
193 |
+
if tag is not None and tag != '*':
|
194 |
+
children = [ el for el in children if el.tag == tag ]
|
195 |
+
if reversed:
|
196 |
+
children = children[::-1]
|
197 |
+
return iter(children)
|
198 |
+
|
199 |
+
cpdef getchildren(self):
|
200 |
+
"""Returns all subelements. The elements are returned in document
|
201 |
+
order.
|
202 |
+
"""
|
203 |
+
cdef xmlNode* c_node
|
204 |
+
cdef list result
|
205 |
+
self._assertNode()
|
206 |
+
result = []
|
207 |
+
c_node = self._c_node.children
|
208 |
+
while c_node is not NULL:
|
209 |
+
if tree._isElement(c_node):
|
210 |
+
result.append(_newReadOnlyProxy(self._source_proxy, c_node))
|
211 |
+
c_node = c_node.next
|
212 |
+
return result
|
213 |
+
|
214 |
+
def getparent(self):
|
215 |
+
"""Returns the parent of this element or None for the root element.
|
216 |
+
"""
|
217 |
+
cdef xmlNode* c_parent
|
218 |
+
self._assertNode()
|
219 |
+
c_parent = self._c_node.parent
|
220 |
+
if c_parent is NULL or not tree._isElement(c_parent):
|
221 |
+
return None
|
222 |
+
else:
|
223 |
+
return _newReadOnlyProxy(self._source_proxy, c_parent)
|
224 |
+
|
225 |
+
def getnext(self):
|
226 |
+
"""Returns the following sibling of this element or None.
|
227 |
+
"""
|
228 |
+
cdef xmlNode* c_node
|
229 |
+
self._assertNode()
|
230 |
+
c_node = _nextElement(self._c_node)
|
231 |
+
if c_node is not NULL:
|
232 |
+
return _newReadOnlyProxy(self._source_proxy, c_node)
|
233 |
+
return None
|
234 |
+
|
235 |
+
def getprevious(self):
|
236 |
+
"""Returns the preceding sibling of this element or None.
|
237 |
+
"""
|
238 |
+
cdef xmlNode* c_node
|
239 |
+
self._assertNode()
|
240 |
+
c_node = _previousElement(self._c_node)
|
241 |
+
if c_node is not NULL:
|
242 |
+
return _newReadOnlyProxy(self._source_proxy, c_node)
|
243 |
+
return None
|
244 |
+
|
245 |
+
|
246 |
+
@cython.final
|
247 |
+
@cython.internal
|
248 |
+
cdef class _ReadOnlyPIProxy(_ReadOnlyProxy):
|
249 |
+
"""A read-only proxy for processing instructions (for internal use only!)"""
|
250 |
+
@property
|
251 |
+
def target(self):
|
252 |
+
self._assertNode()
|
253 |
+
return funicode(self._c_node.name)
|
254 |
+
|
255 |
+
@cython.final
|
256 |
+
@cython.internal
|
257 |
+
cdef class _ReadOnlyEntityProxy(_ReadOnlyProxy):
|
258 |
+
"""A read-only proxy for entity references (for internal use only!)"""
|
259 |
+
property name:
|
260 |
+
def __get__(self):
|
261 |
+
return funicode(self._c_node.name)
|
262 |
+
|
263 |
+
def __set__(self, value):
|
264 |
+
value_utf = _utf8(value)
|
265 |
+
if '&' in value or ';' in value:
|
266 |
+
raise ValueError(f"Invalid entity name '{value}'")
|
267 |
+
tree.xmlNodeSetName(self._c_node, _xcstr(value_utf))
|
268 |
+
|
269 |
+
@property
|
270 |
+
def text(self):
|
271 |
+
return f'&{funicode(self._c_node.name)};'
|
272 |
+
|
273 |
+
|
274 |
+
@cython.internal
|
275 |
+
cdef class _ReadOnlyElementProxy(_ReadOnlyProxy):
|
276 |
+
"""The main read-only Element proxy class (for internal use only!)."""
|
277 |
+
|
278 |
+
@property
|
279 |
+
def attrib(self):
|
280 |
+
self._assertNode()
|
281 |
+
return dict(_collectAttributes(self._c_node, 3))
|
282 |
+
|
283 |
+
@property
|
284 |
+
def prefix(self):
|
285 |
+
"""Namespace prefix or None.
|
286 |
+
"""
|
287 |
+
self._assertNode()
|
288 |
+
if self._c_node.ns is not NULL:
|
289 |
+
if self._c_node.ns.prefix is not NULL:
|
290 |
+
return funicode(self._c_node.ns.prefix)
|
291 |
+
return None
|
292 |
+
|
293 |
+
@property
|
294 |
+
def nsmap(self):
|
295 |
+
"""Namespace prefix->URI mapping known in the context of this
|
296 |
+
Element. This includes all namespace declarations of the
|
297 |
+
parents.
|
298 |
+
|
299 |
+
Note that changing the returned dict has no effect on the Element.
|
300 |
+
"""
|
301 |
+
self._assertNode()
|
302 |
+
return _build_nsmap(self._c_node)
|
303 |
+
|
304 |
+
def get(self, key, default=None):
|
305 |
+
"""Gets an element attribute.
|
306 |
+
"""
|
307 |
+
self._assertNode()
|
308 |
+
return _getNodeAttributeValue(self._c_node, key, default)
|
309 |
+
|
310 |
+
def keys(self):
|
311 |
+
"""Gets a list of attribute names. The names are returned in an
|
312 |
+
arbitrary order (just like for an ordinary Python dictionary).
|
313 |
+
"""
|
314 |
+
self._assertNode()
|
315 |
+
return _collectAttributes(self._c_node, 1)
|
316 |
+
|
317 |
+
def values(self):
|
318 |
+
"""Gets element attributes, as a sequence. The attributes are returned
|
319 |
+
in an arbitrary order.
|
320 |
+
"""
|
321 |
+
self._assertNode()
|
322 |
+
return _collectAttributes(self._c_node, 2)
|
323 |
+
|
324 |
+
def items(self):
|
325 |
+
"""Gets element attributes, as a sequence. The attributes are returned
|
326 |
+
in an arbitrary order.
|
327 |
+
"""
|
328 |
+
self._assertNode()
|
329 |
+
return _collectAttributes(self._c_node, 3)
|
330 |
+
|
331 |
+
cdef _ReadOnlyProxy _newReadOnlyProxy(
|
332 |
+
_ReadOnlyProxy source_proxy, xmlNode* c_node):
|
333 |
+
cdef _ReadOnlyProxy el
|
334 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
335 |
+
el = _ReadOnlyElementProxy.__new__(_ReadOnlyElementProxy)
|
336 |
+
elif c_node.type == tree.XML_PI_NODE:
|
337 |
+
el = _ReadOnlyPIProxy.__new__(_ReadOnlyPIProxy)
|
338 |
+
elif c_node.type in (tree.XML_COMMENT_NODE,
|
339 |
+
tree.XML_ENTITY_REF_NODE):
|
340 |
+
el = _ReadOnlyProxy.__new__(_ReadOnlyProxy)
|
341 |
+
else:
|
342 |
+
raise TypeError(f"Unsupported element type: {c_node.type}")
|
343 |
+
el._c_node = c_node
|
344 |
+
_initReadOnlyProxy(el, source_proxy)
|
345 |
+
return el
|
346 |
+
|
347 |
+
cdef inline _initReadOnlyProxy(_ReadOnlyProxy el,
|
348 |
+
_ReadOnlyProxy source_proxy):
|
349 |
+
if source_proxy is None:
|
350 |
+
el._source_proxy = el
|
351 |
+
el._dependent_proxies = [el]
|
352 |
+
else:
|
353 |
+
el._source_proxy = source_proxy
|
354 |
+
source_proxy._dependent_proxies.append(el)
|
355 |
+
|
356 |
+
cdef _freeReadOnlyProxies(_ReadOnlyProxy sourceProxy):
|
357 |
+
cdef xmlNode* c_node
|
358 |
+
cdef _ReadOnlyProxy el
|
359 |
+
if sourceProxy is None:
|
360 |
+
return
|
361 |
+
if sourceProxy._dependent_proxies is None:
|
362 |
+
return
|
363 |
+
for el in sourceProxy._dependent_proxies:
|
364 |
+
c_node = el._c_node
|
365 |
+
el._c_node = NULL
|
366 |
+
if el._free_after_use:
|
367 |
+
tree.xmlFreeNode(c_node)
|
368 |
+
del sourceProxy._dependent_proxies[:]
|
369 |
+
|
370 |
+
# opaque wrapper around non-element nodes, e.g. the document node
|
371 |
+
#
|
372 |
+
# This class does not imply any restrictions on modifiability or
|
373 |
+
# read-only status of the node, so use with caution.
|
374 |
+
|
375 |
+
@cython.internal
|
376 |
+
cdef class _OpaqueNodeWrapper:
|
377 |
+
cdef tree.xmlNode* _c_node
|
378 |
+
def __init__(self):
|
379 |
+
raise TypeError, "This type cannot be instantiated from Python"
|
380 |
+
|
381 |
+
@cython.final
|
382 |
+
@cython.internal
|
383 |
+
cdef class _OpaqueDocumentWrapper(_OpaqueNodeWrapper):
|
384 |
+
cdef int _assertNode(self) except -1:
|
385 |
+
"""This is our way of saying: this proxy is invalid!
|
386 |
+
"""
|
387 |
+
assert self._c_node is not NULL, "Proxy invalidated!"
|
388 |
+
return 0
|
389 |
+
|
390 |
+
cpdef append(self, other_element):
|
391 |
+
"""Append a copy of an Element to the list of children.
|
392 |
+
"""
|
393 |
+
cdef xmlNode* c_next
|
394 |
+
cdef xmlNode* c_node
|
395 |
+
self._assertNode()
|
396 |
+
c_node = _roNodeOf(other_element)
|
397 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
398 |
+
if tree.xmlDocGetRootElement(<tree.xmlDoc*>self._c_node) is not NULL:
|
399 |
+
raise ValueError, "cannot append, document already has a root element"
|
400 |
+
elif c_node.type not in (tree.XML_PI_NODE, tree.XML_COMMENT_NODE):
|
401 |
+
raise TypeError, f"unsupported element type for top-level node: {c_node.type}"
|
402 |
+
c_node = _copyNodeToDoc(c_node, <tree.xmlDoc*>self._c_node)
|
403 |
+
c_next = c_node.next
|
404 |
+
tree.xmlAddChild(self._c_node, c_node)
|
405 |
+
_moveTail(c_next, c_node)
|
406 |
+
|
407 |
+
def extend(self, elements):
|
408 |
+
"""Append a copy of all Elements from a sequence to the list of
|
409 |
+
children.
|
410 |
+
"""
|
411 |
+
self._assertNode()
|
412 |
+
for element in elements:
|
413 |
+
self.append(element)
|
414 |
+
|
415 |
+
cdef _OpaqueNodeWrapper _newOpaqueAppendOnlyNodeWrapper(xmlNode* c_node):
|
416 |
+
cdef _OpaqueNodeWrapper node
|
417 |
+
if c_node.type in (tree.XML_DOCUMENT_NODE, tree.XML_HTML_DOCUMENT_NODE):
|
418 |
+
node = _OpaqueDocumentWrapper.__new__(_OpaqueDocumentWrapper)
|
419 |
+
else:
|
420 |
+
node = _OpaqueNodeWrapper.__new__(_OpaqueNodeWrapper)
|
421 |
+
node._c_node = c_node
|
422 |
+
return node
|
423 |
+
|
424 |
+
# element proxies that allow restricted modification
|
425 |
+
|
426 |
+
@cython.internal
|
427 |
+
cdef class _ModifyContentOnlyProxy(_ReadOnlyProxy):
|
428 |
+
"""A read-only proxy that allows changing the text content.
|
429 |
+
"""
|
430 |
+
property text:
|
431 |
+
def __get__(self):
|
432 |
+
self._assertNode()
|
433 |
+
if self._c_node.content is NULL:
|
434 |
+
return ''
|
435 |
+
else:
|
436 |
+
return funicode(self._c_node.content)
|
437 |
+
|
438 |
+
def __set__(self, value):
|
439 |
+
cdef tree.xmlDict* c_dict
|
440 |
+
self._assertNode()
|
441 |
+
if value is None:
|
442 |
+
c_text = <const_xmlChar*>NULL
|
443 |
+
else:
|
444 |
+
value = _utf8(value)
|
445 |
+
c_text = _xcstr(value)
|
446 |
+
tree.xmlNodeSetContent(self._c_node, c_text)
|
447 |
+
|
448 |
+
@cython.final
|
449 |
+
@cython.internal
|
450 |
+
cdef class _ModifyContentOnlyPIProxy(_ModifyContentOnlyProxy):
|
451 |
+
"""A read-only proxy that allows changing the text/target content of a
|
452 |
+
processing instruction.
|
453 |
+
"""
|
454 |
+
property target:
|
455 |
+
def __get__(self):
|
456 |
+
self._assertNode()
|
457 |
+
return funicode(self._c_node.name)
|
458 |
+
|
459 |
+
def __set__(self, value):
|
460 |
+
self._assertNode()
|
461 |
+
value = _utf8(value)
|
462 |
+
c_text = _xcstr(value)
|
463 |
+
tree.xmlNodeSetName(self._c_node, c_text)
|
464 |
+
|
465 |
+
@cython.final
|
466 |
+
@cython.internal
|
467 |
+
cdef class _ModifyContentOnlyEntityProxy(_ModifyContentOnlyProxy):
|
468 |
+
"A read-only proxy for entity references (for internal use only!)"
|
469 |
+
property name:
|
470 |
+
def __get__(self):
|
471 |
+
return funicode(self._c_node.name)
|
472 |
+
|
473 |
+
def __set__(self, value):
|
474 |
+
value = _utf8(value)
|
475 |
+
assert '&' not in value and ';' not in value, \
|
476 |
+
f"Invalid entity name '{value}'"
|
477 |
+
c_text = _xcstr(value)
|
478 |
+
tree.xmlNodeSetName(self._c_node, c_text)
|
479 |
+
|
480 |
+
|
481 |
+
@cython.final
|
482 |
+
@cython.internal
|
483 |
+
cdef class _AppendOnlyElementProxy(_ReadOnlyElementProxy):
|
484 |
+
"""A read-only element that allows adding children and changing the
|
485 |
+
text content (i.e. everything that adds to the subtree).
|
486 |
+
"""
|
487 |
+
cpdef append(self, other_element):
|
488 |
+
"""Append a copy of an Element to the list of children.
|
489 |
+
"""
|
490 |
+
cdef xmlNode* c_next
|
491 |
+
cdef xmlNode* c_node
|
492 |
+
self._assertNode()
|
493 |
+
c_node = _roNodeOf(other_element)
|
494 |
+
c_node = _copyNodeToDoc(c_node, self._c_node.doc)
|
495 |
+
c_next = c_node.next
|
496 |
+
tree.xmlAddChild(self._c_node, c_node)
|
497 |
+
_moveTail(c_next, c_node)
|
498 |
+
|
499 |
+
def extend(self, elements):
|
500 |
+
"""Append a copy of all Elements from a sequence to the list of
|
501 |
+
children.
|
502 |
+
"""
|
503 |
+
self._assertNode()
|
504 |
+
for element in elements:
|
505 |
+
self.append(element)
|
506 |
+
|
507 |
+
property text:
|
508 |
+
"""Text before the first subelement. This is either a string or the
|
509 |
+
value None, if there was no text.
|
510 |
+
"""
|
511 |
+
def __get__(self):
|
512 |
+
self._assertNode()
|
513 |
+
return _collectText(self._c_node.children)
|
514 |
+
|
515 |
+
def __set__(self, value):
|
516 |
+
self._assertNode()
|
517 |
+
if isinstance(value, QName):
|
518 |
+
value = _resolveQNameText(self, value).decode('utf8')
|
519 |
+
_setNodeText(self._c_node, value)
|
520 |
+
|
521 |
+
|
522 |
+
cdef _ReadOnlyProxy _newAppendOnlyProxy(
|
523 |
+
_ReadOnlyProxy source_proxy, xmlNode* c_node):
|
524 |
+
cdef _ReadOnlyProxy el
|
525 |
+
if c_node.type == tree.XML_ELEMENT_NODE:
|
526 |
+
el = _AppendOnlyElementProxy.__new__(_AppendOnlyElementProxy)
|
527 |
+
elif c_node.type == tree.XML_PI_NODE:
|
528 |
+
el = _ModifyContentOnlyPIProxy.__new__(_ModifyContentOnlyPIProxy)
|
529 |
+
elif c_node.type == tree.XML_COMMENT_NODE:
|
530 |
+
el = _ModifyContentOnlyProxy.__new__(_ModifyContentOnlyProxy)
|
531 |
+
else:
|
532 |
+
raise TypeError(f"Unsupported element type: {c_node.type}")
|
533 |
+
el._c_node = c_node
|
534 |
+
_initReadOnlyProxy(el, source_proxy)
|
535 |
+
return el
|
536 |
+
|
537 |
+
cdef xmlNode* _roNodeOf(element) except NULL:
|
538 |
+
cdef xmlNode* c_node
|
539 |
+
if isinstance(element, _Element):
|
540 |
+
c_node = (<_Element>element)._c_node
|
541 |
+
elif isinstance(element, _ReadOnlyProxy):
|
542 |
+
c_node = (<_ReadOnlyProxy>element)._c_node
|
543 |
+
elif isinstance(element, _OpaqueNodeWrapper):
|
544 |
+
c_node = (<_OpaqueNodeWrapper>element)._c_node
|
545 |
+
else:
|
546 |
+
raise TypeError, f"invalid argument type {type(element)}"
|
547 |
+
|
548 |
+
if c_node is NULL:
|
549 |
+
raise TypeError, "invalid element"
|
550 |
+
return c_node
|
551 |
+
|
552 |
+
cdef xmlNode* _nonRoNodeOf(element) except NULL:
|
553 |
+
cdef xmlNode* c_node
|
554 |
+
if isinstance(element, _Element):
|
555 |
+
c_node = (<_Element>element)._c_node
|
556 |
+
elif isinstance(element, _AppendOnlyElementProxy):
|
557 |
+
c_node = (<_AppendOnlyElementProxy>element)._c_node
|
558 |
+
elif isinstance(element, _OpaqueNodeWrapper):
|
559 |
+
c_node = (<_OpaqueNodeWrapper>element)._c_node
|
560 |
+
else:
|
561 |
+
raise TypeError, f"invalid argument type {type(element)}"
|
562 |
+
|
563 |
+
if c_node is NULL:
|
564 |
+
raise TypeError, "invalid element"
|
565 |
+
return c_node
|
env-llmeval/lib/python3.10/site-packages/lxml/relaxng.pxi
ADDED
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# support for RelaxNG validation
|
2 |
+
from lxml.includes cimport relaxng
|
3 |
+
|
4 |
+
cdef object _rnc2rng
|
5 |
+
try:
|
6 |
+
import rnc2rng as _rnc2rng
|
7 |
+
except ImportError:
|
8 |
+
_rnc2rng = None
|
9 |
+
|
10 |
+
|
11 |
+
cdef int _require_rnc2rng() except -1:
|
12 |
+
if _rnc2rng is None:
|
13 |
+
raise RelaxNGParseError(
|
14 |
+
'compact syntax not supported (please install rnc2rng)')
|
15 |
+
return 0
|
16 |
+
|
17 |
+
|
18 |
+
cdef class RelaxNGError(LxmlError):
|
19 |
+
"""Base class for RelaxNG errors.
|
20 |
+
"""
|
21 |
+
|
22 |
+
cdef class RelaxNGParseError(RelaxNGError):
|
23 |
+
"""Error while parsing an XML document as RelaxNG.
|
24 |
+
"""
|
25 |
+
|
26 |
+
cdef class RelaxNGValidateError(RelaxNGError):
|
27 |
+
"""Error while validating an XML document with a RelaxNG schema.
|
28 |
+
"""
|
29 |
+
|
30 |
+
|
31 |
+
################################################################################
|
32 |
+
# RelaxNG
|
33 |
+
|
34 |
+
cdef class RelaxNG(_Validator):
|
35 |
+
"""RelaxNG(self, etree=None, file=None)
|
36 |
+
Turn a document into a Relax NG validator.
|
37 |
+
|
38 |
+
Either pass a schema as Element or ElementTree, or pass a file or
|
39 |
+
filename through the ``file`` keyword argument.
|
40 |
+
"""
|
41 |
+
cdef relaxng.xmlRelaxNG* _c_schema
|
42 |
+
def __cinit__(self):
|
43 |
+
self._c_schema = NULL
|
44 |
+
|
45 |
+
def __init__(self, etree=None, *, file=None):
|
46 |
+
cdef _Document doc
|
47 |
+
cdef _Element root_node
|
48 |
+
cdef xmlDoc* fake_c_doc = NULL
|
49 |
+
cdef relaxng.xmlRelaxNGParserCtxt* parser_ctxt = NULL
|
50 |
+
_Validator.__init__(self)
|
51 |
+
if etree is not None:
|
52 |
+
doc = _documentOrRaise(etree)
|
53 |
+
root_node = _rootNodeOrRaise(etree)
|
54 |
+
fake_c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
|
55 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(fake_c_doc)
|
56 |
+
elif file is not None:
|
57 |
+
if _isString(file):
|
58 |
+
if file[-4:].lower() == '.rnc':
|
59 |
+
_require_rnc2rng()
|
60 |
+
rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file)))
|
61 |
+
doc = _parseMemoryDocument(rng_data_utf8, parser=None, url=file)
|
62 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
|
63 |
+
else:
|
64 |
+
doc = None
|
65 |
+
filename = _encodeFilename(file)
|
66 |
+
with self._error_log:
|
67 |
+
orig_loader = _register_document_loader()
|
68 |
+
parser_ctxt = relaxng.xmlRelaxNGNewParserCtxt(_cstr(filename))
|
69 |
+
_reset_document_loader(orig_loader)
|
70 |
+
elif (_getFilenameForFile(file) or '')[-4:].lower() == '.rnc':
|
71 |
+
_require_rnc2rng()
|
72 |
+
rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file)))
|
73 |
+
doc = _parseMemoryDocument(
|
74 |
+
rng_data_utf8, parser=None, url=_getFilenameForFile(file))
|
75 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
|
76 |
+
else:
|
77 |
+
doc = _parseDocument(file, parser=None, base_url=None)
|
78 |
+
parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
|
79 |
+
else:
|
80 |
+
raise RelaxNGParseError, "No tree or file given"
|
81 |
+
|
82 |
+
if parser_ctxt is NULL:
|
83 |
+
if fake_c_doc is not NULL:
|
84 |
+
_destroyFakeDoc(doc._c_doc, fake_c_doc)
|
85 |
+
raise RelaxNGParseError(
|
86 |
+
self._error_log._buildExceptionMessage(
|
87 |
+
"Document is not parsable as Relax NG"),
|
88 |
+
self._error_log)
|
89 |
+
|
90 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
91 |
+
relaxng.xmlRelaxNGSetParserStructuredErrors(
|
92 |
+
parser_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
|
93 |
+
_connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGP)
|
94 |
+
self._c_schema = relaxng.xmlRelaxNGParse(parser_ctxt)
|
95 |
+
_connectGenericErrorLog(None)
|
96 |
+
|
97 |
+
relaxng.xmlRelaxNGFreeParserCtxt(parser_ctxt)
|
98 |
+
if self._c_schema is NULL:
|
99 |
+
if fake_c_doc is not NULL:
|
100 |
+
_destroyFakeDoc(doc._c_doc, fake_c_doc)
|
101 |
+
raise RelaxNGParseError(
|
102 |
+
self._error_log._buildExceptionMessage(
|
103 |
+
"Document is not valid Relax NG"),
|
104 |
+
self._error_log)
|
105 |
+
if fake_c_doc is not NULL:
|
106 |
+
_destroyFakeDoc(doc._c_doc, fake_c_doc)
|
107 |
+
|
108 |
+
def __dealloc__(self):
|
109 |
+
relaxng.xmlRelaxNGFree(self._c_schema)
|
110 |
+
|
111 |
+
def __call__(self, etree):
|
112 |
+
"""__call__(self, etree)
|
113 |
+
|
114 |
+
Validate doc using Relax NG.
|
115 |
+
|
116 |
+
Returns true if document is valid, false if not."""
|
117 |
+
cdef _Document doc
|
118 |
+
cdef _Element root_node
|
119 |
+
cdef xmlDoc* c_doc
|
120 |
+
cdef relaxng.xmlRelaxNGValidCtxt* valid_ctxt
|
121 |
+
cdef int ret
|
122 |
+
|
123 |
+
assert self._c_schema is not NULL, "RelaxNG instance not initialised"
|
124 |
+
doc = _documentOrRaise(etree)
|
125 |
+
root_node = _rootNodeOrRaise(etree)
|
126 |
+
|
127 |
+
valid_ctxt = relaxng.xmlRelaxNGNewValidCtxt(self._c_schema)
|
128 |
+
if valid_ctxt is NULL:
|
129 |
+
raise MemoryError()
|
130 |
+
|
131 |
+
try:
|
132 |
+
self._error_log.clear()
|
133 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
134 |
+
relaxng.xmlRelaxNGSetValidStructuredErrors(
|
135 |
+
valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
|
136 |
+
_connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGV)
|
137 |
+
c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
|
138 |
+
with nogil:
|
139 |
+
ret = relaxng.xmlRelaxNGValidateDoc(valid_ctxt, c_doc)
|
140 |
+
_destroyFakeDoc(doc._c_doc, c_doc)
|
141 |
+
finally:
|
142 |
+
_connectGenericErrorLog(None)
|
143 |
+
relaxng.xmlRelaxNGFreeValidCtxt(valid_ctxt)
|
144 |
+
|
145 |
+
if ret == -1:
|
146 |
+
raise RelaxNGValidateError(
|
147 |
+
"Internal error in Relax NG validation",
|
148 |
+
self._error_log)
|
149 |
+
if ret == 0:
|
150 |
+
return True
|
151 |
+
else:
|
152 |
+
return False
|
153 |
+
|
154 |
+
@classmethod
|
155 |
+
def from_rnc_string(cls, src, base_url=None):
|
156 |
+
"""Parse a RelaxNG schema in compact syntax from a text string
|
157 |
+
|
158 |
+
Requires the rnc2rng package to be installed.
|
159 |
+
|
160 |
+
Passing the source URL or file path of the source as 'base_url'
|
161 |
+
will enable resolving resource references relative to the source.
|
162 |
+
"""
|
163 |
+
_require_rnc2rng()
|
164 |
+
rng_str = utf8(_rnc2rng.dumps(_rnc2rng.loads(src)))
|
165 |
+
return cls(_parseMemoryDocument(rng_str, parser=None, url=base_url))
|
env-llmeval/lib/python3.10/site-packages/lxml/sax.cpython-310-x86_64-linux-gnu.so
ADDED
Binary file (186 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/lxml/sax.py
ADDED
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cython: language_level=2
|
2 |
+
|
3 |
+
"""
|
4 |
+
SAX-based adapter to copy trees from/to the Python standard library.
|
5 |
+
|
6 |
+
Use the `ElementTreeContentHandler` class to build an ElementTree from
|
7 |
+
SAX events.
|
8 |
+
|
9 |
+
Use the `ElementTreeProducer` class or the `saxify()` function to fire
|
10 |
+
the SAX events of an ElementTree against a SAX ContentHandler.
|
11 |
+
|
12 |
+
See https://lxml.de/sax.html
|
13 |
+
"""
|
14 |
+
|
15 |
+
|
16 |
+
from xml.sax.handler import ContentHandler
|
17 |
+
from lxml import etree
|
18 |
+
from lxml.etree import ElementTree, SubElement
|
19 |
+
from lxml.etree import Comment, ProcessingInstruction
|
20 |
+
|
21 |
+
|
22 |
+
class SaxError(etree.LxmlError):
|
23 |
+
"""General SAX error.
|
24 |
+
"""
|
25 |
+
|
26 |
+
|
27 |
+
def _getNsTag(tag):
|
28 |
+
if tag[0] == '{':
|
29 |
+
return tuple(tag[1:].split('}', 1))
|
30 |
+
else:
|
31 |
+
return None, tag
|
32 |
+
|
33 |
+
|
34 |
+
class ElementTreeContentHandler(ContentHandler):
|
35 |
+
"""Build an lxml ElementTree from SAX events.
|
36 |
+
"""
|
37 |
+
def __init__(self, makeelement=None):
|
38 |
+
ContentHandler.__init__(self)
|
39 |
+
self._root = None
|
40 |
+
self._root_siblings = []
|
41 |
+
self._element_stack = []
|
42 |
+
self._default_ns = None
|
43 |
+
self._ns_mapping = { None : [None] }
|
44 |
+
self._new_mappings = {}
|
45 |
+
if makeelement is None:
|
46 |
+
makeelement = etree.Element
|
47 |
+
self._makeelement = makeelement
|
48 |
+
|
49 |
+
def _get_etree(self):
|
50 |
+
"Contains the generated ElementTree after parsing is finished."
|
51 |
+
return ElementTree(self._root)
|
52 |
+
|
53 |
+
etree = property(_get_etree, doc=_get_etree.__doc__)
|
54 |
+
|
55 |
+
def setDocumentLocator(self, locator):
|
56 |
+
pass
|
57 |
+
|
58 |
+
def startDocument(self):
|
59 |
+
pass
|
60 |
+
|
61 |
+
def endDocument(self):
|
62 |
+
pass
|
63 |
+
|
64 |
+
def startPrefixMapping(self, prefix, uri):
|
65 |
+
self._new_mappings[prefix] = uri
|
66 |
+
try:
|
67 |
+
self._ns_mapping[prefix].append(uri)
|
68 |
+
except KeyError:
|
69 |
+
self._ns_mapping[prefix] = [uri]
|
70 |
+
if prefix is None:
|
71 |
+
self._default_ns = uri
|
72 |
+
|
73 |
+
def endPrefixMapping(self, prefix):
|
74 |
+
ns_uri_list = self._ns_mapping[prefix]
|
75 |
+
ns_uri_list.pop()
|
76 |
+
if prefix is None:
|
77 |
+
self._default_ns = ns_uri_list[-1]
|
78 |
+
|
79 |
+
def _buildTag(self, ns_name_tuple):
|
80 |
+
ns_uri, local_name = ns_name_tuple
|
81 |
+
if ns_uri:
|
82 |
+
el_tag = "{%s}%s" % ns_name_tuple
|
83 |
+
elif self._default_ns:
|
84 |
+
el_tag = "{%s}%s" % (self._default_ns, local_name)
|
85 |
+
else:
|
86 |
+
el_tag = local_name
|
87 |
+
return el_tag
|
88 |
+
|
89 |
+
def startElementNS(self, ns_name, qname, attributes=None):
|
90 |
+
el_name = self._buildTag(ns_name)
|
91 |
+
if attributes:
|
92 |
+
attrs = {}
|
93 |
+
try:
|
94 |
+
iter_attributes = attributes.iteritems()
|
95 |
+
except AttributeError:
|
96 |
+
iter_attributes = attributes.items()
|
97 |
+
|
98 |
+
for name_tuple, value in iter_attributes:
|
99 |
+
if name_tuple[0]:
|
100 |
+
attr_name = "{%s}%s" % name_tuple
|
101 |
+
else:
|
102 |
+
attr_name = name_tuple[1]
|
103 |
+
attrs[attr_name] = value
|
104 |
+
else:
|
105 |
+
attrs = None
|
106 |
+
|
107 |
+
element_stack = self._element_stack
|
108 |
+
if self._root is None:
|
109 |
+
element = self._root = \
|
110 |
+
self._makeelement(el_name, attrs, self._new_mappings)
|
111 |
+
if self._root_siblings and hasattr(element, 'addprevious'):
|
112 |
+
for sibling in self._root_siblings:
|
113 |
+
element.addprevious(sibling)
|
114 |
+
del self._root_siblings[:]
|
115 |
+
else:
|
116 |
+
element = SubElement(element_stack[-1], el_name,
|
117 |
+
attrs, self._new_mappings)
|
118 |
+
element_stack.append(element)
|
119 |
+
|
120 |
+
self._new_mappings.clear()
|
121 |
+
|
122 |
+
def processingInstruction(self, target, data):
|
123 |
+
pi = ProcessingInstruction(target, data)
|
124 |
+
if self._root is None:
|
125 |
+
self._root_siblings.append(pi)
|
126 |
+
else:
|
127 |
+
self._element_stack[-1].append(pi)
|
128 |
+
|
129 |
+
def endElementNS(self, ns_name, qname):
|
130 |
+
element = self._element_stack.pop()
|
131 |
+
el_tag = self._buildTag(ns_name)
|
132 |
+
if el_tag != element.tag:
|
133 |
+
raise SaxError("Unexpected element closed: " + el_tag)
|
134 |
+
|
135 |
+
def startElement(self, name, attributes=None):
|
136 |
+
if attributes:
|
137 |
+
attributes = {(None, k): v for k, v in attributes.items()}
|
138 |
+
self.startElementNS((None, name), name, attributes)
|
139 |
+
|
140 |
+
def endElement(self, name):
|
141 |
+
self.endElementNS((None, name), name)
|
142 |
+
|
143 |
+
def characters(self, data):
|
144 |
+
last_element = self._element_stack[-1]
|
145 |
+
try:
|
146 |
+
# if there already is a child element, we must append to its tail
|
147 |
+
last_element = last_element[-1]
|
148 |
+
last_element.tail = (last_element.tail or '') + data
|
149 |
+
except IndexError:
|
150 |
+
# otherwise: append to the text
|
151 |
+
last_element.text = (last_element.text or '') + data
|
152 |
+
|
153 |
+
ignorableWhitespace = characters
|
154 |
+
|
155 |
+
|
156 |
+
class ElementTreeProducer:
|
157 |
+
"""Produces SAX events for an element and children.
|
158 |
+
"""
|
159 |
+
def __init__(self, element_or_tree, content_handler):
|
160 |
+
try:
|
161 |
+
element = element_or_tree.getroot()
|
162 |
+
except AttributeError:
|
163 |
+
element = element_or_tree
|
164 |
+
self._element = element
|
165 |
+
self._content_handler = content_handler
|
166 |
+
from xml.sax.xmlreader import AttributesNSImpl as attr_class
|
167 |
+
self._attr_class = attr_class
|
168 |
+
self._empty_attributes = attr_class({}, {})
|
169 |
+
|
170 |
+
def saxify(self):
|
171 |
+
self._content_handler.startDocument()
|
172 |
+
|
173 |
+
element = self._element
|
174 |
+
if hasattr(element, 'getprevious'):
|
175 |
+
siblings = []
|
176 |
+
sibling = element.getprevious()
|
177 |
+
while getattr(sibling, 'tag', None) is ProcessingInstruction:
|
178 |
+
siblings.append(sibling)
|
179 |
+
sibling = sibling.getprevious()
|
180 |
+
for sibling in siblings[::-1]:
|
181 |
+
self._recursive_saxify(sibling, {})
|
182 |
+
|
183 |
+
self._recursive_saxify(element, {})
|
184 |
+
|
185 |
+
if hasattr(element, 'getnext'):
|
186 |
+
sibling = element.getnext()
|
187 |
+
while getattr(sibling, 'tag', None) is ProcessingInstruction:
|
188 |
+
self._recursive_saxify(sibling, {})
|
189 |
+
sibling = sibling.getnext()
|
190 |
+
|
191 |
+
self._content_handler.endDocument()
|
192 |
+
|
193 |
+
def _recursive_saxify(self, element, parent_nsmap):
|
194 |
+
content_handler = self._content_handler
|
195 |
+
tag = element.tag
|
196 |
+
if tag is Comment or tag is ProcessingInstruction:
|
197 |
+
if tag is ProcessingInstruction:
|
198 |
+
content_handler.processingInstruction(
|
199 |
+
element.target, element.text)
|
200 |
+
tail = element.tail
|
201 |
+
if tail:
|
202 |
+
content_handler.characters(tail)
|
203 |
+
return
|
204 |
+
|
205 |
+
element_nsmap = element.nsmap
|
206 |
+
new_prefixes = []
|
207 |
+
if element_nsmap != parent_nsmap:
|
208 |
+
# There have been updates to the namespace
|
209 |
+
for prefix, ns_uri in element_nsmap.items():
|
210 |
+
if parent_nsmap.get(prefix) != ns_uri:
|
211 |
+
new_prefixes.append( (prefix, ns_uri) )
|
212 |
+
|
213 |
+
attribs = element.items()
|
214 |
+
if attribs:
|
215 |
+
attr_values = {}
|
216 |
+
attr_qnames = {}
|
217 |
+
for attr_ns_name, value in attribs:
|
218 |
+
attr_ns_tuple = _getNsTag(attr_ns_name)
|
219 |
+
attr_values[attr_ns_tuple] = value
|
220 |
+
attr_qnames[attr_ns_tuple] = self._build_qname(
|
221 |
+
attr_ns_tuple[0], attr_ns_tuple[1], element_nsmap,
|
222 |
+
preferred_prefix=None, is_attribute=True)
|
223 |
+
sax_attributes = self._attr_class(attr_values, attr_qnames)
|
224 |
+
else:
|
225 |
+
sax_attributes = self._empty_attributes
|
226 |
+
|
227 |
+
ns_uri, local_name = _getNsTag(tag)
|
228 |
+
qname = self._build_qname(
|
229 |
+
ns_uri, local_name, element_nsmap, element.prefix, is_attribute=False)
|
230 |
+
|
231 |
+
for prefix, uri in new_prefixes:
|
232 |
+
content_handler.startPrefixMapping(prefix, uri)
|
233 |
+
content_handler.startElementNS(
|
234 |
+
(ns_uri, local_name), qname, sax_attributes)
|
235 |
+
text = element.text
|
236 |
+
if text:
|
237 |
+
content_handler.characters(text)
|
238 |
+
for child in element:
|
239 |
+
self._recursive_saxify(child, element_nsmap)
|
240 |
+
content_handler.endElementNS((ns_uri, local_name), qname)
|
241 |
+
for prefix, uri in new_prefixes:
|
242 |
+
content_handler.endPrefixMapping(prefix)
|
243 |
+
tail = element.tail
|
244 |
+
if tail:
|
245 |
+
content_handler.characters(tail)
|
246 |
+
|
247 |
+
def _build_qname(self, ns_uri, local_name, nsmap, preferred_prefix, is_attribute):
|
248 |
+
if ns_uri is None:
|
249 |
+
return local_name
|
250 |
+
|
251 |
+
if not is_attribute and nsmap.get(preferred_prefix) == ns_uri:
|
252 |
+
prefix = preferred_prefix
|
253 |
+
else:
|
254 |
+
# Pick the first matching prefix, in alphabetical order.
|
255 |
+
candidates = [
|
256 |
+
pfx for (pfx, uri) in nsmap.items()
|
257 |
+
if pfx is not None and uri == ns_uri
|
258 |
+
]
|
259 |
+
prefix = (
|
260 |
+
candidates[0] if len(candidates) == 1
|
261 |
+
else min(candidates) if candidates
|
262 |
+
else None
|
263 |
+
)
|
264 |
+
|
265 |
+
if prefix is None:
|
266 |
+
# Default namespace
|
267 |
+
return local_name
|
268 |
+
return prefix + ':' + local_name
|
269 |
+
|
270 |
+
|
271 |
+
def saxify(element_or_tree, content_handler):
|
272 |
+
"""One-shot helper to generate SAX events from an XML tree and fire
|
273 |
+
them against a SAX ContentHandler.
|
274 |
+
"""
|
275 |
+
return ElementTreeProducer(element_or_tree, content_handler).saxify()
|
env-llmeval/lib/python3.10/site-packages/lxml/serializer.pxi
ADDED
@@ -0,0 +1,1871 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# XML serialization and output functions
|
2 |
+
|
3 |
+
cdef object GzipFile
|
4 |
+
from gzip import GzipFile
|
5 |
+
|
6 |
+
|
7 |
+
cdef class SerialisationError(LxmlError):
|
8 |
+
"""A libxml2 error that occurred during serialisation.
|
9 |
+
"""
|
10 |
+
|
11 |
+
|
12 |
+
cdef enum _OutputMethods:
|
13 |
+
OUTPUT_METHOD_XML
|
14 |
+
OUTPUT_METHOD_HTML
|
15 |
+
OUTPUT_METHOD_TEXT
|
16 |
+
|
17 |
+
|
18 |
+
cdef int _findOutputMethod(method) except -1:
|
19 |
+
if method is None:
|
20 |
+
return OUTPUT_METHOD_XML
|
21 |
+
method = method.lower()
|
22 |
+
if method == "xml":
|
23 |
+
return OUTPUT_METHOD_XML
|
24 |
+
if method == "html":
|
25 |
+
return OUTPUT_METHOD_HTML
|
26 |
+
if method == "text":
|
27 |
+
return OUTPUT_METHOD_TEXT
|
28 |
+
raise ValueError(f"unknown output method {method!r}")
|
29 |
+
|
30 |
+
|
31 |
+
cdef _textToString(xmlNode* c_node, encoding, bint with_tail):
|
32 |
+
cdef bint needs_conversion
|
33 |
+
cdef const_xmlChar* c_text
|
34 |
+
cdef xmlNode* c_text_node
|
35 |
+
cdef tree.xmlBuffer* c_buffer
|
36 |
+
cdef int error_result
|
37 |
+
|
38 |
+
c_buffer = tree.xmlBufferCreate()
|
39 |
+
if c_buffer is NULL:
|
40 |
+
raise MemoryError()
|
41 |
+
|
42 |
+
with nogil:
|
43 |
+
error_result = tree.xmlNodeBufGetContent(c_buffer, c_node)
|
44 |
+
if with_tail:
|
45 |
+
c_text_node = _textNodeOrSkip(c_node.next)
|
46 |
+
while c_text_node is not NULL:
|
47 |
+
tree.xmlBufferWriteChar(c_buffer, <const_char*>c_text_node.content)
|
48 |
+
c_text_node = _textNodeOrSkip(c_text_node.next)
|
49 |
+
c_text = tree.xmlBufferContent(c_buffer)
|
50 |
+
|
51 |
+
if error_result < 0 or c_text is NULL:
|
52 |
+
tree.xmlBufferFree(c_buffer)
|
53 |
+
raise SerialisationError, "Error during serialisation (out of memory?)"
|
54 |
+
|
55 |
+
try:
|
56 |
+
needs_conversion = 0
|
57 |
+
if encoding is unicode:
|
58 |
+
needs_conversion = 1
|
59 |
+
elif encoding is not None:
|
60 |
+
# Python prefers lower case encoding names
|
61 |
+
encoding = encoding.lower()
|
62 |
+
if encoding not in ('utf8', 'utf-8'):
|
63 |
+
if encoding == 'ascii':
|
64 |
+
if isutf8l(c_text, tree.xmlBufferLength(c_buffer)):
|
65 |
+
# will raise a decode error below
|
66 |
+
needs_conversion = 1
|
67 |
+
else:
|
68 |
+
needs_conversion = 1
|
69 |
+
|
70 |
+
if needs_conversion:
|
71 |
+
text = (<const_char*>c_text)[:tree.xmlBufferLength(c_buffer)].decode('utf8')
|
72 |
+
if encoding is not unicode:
|
73 |
+
encoding = _utf8(encoding)
|
74 |
+
text = python.PyUnicode_AsEncodedString(
|
75 |
+
text, encoding, 'strict')
|
76 |
+
else:
|
77 |
+
text = (<unsigned char*>c_text)[:tree.xmlBufferLength(c_buffer)]
|
78 |
+
finally:
|
79 |
+
tree.xmlBufferFree(c_buffer)
|
80 |
+
return text
|
81 |
+
|
82 |
+
|
83 |
+
cdef _tostring(_Element element, encoding, doctype, method,
|
84 |
+
bint write_xml_declaration, bint write_complete_document,
|
85 |
+
bint pretty_print, bint with_tail, int standalone):
|
86 |
+
"""Serialize an element to an encoded string representation of its XML
|
87 |
+
tree.
|
88 |
+
"""
|
89 |
+
cdef tree.xmlOutputBuffer* c_buffer
|
90 |
+
cdef tree.xmlBuf* c_result_buffer
|
91 |
+
cdef tree.xmlCharEncodingHandler* enchandler
|
92 |
+
cdef const_char* c_enc
|
93 |
+
cdef const_xmlChar* c_version
|
94 |
+
cdef const_xmlChar* c_doctype
|
95 |
+
cdef int c_method
|
96 |
+
cdef int error_result
|
97 |
+
if element is None:
|
98 |
+
return None
|
99 |
+
_assertValidNode(element)
|
100 |
+
c_method = _findOutputMethod(method)
|
101 |
+
if c_method == OUTPUT_METHOD_TEXT:
|
102 |
+
return _textToString(element._c_node, encoding, with_tail)
|
103 |
+
if encoding is None or encoding is unicode:
|
104 |
+
c_enc = NULL
|
105 |
+
else:
|
106 |
+
encoding = _utf8(encoding)
|
107 |
+
c_enc = _cstr(encoding)
|
108 |
+
if doctype is None:
|
109 |
+
c_doctype = NULL
|
110 |
+
else:
|
111 |
+
doctype = _utf8(doctype)
|
112 |
+
c_doctype = _xcstr(doctype)
|
113 |
+
# it is necessary to *and* find the encoding handler *and* use
|
114 |
+
# encoding during output
|
115 |
+
enchandler = tree.xmlFindCharEncodingHandler(c_enc)
|
116 |
+
if enchandler is NULL and c_enc is not NULL:
|
117 |
+
if encoding is not None:
|
118 |
+
encoding = encoding.decode('UTF-8')
|
119 |
+
raise LookupError, f"unknown encoding: '{encoding}'"
|
120 |
+
c_buffer = tree.xmlAllocOutputBuffer(enchandler)
|
121 |
+
if c_buffer is NULL:
|
122 |
+
tree.xmlCharEncCloseFunc(enchandler)
|
123 |
+
raise MemoryError()
|
124 |
+
|
125 |
+
with nogil:
|
126 |
+
_writeNodeToBuffer(c_buffer, element._c_node, c_enc, c_doctype, c_method,
|
127 |
+
write_xml_declaration, write_complete_document,
|
128 |
+
pretty_print, with_tail, standalone)
|
129 |
+
tree.xmlOutputBufferFlush(c_buffer)
|
130 |
+
if c_buffer.conv is not NULL:
|
131 |
+
c_result_buffer = c_buffer.conv
|
132 |
+
else:
|
133 |
+
c_result_buffer = c_buffer.buffer
|
134 |
+
|
135 |
+
error_result = c_buffer.error
|
136 |
+
if error_result != xmlerror.XML_ERR_OK:
|
137 |
+
tree.xmlOutputBufferClose(c_buffer)
|
138 |
+
_raiseSerialisationError(error_result)
|
139 |
+
|
140 |
+
try:
|
141 |
+
if encoding is unicode:
|
142 |
+
result = (<unsigned char*>tree.xmlBufContent(
|
143 |
+
c_result_buffer))[:tree.xmlBufUse(c_result_buffer)].decode('UTF-8')
|
144 |
+
else:
|
145 |
+
result = <bytes>(<unsigned char*>tree.xmlBufContent(
|
146 |
+
c_result_buffer))[:tree.xmlBufUse(c_result_buffer)]
|
147 |
+
finally:
|
148 |
+
error_result = tree.xmlOutputBufferClose(c_buffer)
|
149 |
+
if error_result == -1:
|
150 |
+
_raiseSerialisationError(error_result)
|
151 |
+
return result
|
152 |
+
|
153 |
+
cdef bytes _tostringC14N(element_or_tree, bint exclusive, bint with_comments, inclusive_ns_prefixes):
|
154 |
+
cdef xmlDoc* c_doc
|
155 |
+
cdef xmlChar* c_buffer = NULL
|
156 |
+
cdef int byte_count = -1
|
157 |
+
cdef bytes result
|
158 |
+
cdef _Document doc
|
159 |
+
cdef _Element element
|
160 |
+
cdef xmlChar **c_inclusive_ns_prefixes
|
161 |
+
|
162 |
+
if isinstance(element_or_tree, _Element):
|
163 |
+
_assertValidNode(<_Element>element_or_tree)
|
164 |
+
doc = (<_Element>element_or_tree)._doc
|
165 |
+
c_doc = _plainFakeRootDoc(doc._c_doc, (<_Element>element_or_tree)._c_node, 0)
|
166 |
+
else:
|
167 |
+
doc = _documentOrRaise(element_or_tree)
|
168 |
+
_assertValidDoc(doc)
|
169 |
+
c_doc = doc._c_doc
|
170 |
+
|
171 |
+
c_inclusive_ns_prefixes = _convert_ns_prefixes(c_doc.dict, inclusive_ns_prefixes) if inclusive_ns_prefixes else NULL
|
172 |
+
try:
|
173 |
+
with nogil:
|
174 |
+
byte_count = c14n.xmlC14NDocDumpMemory(
|
175 |
+
c_doc, NULL, exclusive, c_inclusive_ns_prefixes, with_comments, &c_buffer)
|
176 |
+
|
177 |
+
finally:
|
178 |
+
_destroyFakeDoc(doc._c_doc, c_doc)
|
179 |
+
if c_inclusive_ns_prefixes is not NULL:
|
180 |
+
python.lxml_free(c_inclusive_ns_prefixes)
|
181 |
+
|
182 |
+
if byte_count < 0 or c_buffer is NULL:
|
183 |
+
if c_buffer is not NULL:
|
184 |
+
tree.xmlFree(c_buffer)
|
185 |
+
raise C14NError, "C14N failed"
|
186 |
+
try:
|
187 |
+
result = c_buffer[:byte_count]
|
188 |
+
finally:
|
189 |
+
tree.xmlFree(c_buffer)
|
190 |
+
return result
|
191 |
+
|
192 |
+
cdef _raiseSerialisationError(int error_result):
|
193 |
+
if error_result == xmlerror.XML_ERR_NO_MEMORY:
|
194 |
+
raise MemoryError()
|
195 |
+
message = ErrorTypes._getName(error_result)
|
196 |
+
if message is None:
|
197 |
+
message = f"unknown error {error_result}"
|
198 |
+
raise SerialisationError, message
|
199 |
+
|
200 |
+
############################################################
|
201 |
+
# low-level serialisation functions
|
202 |
+
|
203 |
+
cdef void _writeDoctype(tree.xmlOutputBuffer* c_buffer,
|
204 |
+
const_xmlChar* c_doctype) noexcept nogil:
|
205 |
+
tree.xmlOutputBufferWrite(c_buffer, tree.xmlStrlen(c_doctype),
|
206 |
+
<const_char*>c_doctype)
|
207 |
+
tree.xmlOutputBufferWriteString(c_buffer, "\n")
|
208 |
+
|
209 |
+
cdef void _writeNodeToBuffer(tree.xmlOutputBuffer* c_buffer,
|
210 |
+
xmlNode* c_node, const_char* encoding, const_xmlChar* c_doctype,
|
211 |
+
int c_method, bint write_xml_declaration,
|
212 |
+
bint write_complete_document,
|
213 |
+
bint pretty_print, bint with_tail,
|
214 |
+
int standalone) noexcept nogil:
|
215 |
+
cdef xmlNode* c_nsdecl_node
|
216 |
+
cdef xmlDoc* c_doc = c_node.doc
|
217 |
+
if write_xml_declaration and c_method == OUTPUT_METHOD_XML:
|
218 |
+
_writeDeclarationToBuffer(c_buffer, c_doc.version, encoding, standalone)
|
219 |
+
|
220 |
+
# comments/processing instructions before doctype declaration
|
221 |
+
if write_complete_document and not c_buffer.error and c_doc.intSubset:
|
222 |
+
_writePrevSiblings(c_buffer, <xmlNode*>c_doc.intSubset, encoding, pretty_print)
|
223 |
+
|
224 |
+
if c_doctype:
|
225 |
+
_writeDoctype(c_buffer, c_doctype)
|
226 |
+
# write internal DTD subset, preceding PIs/comments, etc.
|
227 |
+
if write_complete_document and not c_buffer.error:
|
228 |
+
if c_doctype is NULL:
|
229 |
+
_writeDtdToBuffer(c_buffer, c_doc, c_node.name, c_method, encoding)
|
230 |
+
_writePrevSiblings(c_buffer, c_node, encoding, pretty_print)
|
231 |
+
|
232 |
+
c_nsdecl_node = c_node
|
233 |
+
if not c_node.parent or c_node.parent.type != tree.XML_DOCUMENT_NODE:
|
234 |
+
# copy the node and add namespaces from parents
|
235 |
+
# this is required to make libxml write them
|
236 |
+
c_nsdecl_node = tree.xmlCopyNode(c_node, 2)
|
237 |
+
if not c_nsdecl_node:
|
238 |
+
c_buffer.error = xmlerror.XML_ERR_NO_MEMORY
|
239 |
+
return
|
240 |
+
_copyParentNamespaces(c_node, c_nsdecl_node)
|
241 |
+
|
242 |
+
c_nsdecl_node.parent = c_node.parent
|
243 |
+
c_nsdecl_node.children = c_node.children
|
244 |
+
c_nsdecl_node.last = c_node.last
|
245 |
+
|
246 |
+
# write node
|
247 |
+
if c_method == OUTPUT_METHOD_HTML:
|
248 |
+
tree.htmlNodeDumpFormatOutput(
|
249 |
+
c_buffer, c_doc, c_nsdecl_node, encoding, pretty_print)
|
250 |
+
else:
|
251 |
+
tree.xmlNodeDumpOutput(
|
252 |
+
c_buffer, c_doc, c_nsdecl_node, 0, pretty_print, encoding)
|
253 |
+
|
254 |
+
if c_nsdecl_node is not c_node:
|
255 |
+
# clean up
|
256 |
+
c_nsdecl_node.children = c_nsdecl_node.last = NULL
|
257 |
+
tree.xmlFreeNode(c_nsdecl_node)
|
258 |
+
|
259 |
+
if c_buffer.error:
|
260 |
+
return
|
261 |
+
|
262 |
+
# write tail, trailing comments, etc.
|
263 |
+
if with_tail:
|
264 |
+
_writeTail(c_buffer, c_node, encoding, c_method, pretty_print)
|
265 |
+
if write_complete_document:
|
266 |
+
_writeNextSiblings(c_buffer, c_node, encoding, pretty_print)
|
267 |
+
if pretty_print:
|
268 |
+
tree.xmlOutputBufferWrite(c_buffer, 1, "\n")
|
269 |
+
|
270 |
+
cdef void _writeDeclarationToBuffer(tree.xmlOutputBuffer* c_buffer,
|
271 |
+
const_xmlChar* version, const_char* encoding,
|
272 |
+
int standalone) noexcept nogil:
|
273 |
+
if version is NULL:
|
274 |
+
version = <unsigned char*>"1.0"
|
275 |
+
tree.xmlOutputBufferWrite(c_buffer, 15, "<?xml version='")
|
276 |
+
tree.xmlOutputBufferWriteString(c_buffer, <const_char*>version)
|
277 |
+
tree.xmlOutputBufferWrite(c_buffer, 12, "' encoding='")
|
278 |
+
tree.xmlOutputBufferWriteString(c_buffer, encoding)
|
279 |
+
if standalone == 0:
|
280 |
+
tree.xmlOutputBufferWrite(c_buffer, 20, "' standalone='no'?>\n")
|
281 |
+
elif standalone == 1:
|
282 |
+
tree.xmlOutputBufferWrite(c_buffer, 21, "' standalone='yes'?>\n")
|
283 |
+
else:
|
284 |
+
tree.xmlOutputBufferWrite(c_buffer, 4, "'?>\n")
|
285 |
+
|
286 |
+
cdef void _writeDtdToBuffer(tree.xmlOutputBuffer* c_buffer,
|
287 |
+
xmlDoc* c_doc, const_xmlChar* c_root_name,
|
288 |
+
int c_method, const_char* encoding) noexcept nogil:
|
289 |
+
cdef tree.xmlDtd* c_dtd
|
290 |
+
cdef xmlNode* c_node
|
291 |
+
cdef char* quotechar
|
292 |
+
c_dtd = c_doc.intSubset
|
293 |
+
if not c_dtd or not c_dtd.name:
|
294 |
+
return
|
295 |
+
|
296 |
+
# Name in document type declaration must match the root element tag.
|
297 |
+
# For XML, case sensitive match, for HTML insensitive.
|
298 |
+
if c_method == OUTPUT_METHOD_HTML:
|
299 |
+
if tree.xmlStrcasecmp(c_root_name, c_dtd.name) != 0:
|
300 |
+
return
|
301 |
+
else:
|
302 |
+
if tree.xmlStrcmp(c_root_name, c_dtd.name) != 0:
|
303 |
+
return
|
304 |
+
|
305 |
+
tree.xmlOutputBufferWrite(c_buffer, 10, "<!DOCTYPE ")
|
306 |
+
tree.xmlOutputBufferWriteString(c_buffer, <const_char*>c_dtd.name)
|
307 |
+
|
308 |
+
cdef const_xmlChar* public_id = c_dtd.ExternalID
|
309 |
+
cdef const_xmlChar* sys_url = c_dtd.SystemID
|
310 |
+
if public_id and public_id[0] == b'\0':
|
311 |
+
public_id = NULL
|
312 |
+
if sys_url and sys_url[0] == b'\0':
|
313 |
+
sys_url = NULL
|
314 |
+
|
315 |
+
if public_id:
|
316 |
+
tree.xmlOutputBufferWrite(c_buffer, 9, ' PUBLIC "')
|
317 |
+
tree.xmlOutputBufferWriteString(c_buffer, <const_char*>public_id)
|
318 |
+
if sys_url:
|
319 |
+
tree.xmlOutputBufferWrite(c_buffer, 2, '" ')
|
320 |
+
else:
|
321 |
+
tree.xmlOutputBufferWrite(c_buffer, 1, '"')
|
322 |
+
elif sys_url:
|
323 |
+
tree.xmlOutputBufferWrite(c_buffer, 8, ' SYSTEM ')
|
324 |
+
|
325 |
+
if sys_url:
|
326 |
+
if tree.xmlStrchr(sys_url, b'"'):
|
327 |
+
quotechar = '\''
|
328 |
+
else:
|
329 |
+
quotechar = '"'
|
330 |
+
tree.xmlOutputBufferWrite(c_buffer, 1, quotechar)
|
331 |
+
tree.xmlOutputBufferWriteString(c_buffer, <const_char*>sys_url)
|
332 |
+
tree.xmlOutputBufferWrite(c_buffer, 1, quotechar)
|
333 |
+
|
334 |
+
if (not c_dtd.entities and not c_dtd.elements and
|
335 |
+
not c_dtd.attributes and not c_dtd.notations and
|
336 |
+
not c_dtd.pentities):
|
337 |
+
tree.xmlOutputBufferWrite(c_buffer, 2, '>\n')
|
338 |
+
return
|
339 |
+
|
340 |
+
tree.xmlOutputBufferWrite(c_buffer, 3, ' [\n')
|
341 |
+
if c_dtd.notations and not c_buffer.error:
|
342 |
+
c_buf = tree.xmlBufferCreate()
|
343 |
+
if not c_buf:
|
344 |
+
c_buffer.error = xmlerror.XML_ERR_NO_MEMORY
|
345 |
+
return
|
346 |
+
tree.xmlDumpNotationTable(c_buf, <tree.xmlNotationTable*>c_dtd.notations)
|
347 |
+
tree.xmlOutputBufferWrite(
|
348 |
+
c_buffer, tree.xmlBufferLength(c_buf),
|
349 |
+
<const_char*>tree.xmlBufferContent(c_buf))
|
350 |
+
tree.xmlBufferFree(c_buf)
|
351 |
+
c_node = c_dtd.children
|
352 |
+
while c_node and not c_buffer.error:
|
353 |
+
tree.xmlNodeDumpOutput(c_buffer, c_node.doc, c_node, 0, 0, encoding)
|
354 |
+
c_node = c_node.next
|
355 |
+
tree.xmlOutputBufferWrite(c_buffer, 3, "]>\n")
|
356 |
+
|
357 |
+
cdef void _writeTail(tree.xmlOutputBuffer* c_buffer, xmlNode* c_node,
|
358 |
+
const_char* encoding, int c_method, bint pretty_print) noexcept nogil:
|
359 |
+
"Write the element tail."
|
360 |
+
c_node = c_node.next
|
361 |
+
while c_node and not c_buffer.error and c_node.type in (
|
362 |
+
tree.XML_TEXT_NODE, tree.XML_CDATA_SECTION_NODE):
|
363 |
+
if c_method == OUTPUT_METHOD_HTML:
|
364 |
+
tree.htmlNodeDumpFormatOutput(
|
365 |
+
c_buffer, c_node.doc, c_node, encoding, pretty_print)
|
366 |
+
else:
|
367 |
+
tree.xmlNodeDumpOutput(
|
368 |
+
c_buffer, c_node.doc, c_node, 0, pretty_print, encoding)
|
369 |
+
c_node = c_node.next
|
370 |
+
|
371 |
+
cdef void _writePrevSiblings(tree.xmlOutputBuffer* c_buffer, xmlNode* c_node,
|
372 |
+
const_char* encoding, bint pretty_print) noexcept nogil:
|
373 |
+
cdef xmlNode* c_sibling
|
374 |
+
if c_node.parent and _isElement(c_node.parent):
|
375 |
+
return
|
376 |
+
# we are at a root node, so add PI and comment siblings
|
377 |
+
c_sibling = c_node
|
378 |
+
while c_sibling.prev and \
|
379 |
+
(c_sibling.prev.type == tree.XML_PI_NODE or
|
380 |
+
c_sibling.prev.type == tree.XML_COMMENT_NODE):
|
381 |
+
c_sibling = c_sibling.prev
|
382 |
+
while c_sibling is not c_node and not c_buffer.error:
|
383 |
+
tree.xmlNodeDumpOutput(c_buffer, c_node.doc, c_sibling, 0,
|
384 |
+
pretty_print, encoding)
|
385 |
+
if pretty_print:
|
386 |
+
tree.xmlOutputBufferWriteString(c_buffer, "\n")
|
387 |
+
c_sibling = c_sibling.next
|
388 |
+
|
389 |
+
cdef void _writeNextSiblings(tree.xmlOutputBuffer* c_buffer, xmlNode* c_node,
|
390 |
+
const_char* encoding, bint pretty_print) noexcept nogil:
|
391 |
+
cdef xmlNode* c_sibling
|
392 |
+
if c_node.parent and _isElement(c_node.parent):
|
393 |
+
return
|
394 |
+
# we are at a root node, so add PI and comment siblings
|
395 |
+
c_sibling = c_node.next
|
396 |
+
while not c_buffer.error and c_sibling and \
|
397 |
+
(c_sibling.type == tree.XML_PI_NODE or
|
398 |
+
c_sibling.type == tree.XML_COMMENT_NODE):
|
399 |
+
if pretty_print:
|
400 |
+
tree.xmlOutputBufferWriteString(c_buffer, "\n")
|
401 |
+
tree.xmlNodeDumpOutput(c_buffer, c_node.doc, c_sibling, 0,
|
402 |
+
pretty_print, encoding)
|
403 |
+
c_sibling = c_sibling.next
|
404 |
+
|
405 |
+
|
406 |
+
# copied and adapted from libxml2
|
407 |
+
cdef unsigned char *xmlSerializeHexCharRef(unsigned char *out, int val) noexcept:
|
408 |
+
cdef xmlChar *ptr
|
409 |
+
cdef const xmlChar* hexdigits = b"0123456789ABCDEF"
|
410 |
+
|
411 |
+
out[0] = b'&'
|
412 |
+
out += 1
|
413 |
+
out[0] = b'#'
|
414 |
+
out += 1
|
415 |
+
out[0] = b'x'
|
416 |
+
out += 1
|
417 |
+
|
418 |
+
if val < 0x10:
|
419 |
+
ptr = out
|
420 |
+
elif val < 0x100:
|
421 |
+
ptr = out + 1
|
422 |
+
elif val < 0x1000:
|
423 |
+
ptr = out + 2
|
424 |
+
elif val < 0x10000:
|
425 |
+
ptr = out + 3
|
426 |
+
elif val < 0x100000:
|
427 |
+
ptr = out + 4
|
428 |
+
else:
|
429 |
+
ptr = out + 5
|
430 |
+
|
431 |
+
out = ptr + 1
|
432 |
+
while val > 0:
|
433 |
+
ptr[0] = hexdigits[val & 0xF]
|
434 |
+
ptr -= 1
|
435 |
+
val >>= 4
|
436 |
+
|
437 |
+
out[0] = b';'
|
438 |
+
out += 1
|
439 |
+
out[0] = 0
|
440 |
+
|
441 |
+
return out
|
442 |
+
|
443 |
+
|
444 |
+
# copied and adapted from libxml2 (xmlBufAttrSerializeTxtContent())
|
445 |
+
cdef _write_attr_string(tree.xmlOutputBuffer* buf, const char *string):
|
446 |
+
cdef const char *base
|
447 |
+
cdef const char *cur
|
448 |
+
cdef const unsigned char *ucur
|
449 |
+
|
450 |
+
cdef unsigned char tmp[12]
|
451 |
+
cdef int val = 0
|
452 |
+
cdef int l
|
453 |
+
|
454 |
+
if string == NULL:
|
455 |
+
return
|
456 |
+
|
457 |
+
base = cur = <const char*>string
|
458 |
+
while cur[0] != 0:
|
459 |
+
if cur[0] == b'\n':
|
460 |
+
if base != cur:
|
461 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
462 |
+
|
463 |
+
tree.xmlOutputBufferWrite(buf, 5, " ")
|
464 |
+
cur += 1
|
465 |
+
base = cur
|
466 |
+
|
467 |
+
elif cur[0] == b'\r':
|
468 |
+
if base != cur:
|
469 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
470 |
+
|
471 |
+
tree.xmlOutputBufferWrite(buf, 5, " ")
|
472 |
+
cur += 1
|
473 |
+
base = cur
|
474 |
+
|
475 |
+
elif cur[0] == b'\t':
|
476 |
+
if base != cur:
|
477 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
478 |
+
|
479 |
+
tree.xmlOutputBufferWrite(buf, 4, "	")
|
480 |
+
cur += 1
|
481 |
+
base = cur
|
482 |
+
|
483 |
+
elif cur[0] == b'"':
|
484 |
+
if base != cur:
|
485 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
486 |
+
|
487 |
+
tree.xmlOutputBufferWrite(buf, 6, """)
|
488 |
+
cur += 1
|
489 |
+
base = cur
|
490 |
+
|
491 |
+
elif cur[0] == b'<':
|
492 |
+
if base != cur:
|
493 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
494 |
+
|
495 |
+
tree.xmlOutputBufferWrite(buf, 4, "<")
|
496 |
+
cur += 1
|
497 |
+
base = cur
|
498 |
+
|
499 |
+
elif cur[0] == b'>':
|
500 |
+
if base != cur:
|
501 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
502 |
+
|
503 |
+
tree.xmlOutputBufferWrite(buf, 4, ">")
|
504 |
+
cur += 1
|
505 |
+
base = cur
|
506 |
+
elif cur[0] == b'&':
|
507 |
+
if base != cur:
|
508 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
509 |
+
|
510 |
+
tree.xmlOutputBufferWrite(buf, 5, "&")
|
511 |
+
cur += 1
|
512 |
+
base = cur
|
513 |
+
|
514 |
+
elif (<const unsigned char>cur[0] >= 0x80) and (cur[1] != 0):
|
515 |
+
|
516 |
+
if base != cur:
|
517 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
518 |
+
|
519 |
+
ucur = <const unsigned char *>cur
|
520 |
+
|
521 |
+
if ucur[0] < 0xC0:
|
522 |
+
# invalid UTF-8 sequence
|
523 |
+
val = ucur[0]
|
524 |
+
l = 1
|
525 |
+
|
526 |
+
elif ucur[0] < 0xE0:
|
527 |
+
val = (ucur[0]) & 0x1F
|
528 |
+
val <<= 6
|
529 |
+
val |= (ucur[1]) & 0x3F
|
530 |
+
l = 2
|
531 |
+
|
532 |
+
elif (ucur[0] < 0xF0) and (ucur[2] != 0):
|
533 |
+
val = (ucur[0]) & 0x0F
|
534 |
+
val <<= 6
|
535 |
+
val |= (ucur[1]) & 0x3F
|
536 |
+
val <<= 6
|
537 |
+
val |= (ucur[2]) & 0x3F
|
538 |
+
l = 3
|
539 |
+
|
540 |
+
elif (ucur[0] < 0xF8) and (ucur[2] != 0) and (ucur[3] != 0):
|
541 |
+
val = (ucur[0]) & 0x07
|
542 |
+
val <<= 6
|
543 |
+
val |= (ucur[1]) & 0x3F
|
544 |
+
val <<= 6
|
545 |
+
val |= (ucur[2]) & 0x3F
|
546 |
+
val <<= 6
|
547 |
+
val |= (ucur[3]) & 0x3F
|
548 |
+
l = 4
|
549 |
+
else:
|
550 |
+
# invalid UTF-8 sequence
|
551 |
+
val = ucur[0]
|
552 |
+
l = 1
|
553 |
+
|
554 |
+
if (l == 1) or (not tree.xmlIsCharQ(val)):
|
555 |
+
raise ValueError(f"Invalid character: {val:X}")
|
556 |
+
|
557 |
+
# We could do multiple things here. Just save
|
558 |
+
# as a char ref
|
559 |
+
xmlSerializeHexCharRef(tmp, val)
|
560 |
+
tree.xmlOutputBufferWrite(buf, len(tmp), <const char*> tmp)
|
561 |
+
cur += l
|
562 |
+
base = cur
|
563 |
+
|
564 |
+
else:
|
565 |
+
cur += 1
|
566 |
+
|
567 |
+
if base != cur:
|
568 |
+
tree.xmlOutputBufferWrite(buf, cur - base, base)
|
569 |
+
|
570 |
+
|
571 |
+
############################################################
|
572 |
+
# output to file-like objects
|
573 |
+
|
574 |
+
cdef object io_open
|
575 |
+
from io import open
|
576 |
+
|
577 |
+
cdef object gzip
|
578 |
+
import gzip
|
579 |
+
|
580 |
+
cdef object getwriter
|
581 |
+
from codecs import getwriter
|
582 |
+
cdef object utf8_writer = getwriter('utf8')
|
583 |
+
|
584 |
+
cdef object contextmanager
|
585 |
+
from contextlib import contextmanager
|
586 |
+
|
587 |
+
cdef object _open_utf8_file
|
588 |
+
|
589 |
+
@contextmanager
|
590 |
+
def _open_utf8_file(file, compression=0):
|
591 |
+
file = _getFSPathOrObject(file)
|
592 |
+
if _isString(file):
|
593 |
+
if compression:
|
594 |
+
with gzip.GzipFile(file, mode='wb', compresslevel=compression) as zf:
|
595 |
+
yield utf8_writer(zf)
|
596 |
+
else:
|
597 |
+
with io_open(file, 'w', encoding='utf8') as f:
|
598 |
+
yield f
|
599 |
+
else:
|
600 |
+
if compression:
|
601 |
+
with gzip.GzipFile(fileobj=file, mode='wb', compresslevel=compression) as zf:
|
602 |
+
yield utf8_writer(zf)
|
603 |
+
else:
|
604 |
+
yield utf8_writer(file)
|
605 |
+
|
606 |
+
|
607 |
+
@cython.final
|
608 |
+
@cython.internal
|
609 |
+
cdef class _FilelikeWriter:
|
610 |
+
cdef object _filelike
|
611 |
+
cdef object _close_filelike
|
612 |
+
cdef _ExceptionContext _exc_context
|
613 |
+
cdef _ErrorLog error_log
|
614 |
+
def __cinit__(self, filelike, exc_context=None, compression=None, close=False):
|
615 |
+
if compression is not None and compression > 0:
|
616 |
+
filelike = GzipFile(
|
617 |
+
fileobj=filelike, mode='wb', compresslevel=compression)
|
618 |
+
self._close_filelike = filelike.close
|
619 |
+
elif close:
|
620 |
+
self._close_filelike = filelike.close
|
621 |
+
self._filelike = filelike
|
622 |
+
if exc_context is None:
|
623 |
+
self._exc_context = _ExceptionContext()
|
624 |
+
else:
|
625 |
+
self._exc_context = exc_context
|
626 |
+
self.error_log = _ErrorLog()
|
627 |
+
|
628 |
+
cdef tree.xmlOutputBuffer* _createOutputBuffer(
|
629 |
+
self, tree.xmlCharEncodingHandler* enchandler) except NULL:
|
630 |
+
cdef tree.xmlOutputBuffer* c_buffer
|
631 |
+
c_buffer = tree.xmlOutputBufferCreateIO(
|
632 |
+
<tree.xmlOutputWriteCallback>_writeFilelikeWriter, _closeFilelikeWriter,
|
633 |
+
<python.PyObject*>self, enchandler)
|
634 |
+
if c_buffer is NULL:
|
635 |
+
raise IOError, "Could not create I/O writer context."
|
636 |
+
return c_buffer
|
637 |
+
|
638 |
+
cdef int write(self, char* c_buffer, int size) noexcept:
|
639 |
+
try:
|
640 |
+
if self._filelike is None:
|
641 |
+
raise IOError, "File is already closed"
|
642 |
+
py_buffer = <bytes>c_buffer[:size]
|
643 |
+
self._filelike.write(py_buffer)
|
644 |
+
except:
|
645 |
+
size = -1
|
646 |
+
self._exc_context._store_raised()
|
647 |
+
finally:
|
648 |
+
return size # and swallow any further exceptions
|
649 |
+
|
650 |
+
cdef int close(self) noexcept:
|
651 |
+
retval = 0
|
652 |
+
try:
|
653 |
+
if self._close_filelike is not None:
|
654 |
+
self._close_filelike()
|
655 |
+
# we should not close the file here as we didn't open it
|
656 |
+
self._filelike = None
|
657 |
+
except:
|
658 |
+
retval = -1
|
659 |
+
self._exc_context._store_raised()
|
660 |
+
finally:
|
661 |
+
return retval # and swallow any further exceptions
|
662 |
+
|
663 |
+
cdef int _writeFilelikeWriter(void* ctxt, char* c_buffer, int length) noexcept:
|
664 |
+
return (<_FilelikeWriter>ctxt).write(c_buffer, length)
|
665 |
+
|
666 |
+
cdef int _closeFilelikeWriter(void* ctxt) noexcept:
|
667 |
+
return (<_FilelikeWriter>ctxt).close()
|
668 |
+
|
669 |
+
cdef _tofilelike(f, _Element element, encoding, doctype, method,
|
670 |
+
bint write_xml_declaration, bint write_doctype,
|
671 |
+
bint pretty_print, bint with_tail, int standalone,
|
672 |
+
int compression):
|
673 |
+
cdef _FilelikeWriter writer = None
|
674 |
+
cdef tree.xmlOutputBuffer* c_buffer
|
675 |
+
cdef tree.xmlCharEncodingHandler* enchandler
|
676 |
+
cdef const_char* c_enc
|
677 |
+
cdef const_xmlChar* c_doctype
|
678 |
+
cdef int error_result
|
679 |
+
|
680 |
+
c_method = _findOutputMethod(method)
|
681 |
+
if c_method == OUTPUT_METHOD_TEXT:
|
682 |
+
data = _textToString(element._c_node, encoding, with_tail)
|
683 |
+
if compression:
|
684 |
+
bytes_out = BytesIO()
|
685 |
+
with GzipFile(fileobj=bytes_out, mode='wb', compresslevel=compression) as gzip_file:
|
686 |
+
gzip_file.write(data)
|
687 |
+
data = bytes_out.getvalue()
|
688 |
+
f = _getFSPathOrObject(f)
|
689 |
+
if _isString(f):
|
690 |
+
filename8 = _encodeFilename(f)
|
691 |
+
with open(filename8, 'wb') as f:
|
692 |
+
f.write(data)
|
693 |
+
else:
|
694 |
+
f.write(data)
|
695 |
+
return
|
696 |
+
|
697 |
+
if encoding is None:
|
698 |
+
c_enc = NULL
|
699 |
+
else:
|
700 |
+
encoding = _utf8(encoding)
|
701 |
+
c_enc = _cstr(encoding)
|
702 |
+
if doctype is None:
|
703 |
+
c_doctype = NULL
|
704 |
+
else:
|
705 |
+
doctype = _utf8(doctype)
|
706 |
+
c_doctype = _xcstr(doctype)
|
707 |
+
|
708 |
+
writer = _create_output_buffer(f, c_enc, compression, &c_buffer, close=False)
|
709 |
+
if writer is None:
|
710 |
+
with nogil:
|
711 |
+
error_result = _serialise_node(
|
712 |
+
c_buffer, c_doctype, c_enc, element._c_node, c_method,
|
713 |
+
write_xml_declaration, write_doctype, pretty_print, with_tail, standalone)
|
714 |
+
else:
|
715 |
+
error_result = _serialise_node(
|
716 |
+
c_buffer, c_doctype, c_enc, element._c_node, c_method,
|
717 |
+
write_xml_declaration, write_doctype, pretty_print, with_tail, standalone)
|
718 |
+
|
719 |
+
if writer is not None:
|
720 |
+
writer._exc_context._raise_if_stored()
|
721 |
+
if error_result != xmlerror.XML_ERR_OK:
|
722 |
+
_raiseSerialisationError(error_result)
|
723 |
+
|
724 |
+
|
725 |
+
cdef int _serialise_node(tree.xmlOutputBuffer* c_buffer, const_xmlChar* c_doctype,
|
726 |
+
const_char* c_enc, xmlNode* c_node, int c_method,
|
727 |
+
bint write_xml_declaration, bint write_doctype, bint pretty_print,
|
728 |
+
bint with_tail, int standalone) noexcept nogil:
|
729 |
+
_writeNodeToBuffer(
|
730 |
+
c_buffer, c_node, c_enc, c_doctype, c_method,
|
731 |
+
write_xml_declaration, write_doctype, pretty_print, with_tail, standalone)
|
732 |
+
error_result = c_buffer.error
|
733 |
+
if error_result == xmlerror.XML_ERR_OK:
|
734 |
+
error_result = tree.xmlOutputBufferClose(c_buffer)
|
735 |
+
if error_result != -1:
|
736 |
+
error_result = xmlerror.XML_ERR_OK
|
737 |
+
else:
|
738 |
+
tree.xmlOutputBufferClose(c_buffer)
|
739 |
+
return error_result
|
740 |
+
|
741 |
+
|
742 |
+
cdef _FilelikeWriter _create_output_buffer(
|
743 |
+
f, const_char* c_enc, int c_compression,
|
744 |
+
tree.xmlOutputBuffer** c_buffer_ret, bint close):
|
745 |
+
cdef tree.xmlOutputBuffer* c_buffer
|
746 |
+
cdef _FilelikeWriter writer
|
747 |
+
cdef bytes filename8
|
748 |
+
enchandler = tree.xmlFindCharEncodingHandler(c_enc)
|
749 |
+
if enchandler is NULL:
|
750 |
+
raise LookupError(
|
751 |
+
f"unknown encoding: '{c_enc.decode('UTF-8') if c_enc is not NULL else u''}'")
|
752 |
+
try:
|
753 |
+
f = _getFSPathOrObject(f)
|
754 |
+
if _isString(f):
|
755 |
+
filename8 = _encodeFilename(f)
|
756 |
+
if b'%' in filename8 and (
|
757 |
+
# Exclude absolute Windows paths and file:// URLs.
|
758 |
+
_isFilePath(<const xmlChar*>filename8) not in (NO_FILE_PATH, ABS_WIN_FILE_PATH)
|
759 |
+
or filename8[:7].lower() == b'file://'):
|
760 |
+
# A file path (not a URL) containing the '%' URL escape character.
|
761 |
+
# libxml2 uses URL-unescaping on these, so escape the path before passing it in.
|
762 |
+
filename8 = filename8.replace(b'%', b'%25')
|
763 |
+
c_buffer = tree.xmlOutputBufferCreateFilename(
|
764 |
+
_cstr(filename8), enchandler, c_compression)
|
765 |
+
if c_buffer is NULL:
|
766 |
+
python.PyErr_SetFromErrno(IOError) # raises IOError
|
767 |
+
writer = None
|
768 |
+
elif hasattr(f, 'write'):
|
769 |
+
writer = _FilelikeWriter(f, compression=c_compression, close=close)
|
770 |
+
c_buffer = writer._createOutputBuffer(enchandler)
|
771 |
+
else:
|
772 |
+
raise TypeError(
|
773 |
+
f"File or filename expected, got '{python._fqtypename(f).decode('UTF-8')}'")
|
774 |
+
except:
|
775 |
+
tree.xmlCharEncCloseFunc(enchandler)
|
776 |
+
raise
|
777 |
+
c_buffer_ret[0] = c_buffer
|
778 |
+
return writer
|
779 |
+
|
780 |
+
cdef xmlChar **_convert_ns_prefixes(tree.xmlDict* c_dict, ns_prefixes) except NULL:
|
781 |
+
cdef size_t i, num_ns_prefixes = len(ns_prefixes)
|
782 |
+
# Need to allocate one extra memory block to handle last NULL entry
|
783 |
+
c_ns_prefixes = <xmlChar **>python.lxml_malloc(num_ns_prefixes + 1, sizeof(xmlChar*))
|
784 |
+
if not c_ns_prefixes:
|
785 |
+
raise MemoryError()
|
786 |
+
i = 0
|
787 |
+
try:
|
788 |
+
for prefix in ns_prefixes:
|
789 |
+
prefix_utf = _utf8(prefix)
|
790 |
+
c_prefix = tree.xmlDictExists(c_dict, _xcstr(prefix_utf), len(prefix_utf))
|
791 |
+
if c_prefix:
|
792 |
+
# unknown prefixes do not need to get serialised
|
793 |
+
c_ns_prefixes[i] = <xmlChar*>c_prefix
|
794 |
+
i += 1
|
795 |
+
except:
|
796 |
+
python.lxml_free(c_ns_prefixes)
|
797 |
+
raise
|
798 |
+
|
799 |
+
c_ns_prefixes[i] = NULL # append end marker
|
800 |
+
return c_ns_prefixes
|
801 |
+
|
802 |
+
cdef _tofilelikeC14N(f, _Element element, bint exclusive, bint with_comments,
|
803 |
+
int compression, inclusive_ns_prefixes):
|
804 |
+
cdef _FilelikeWriter writer = None
|
805 |
+
cdef tree.xmlOutputBuffer* c_buffer
|
806 |
+
cdef xmlChar **c_inclusive_ns_prefixes = NULL
|
807 |
+
cdef char* c_filename
|
808 |
+
cdef xmlDoc* c_base_doc
|
809 |
+
cdef xmlDoc* c_doc
|
810 |
+
cdef int bytes_count, error = 0
|
811 |
+
|
812 |
+
c_base_doc = element._c_node.doc
|
813 |
+
c_doc = _fakeRootDoc(c_base_doc, element._c_node)
|
814 |
+
try:
|
815 |
+
c_inclusive_ns_prefixes = (
|
816 |
+
_convert_ns_prefixes(c_doc.dict, inclusive_ns_prefixes)
|
817 |
+
if inclusive_ns_prefixes else NULL)
|
818 |
+
|
819 |
+
f = _getFSPathOrObject(f)
|
820 |
+
if _isString(f):
|
821 |
+
filename8 = _encodeFilename(f)
|
822 |
+
c_filename = _cstr(filename8)
|
823 |
+
with nogil:
|
824 |
+
error = c14n.xmlC14NDocSave(
|
825 |
+
c_doc, NULL, exclusive, c_inclusive_ns_prefixes,
|
826 |
+
with_comments, c_filename, compression)
|
827 |
+
elif hasattr(f, 'write'):
|
828 |
+
writer = _FilelikeWriter(f, compression=compression)
|
829 |
+
c_buffer = writer._createOutputBuffer(NULL)
|
830 |
+
try:
|
831 |
+
with writer.error_log:
|
832 |
+
bytes_count = c14n.xmlC14NDocSaveTo(
|
833 |
+
c_doc, NULL, exclusive, c_inclusive_ns_prefixes,
|
834 |
+
with_comments, c_buffer)
|
835 |
+
finally:
|
836 |
+
error = tree.xmlOutputBufferClose(c_buffer)
|
837 |
+
if bytes_count < 0:
|
838 |
+
error = bytes_count
|
839 |
+
elif error != -1:
|
840 |
+
error = xmlerror.XML_ERR_OK
|
841 |
+
else:
|
842 |
+
raise TypeError(f"File or filename expected, got '{python._fqtypename(f).decode('UTF-8')}'")
|
843 |
+
finally:
|
844 |
+
_destroyFakeDoc(c_base_doc, c_doc)
|
845 |
+
if c_inclusive_ns_prefixes is not NULL:
|
846 |
+
python.lxml_free(c_inclusive_ns_prefixes)
|
847 |
+
|
848 |
+
if writer is not None:
|
849 |
+
writer._exc_context._raise_if_stored()
|
850 |
+
|
851 |
+
if error < 0:
|
852 |
+
message = "C14N failed"
|
853 |
+
if writer is not None:
|
854 |
+
errors = writer.error_log
|
855 |
+
if len(errors):
|
856 |
+
message = errors[0].message
|
857 |
+
raise C14NError(message)
|
858 |
+
|
859 |
+
|
860 |
+
# C14N 2.0
|
861 |
+
|
862 |
+
def canonicalize(xml_data=None, *, out=None, from_file=None, **options):
|
863 |
+
"""Convert XML to its C14N 2.0 serialised form.
|
864 |
+
|
865 |
+
If *out* is provided, it must be a file or file-like object that receives
|
866 |
+
the serialised canonical XML output (text, not bytes) through its ``.write()``
|
867 |
+
method. To write to a file, open it in text mode with encoding "utf-8".
|
868 |
+
If *out* is not provided, this function returns the output as text string.
|
869 |
+
|
870 |
+
Either *xml_data* (an XML string, tree or Element) or *file*
|
871 |
+
(a file path or file-like object) must be provided as input.
|
872 |
+
|
873 |
+
The configuration options are the same as for the ``C14NWriterTarget``.
|
874 |
+
"""
|
875 |
+
if xml_data is None and from_file is None:
|
876 |
+
raise ValueError("Either 'xml_data' or 'from_file' must be provided as input")
|
877 |
+
|
878 |
+
sio = None
|
879 |
+
if out is None:
|
880 |
+
sio = out = StringIO()
|
881 |
+
|
882 |
+
target = C14NWriterTarget(out.write, **options)
|
883 |
+
|
884 |
+
if xml_data is not None and not isinstance(xml_data, basestring):
|
885 |
+
_tree_to_target(xml_data, target)
|
886 |
+
return sio.getvalue() if sio is not None else None
|
887 |
+
|
888 |
+
cdef _FeedParser parser = XMLParser(
|
889 |
+
target=target,
|
890 |
+
attribute_defaults=True,
|
891 |
+
collect_ids=False,
|
892 |
+
)
|
893 |
+
|
894 |
+
if xml_data is not None:
|
895 |
+
parser.feed(xml_data)
|
896 |
+
parser.close()
|
897 |
+
elif from_file is not None:
|
898 |
+
try:
|
899 |
+
_parseDocument(from_file, parser, base_url=None)
|
900 |
+
except _TargetParserResult:
|
901 |
+
pass
|
902 |
+
|
903 |
+
return sio.getvalue() if sio is not None else None
|
904 |
+
|
905 |
+
|
906 |
+
cdef _tree_to_target(element, target):
|
907 |
+
for event, elem in iterwalk(element, events=('start', 'end', 'start-ns', 'comment', 'pi')):
|
908 |
+
text = None
|
909 |
+
if event == 'start':
|
910 |
+
target.start(elem.tag, elem.attrib)
|
911 |
+
text = elem.text
|
912 |
+
elif event == 'end':
|
913 |
+
target.end(elem.tag)
|
914 |
+
text = elem.tail
|
915 |
+
elif event == 'start-ns':
|
916 |
+
target.start_ns(*elem)
|
917 |
+
continue
|
918 |
+
elif event == 'comment':
|
919 |
+
target.comment(elem.text)
|
920 |
+
text = elem.tail
|
921 |
+
elif event == 'pi':
|
922 |
+
target.pi(elem.target, elem.text)
|
923 |
+
text = elem.tail
|
924 |
+
if text:
|
925 |
+
target.data(text)
|
926 |
+
return target.close()
|
927 |
+
|
928 |
+
|
929 |
+
cdef object _looks_like_prefix_name = re.compile(r'^\w+:\w+$', re.UNICODE).match
|
930 |
+
|
931 |
+
|
932 |
+
cdef class C14NWriterTarget:
|
933 |
+
"""
|
934 |
+
Canonicalization writer target for the XMLParser.
|
935 |
+
|
936 |
+
Serialises parse events to XML C14N 2.0.
|
937 |
+
|
938 |
+
Configuration options:
|
939 |
+
|
940 |
+
- *with_comments*: set to true to include comments
|
941 |
+
- *strip_text*: set to true to strip whitespace before and after text content
|
942 |
+
- *rewrite_prefixes*: set to true to replace namespace prefixes by "n{number}"
|
943 |
+
- *qname_aware_tags*: a set of qname aware tag names in which prefixes
|
944 |
+
should be replaced in text content
|
945 |
+
- *qname_aware_attrs*: a set of qname aware attribute names in which prefixes
|
946 |
+
should be replaced in text content
|
947 |
+
- *exclude_attrs*: a set of attribute names that should not be serialised
|
948 |
+
- *exclude_tags*: a set of tag names that should not be serialised
|
949 |
+
"""
|
950 |
+
cdef object _write
|
951 |
+
cdef list _data
|
952 |
+
cdef set _qname_aware_tags
|
953 |
+
cdef object _find_qname_aware_attrs
|
954 |
+
cdef list _declared_ns_stack
|
955 |
+
cdef list _ns_stack
|
956 |
+
cdef dict _prefix_map
|
957 |
+
cdef list _preserve_space
|
958 |
+
cdef tuple _pending_start
|
959 |
+
cdef set _exclude_tags
|
960 |
+
cdef set _exclude_attrs
|
961 |
+
cdef Py_ssize_t _ignored_depth
|
962 |
+
cdef bint _with_comments
|
963 |
+
cdef bint _strip_text
|
964 |
+
cdef bint _rewrite_prefixes
|
965 |
+
cdef bint _root_seen
|
966 |
+
cdef bint _root_done
|
967 |
+
|
968 |
+
def __init__(self, write, *,
|
969 |
+
with_comments=False, strip_text=False, rewrite_prefixes=False,
|
970 |
+
qname_aware_tags=None, qname_aware_attrs=None,
|
971 |
+
exclude_attrs=None, exclude_tags=None):
|
972 |
+
self._write = write
|
973 |
+
self._data = []
|
974 |
+
self._with_comments = with_comments
|
975 |
+
self._strip_text = strip_text
|
976 |
+
self._exclude_attrs = set(exclude_attrs) if exclude_attrs else None
|
977 |
+
self._exclude_tags = set(exclude_tags) if exclude_tags else None
|
978 |
+
|
979 |
+
self._rewrite_prefixes = rewrite_prefixes
|
980 |
+
if qname_aware_tags:
|
981 |
+
self._qname_aware_tags = set(qname_aware_tags)
|
982 |
+
else:
|
983 |
+
self._qname_aware_tags = None
|
984 |
+
if qname_aware_attrs:
|
985 |
+
self._find_qname_aware_attrs = set(qname_aware_attrs).intersection
|
986 |
+
else:
|
987 |
+
self._find_qname_aware_attrs = None
|
988 |
+
|
989 |
+
# Stack with globally and newly declared namespaces as (uri, prefix) pairs.
|
990 |
+
self._declared_ns_stack = [[
|
991 |
+
("http://www.w3.org/XML/1998/namespace", "xml"),
|
992 |
+
]]
|
993 |
+
# Stack with user declared namespace prefixes as (uri, prefix) pairs.
|
994 |
+
self._ns_stack = []
|
995 |
+
if not rewrite_prefixes:
|
996 |
+
self._ns_stack.append(_DEFAULT_NAMESPACE_PREFIXES_ITEMS)
|
997 |
+
self._ns_stack.append([])
|
998 |
+
self._prefix_map = {}
|
999 |
+
self._preserve_space = [False]
|
1000 |
+
self._pending_start = None
|
1001 |
+
self._ignored_depth = 0
|
1002 |
+
self._root_seen = False
|
1003 |
+
self._root_done = False
|
1004 |
+
|
1005 |
+
def _iter_namespaces(self, ns_stack):
|
1006 |
+
for namespaces in reversed(ns_stack):
|
1007 |
+
if namespaces: # almost no element declares new namespaces
|
1008 |
+
yield from namespaces
|
1009 |
+
|
1010 |
+
cdef _resolve_prefix_name(self, prefixed_name):
|
1011 |
+
prefix, name = prefixed_name.split(':', 1)
|
1012 |
+
for uri, p in self._iter_namespaces(self._ns_stack):
|
1013 |
+
if p == prefix:
|
1014 |
+
return f'{{{uri}}}{name}'
|
1015 |
+
raise ValueError(f'Prefix {prefix} of QName "{prefixed_name}" is not declared in scope')
|
1016 |
+
|
1017 |
+
cdef _qname(self, qname, uri=None):
|
1018 |
+
if uri is None:
|
1019 |
+
uri, tag = qname[1:].rsplit('}', 1) if qname[:1] == '{' else ('', qname)
|
1020 |
+
else:
|
1021 |
+
tag = qname
|
1022 |
+
|
1023 |
+
prefixes_seen = set()
|
1024 |
+
for u, prefix in self._iter_namespaces(self._declared_ns_stack):
|
1025 |
+
if u == uri and prefix not in prefixes_seen:
|
1026 |
+
return f'{prefix}:{tag}' if prefix else tag, tag, uri
|
1027 |
+
prefixes_seen.add(prefix)
|
1028 |
+
|
1029 |
+
# Not declared yet => add new declaration.
|
1030 |
+
if self._rewrite_prefixes:
|
1031 |
+
if uri in self._prefix_map:
|
1032 |
+
prefix = self._prefix_map[uri]
|
1033 |
+
else:
|
1034 |
+
prefix = self._prefix_map[uri] = f'n{len(self._prefix_map)}'
|
1035 |
+
self._declared_ns_stack[-1].append((uri, prefix))
|
1036 |
+
return f'{prefix}:{tag}', tag, uri
|
1037 |
+
|
1038 |
+
if not uri and '' not in prefixes_seen:
|
1039 |
+
# No default namespace declared => no prefix needed.
|
1040 |
+
return tag, tag, uri
|
1041 |
+
|
1042 |
+
for u, prefix in self._iter_namespaces(self._ns_stack):
|
1043 |
+
if u == uri:
|
1044 |
+
self._declared_ns_stack[-1].append((uri, prefix))
|
1045 |
+
return f'{prefix}:{tag}' if prefix else tag, tag, uri
|
1046 |
+
|
1047 |
+
if not uri:
|
1048 |
+
# As soon as a default namespace is defined,
|
1049 |
+
# anything that has no namespace (and thus, no prefix) goes there.
|
1050 |
+
return tag, tag, uri
|
1051 |
+
|
1052 |
+
raise ValueError(f'Namespace "{uri}" of name "{tag}" is not declared in scope')
|
1053 |
+
|
1054 |
+
def data(self, data):
|
1055 |
+
if not self._ignored_depth:
|
1056 |
+
self._data.append(data)
|
1057 |
+
|
1058 |
+
cdef _flush(self):
|
1059 |
+
cdef unicode data = ''.join(self._data)
|
1060 |
+
del self._data[:]
|
1061 |
+
if self._strip_text and not self._preserve_space[-1]:
|
1062 |
+
data = data.strip()
|
1063 |
+
if self._pending_start is not None:
|
1064 |
+
(tag, attrs, new_namespaces), self._pending_start = self._pending_start, None
|
1065 |
+
qname_text = data if ':' in data and _looks_like_prefix_name(data) else None
|
1066 |
+
self._start(tag, attrs, new_namespaces, qname_text)
|
1067 |
+
if qname_text is not None:
|
1068 |
+
return
|
1069 |
+
if data and self._root_seen:
|
1070 |
+
self._write(_escape_cdata_c14n(data))
|
1071 |
+
|
1072 |
+
def start_ns(self, prefix, uri):
|
1073 |
+
if self._ignored_depth:
|
1074 |
+
return
|
1075 |
+
# we may have to resolve qnames in text content
|
1076 |
+
if self._data:
|
1077 |
+
self._flush()
|
1078 |
+
self._ns_stack[-1].append((uri, prefix))
|
1079 |
+
|
1080 |
+
def start(self, tag, attrs):
|
1081 |
+
if self._exclude_tags is not None and (
|
1082 |
+
self._ignored_depth or tag in self._exclude_tags):
|
1083 |
+
self._ignored_depth += 1
|
1084 |
+
return
|
1085 |
+
if self._data:
|
1086 |
+
self._flush()
|
1087 |
+
|
1088 |
+
new_namespaces = []
|
1089 |
+
self._declared_ns_stack.append(new_namespaces)
|
1090 |
+
|
1091 |
+
if self._qname_aware_tags is not None and tag in self._qname_aware_tags:
|
1092 |
+
# Need to parse text first to see if it requires a prefix declaration.
|
1093 |
+
self._pending_start = (tag, attrs, new_namespaces)
|
1094 |
+
return
|
1095 |
+
self._start(tag, attrs, new_namespaces)
|
1096 |
+
|
1097 |
+
cdef _start(self, tag, attrs, new_namespaces, qname_text=None):
|
1098 |
+
if self._exclude_attrs is not None and attrs:
|
1099 |
+
attrs = {k: v for k, v in attrs.items() if k not in self._exclude_attrs}
|
1100 |
+
|
1101 |
+
qnames = {tag, *attrs}
|
1102 |
+
resolved_names = {}
|
1103 |
+
|
1104 |
+
# Resolve prefixes in attribute and tag text.
|
1105 |
+
if qname_text is not None:
|
1106 |
+
qname = resolved_names[qname_text] = self._resolve_prefix_name(qname_text)
|
1107 |
+
qnames.add(qname)
|
1108 |
+
if self._find_qname_aware_attrs is not None and attrs:
|
1109 |
+
qattrs = self._find_qname_aware_attrs(attrs)
|
1110 |
+
if qattrs:
|
1111 |
+
for attr_name in qattrs:
|
1112 |
+
value = attrs[attr_name]
|
1113 |
+
if _looks_like_prefix_name(value):
|
1114 |
+
qname = resolved_names[value] = self._resolve_prefix_name(value)
|
1115 |
+
qnames.add(qname)
|
1116 |
+
else:
|
1117 |
+
qattrs = None
|
1118 |
+
else:
|
1119 |
+
qattrs = None
|
1120 |
+
|
1121 |
+
# Assign prefixes in lexicographical order of used URIs.
|
1122 |
+
parsed_qnames = {n: self._qname(n) for n in sorted(
|
1123 |
+
qnames, key=lambda n: n.split('}', 1))}
|
1124 |
+
|
1125 |
+
# Write namespace declarations in prefix order ...
|
1126 |
+
if new_namespaces:
|
1127 |
+
attr_list = [
|
1128 |
+
('xmlns:' + prefix if prefix else 'xmlns', uri)
|
1129 |
+
for uri, prefix in new_namespaces
|
1130 |
+
]
|
1131 |
+
attr_list.sort()
|
1132 |
+
else:
|
1133 |
+
# almost always empty
|
1134 |
+
attr_list = []
|
1135 |
+
|
1136 |
+
# ... followed by attributes in URI+name order
|
1137 |
+
if attrs:
|
1138 |
+
for k, v in sorted(attrs.items()):
|
1139 |
+
if qattrs is not None and k in qattrs and v in resolved_names:
|
1140 |
+
v = parsed_qnames[resolved_names[v]][0]
|
1141 |
+
attr_qname, attr_name, uri = parsed_qnames[k]
|
1142 |
+
# No prefix for attributes in default ('') namespace.
|
1143 |
+
attr_list.append((attr_qname if uri else attr_name, v))
|
1144 |
+
|
1145 |
+
# Honour xml:space attributes.
|
1146 |
+
space_behaviour = attrs.get('{http://www.w3.org/XML/1998/namespace}space')
|
1147 |
+
self._preserve_space.append(
|
1148 |
+
space_behaviour == 'preserve' if space_behaviour
|
1149 |
+
else self._preserve_space[-1])
|
1150 |
+
|
1151 |
+
# Write the tag.
|
1152 |
+
write = self._write
|
1153 |
+
write('<' + parsed_qnames[tag][0])
|
1154 |
+
if attr_list:
|
1155 |
+
write(''.join([f' {k}="{_escape_attrib_c14n(v)}"' for k, v in attr_list]))
|
1156 |
+
write('>')
|
1157 |
+
|
1158 |
+
# Write the resolved qname text content.
|
1159 |
+
if qname_text is not None:
|
1160 |
+
write(_escape_cdata_c14n(parsed_qnames[resolved_names[qname_text]][0]))
|
1161 |
+
|
1162 |
+
self._root_seen = True
|
1163 |
+
self._ns_stack.append([])
|
1164 |
+
|
1165 |
+
def end(self, tag):
|
1166 |
+
if self._ignored_depth:
|
1167 |
+
self._ignored_depth -= 1
|
1168 |
+
return
|
1169 |
+
if self._data:
|
1170 |
+
self._flush()
|
1171 |
+
self._write(f'</{self._qname(tag)[0]}>')
|
1172 |
+
self._preserve_space.pop()
|
1173 |
+
self._root_done = len(self._preserve_space) == 1
|
1174 |
+
self._declared_ns_stack.pop()
|
1175 |
+
self._ns_stack.pop()
|
1176 |
+
|
1177 |
+
def comment(self, text):
|
1178 |
+
if not self._with_comments:
|
1179 |
+
return
|
1180 |
+
if self._ignored_depth:
|
1181 |
+
return
|
1182 |
+
if self._root_done:
|
1183 |
+
self._write('\n')
|
1184 |
+
elif self._root_seen and self._data:
|
1185 |
+
self._flush()
|
1186 |
+
self._write(f'<!--{_escape_cdata_c14n(text)}-->')
|
1187 |
+
if not self._root_seen:
|
1188 |
+
self._write('\n')
|
1189 |
+
|
1190 |
+
def pi(self, target, data):
|
1191 |
+
if self._ignored_depth:
|
1192 |
+
return
|
1193 |
+
if self._root_done:
|
1194 |
+
self._write('\n')
|
1195 |
+
elif self._root_seen and self._data:
|
1196 |
+
self._flush()
|
1197 |
+
self._write(
|
1198 |
+
f'<?{target} {_escape_cdata_c14n(data)}?>' if data else f'<?{target}?>')
|
1199 |
+
if not self._root_seen:
|
1200 |
+
self._write('\n')
|
1201 |
+
|
1202 |
+
def close(self):
|
1203 |
+
return None
|
1204 |
+
|
1205 |
+
|
1206 |
+
cdef _raise_serialization_error(text):
|
1207 |
+
raise TypeError("cannot serialize %r (type %s)" % (text, type(text).__name__))
|
1208 |
+
|
1209 |
+
|
1210 |
+
cdef unicode _escape_cdata_c14n(stext):
|
1211 |
+
# escape character data
|
1212 |
+
cdef unicode text
|
1213 |
+
cdef Py_UCS4 ch
|
1214 |
+
cdef Py_ssize_t start = 0, pos = 0
|
1215 |
+
cdef list substrings = None
|
1216 |
+
try:
|
1217 |
+
text = unicode(stext)
|
1218 |
+
except (TypeError, AttributeError):
|
1219 |
+
return _raise_serialization_error(stext)
|
1220 |
+
|
1221 |
+
for pos, ch in enumerate(text):
|
1222 |
+
if ch == '&':
|
1223 |
+
escape = '&'
|
1224 |
+
elif ch == '<':
|
1225 |
+
escape = '<'
|
1226 |
+
elif ch == '>':
|
1227 |
+
escape = '>'
|
1228 |
+
elif ch == '\r':
|
1229 |
+
escape = '
'
|
1230 |
+
else:
|
1231 |
+
continue
|
1232 |
+
|
1233 |
+
if substrings is None:
|
1234 |
+
substrings = []
|
1235 |
+
if pos > start:
|
1236 |
+
substrings.append(text[start:pos])
|
1237 |
+
substrings.append(escape)
|
1238 |
+
start = pos + 1
|
1239 |
+
|
1240 |
+
if substrings is None:
|
1241 |
+
return text
|
1242 |
+
if pos >= start:
|
1243 |
+
substrings.append(text[start:pos+1])
|
1244 |
+
return ''.join(substrings)
|
1245 |
+
|
1246 |
+
|
1247 |
+
cdef unicode _escape_attrib_c14n(stext):
|
1248 |
+
# escape attribute value
|
1249 |
+
cdef unicode text
|
1250 |
+
cdef Py_UCS4 ch
|
1251 |
+
cdef Py_ssize_t start = 0, pos = 0
|
1252 |
+
cdef list substrings = None
|
1253 |
+
try:
|
1254 |
+
text = unicode(stext)
|
1255 |
+
except (TypeError, AttributeError):
|
1256 |
+
return _raise_serialization_error(stext)
|
1257 |
+
|
1258 |
+
for pos, ch in enumerate(text):
|
1259 |
+
if ch == '&':
|
1260 |
+
escape = '&'
|
1261 |
+
elif ch == '<':
|
1262 |
+
escape = '<'
|
1263 |
+
elif ch == '"':
|
1264 |
+
escape = '"'
|
1265 |
+
elif ch == '\t':
|
1266 |
+
escape = '	'
|
1267 |
+
elif ch == '\n':
|
1268 |
+
escape = '
'
|
1269 |
+
elif ch == '\r':
|
1270 |
+
escape = '
'
|
1271 |
+
else:
|
1272 |
+
continue
|
1273 |
+
|
1274 |
+
if substrings is None:
|
1275 |
+
substrings = []
|
1276 |
+
if pos > start:
|
1277 |
+
substrings.append(text[start:pos])
|
1278 |
+
substrings.append(escape)
|
1279 |
+
start = pos + 1
|
1280 |
+
|
1281 |
+
if substrings is None:
|
1282 |
+
return text
|
1283 |
+
if pos >= start:
|
1284 |
+
substrings.append(text[start:pos+1])
|
1285 |
+
return ''.join(substrings)
|
1286 |
+
|
1287 |
+
|
1288 |
+
# incremental serialisation
|
1289 |
+
|
1290 |
+
cdef class xmlfile:
|
1291 |
+
"""xmlfile(self, output_file, encoding=None, compression=None, close=False, buffered=True)
|
1292 |
+
|
1293 |
+
A simple mechanism for incremental XML serialisation.
|
1294 |
+
|
1295 |
+
Usage example::
|
1296 |
+
|
1297 |
+
with xmlfile("somefile.xml", encoding='utf-8') as xf:
|
1298 |
+
xf.write_declaration(standalone=True)
|
1299 |
+
xf.write_doctype('<!DOCTYPE root SYSTEM "some.dtd">')
|
1300 |
+
|
1301 |
+
# generate an element (the root element)
|
1302 |
+
with xf.element('root'):
|
1303 |
+
# write a complete Element into the open root element
|
1304 |
+
xf.write(etree.Element('test'))
|
1305 |
+
|
1306 |
+
# generate and write more Elements, e.g. through iterparse
|
1307 |
+
for element in generate_some_elements():
|
1308 |
+
# serialise generated elements into the XML file
|
1309 |
+
xf.write(element)
|
1310 |
+
|
1311 |
+
# or write multiple Elements or strings at once
|
1312 |
+
xf.write(etree.Element('start'), "text", etree.Element('end'))
|
1313 |
+
|
1314 |
+
If 'output_file' is a file(-like) object, passing ``close=True`` will
|
1315 |
+
close it when exiting the context manager. By default, it is left
|
1316 |
+
to the owner to do that. When a file path is used, lxml will take care
|
1317 |
+
of opening and closing the file itself. Also, when a compression level
|
1318 |
+
is set, lxml will deliberately close the file to make sure all data gets
|
1319 |
+
compressed and written.
|
1320 |
+
|
1321 |
+
Setting ``buffered=False`` will flush the output after each operation,
|
1322 |
+
such as opening or closing an ``xf.element()`` block or calling
|
1323 |
+
``xf.write()``. Alternatively, calling ``xf.flush()`` can be used to
|
1324 |
+
explicitly flush any pending output when buffering is enabled.
|
1325 |
+
"""
|
1326 |
+
cdef object output_file
|
1327 |
+
cdef bytes encoding
|
1328 |
+
cdef _IncrementalFileWriter writer
|
1329 |
+
cdef _AsyncIncrementalFileWriter async_writer
|
1330 |
+
cdef int compresslevel
|
1331 |
+
cdef bint close
|
1332 |
+
cdef bint buffered
|
1333 |
+
cdef int method
|
1334 |
+
|
1335 |
+
def __init__(self, output_file not None, encoding=None, compression=None,
|
1336 |
+
close=False, buffered=True):
|
1337 |
+
self.output_file = output_file
|
1338 |
+
self.encoding = _utf8orNone(encoding)
|
1339 |
+
self.compresslevel = compression or 0
|
1340 |
+
self.close = close
|
1341 |
+
self.buffered = buffered
|
1342 |
+
self.method = OUTPUT_METHOD_XML
|
1343 |
+
|
1344 |
+
def __enter__(self):
|
1345 |
+
assert self.output_file is not None
|
1346 |
+
self.writer = _IncrementalFileWriter(
|
1347 |
+
self.output_file, self.encoding, self.compresslevel,
|
1348 |
+
self.close, self.buffered, self.method)
|
1349 |
+
return self.writer
|
1350 |
+
|
1351 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
1352 |
+
if self.writer is not None:
|
1353 |
+
old_writer, self.writer = self.writer, None
|
1354 |
+
raise_on_error = exc_type is None
|
1355 |
+
old_writer._close(raise_on_error)
|
1356 |
+
if self.close:
|
1357 |
+
self.output_file = None
|
1358 |
+
|
1359 |
+
async def __aenter__(self):
|
1360 |
+
assert self.output_file is not None
|
1361 |
+
if isinstance(self.output_file, basestring):
|
1362 |
+
raise TypeError("Cannot asynchronously write to a plain file")
|
1363 |
+
if not hasattr(self.output_file, 'write'):
|
1364 |
+
raise TypeError("Output file needs an async .write() method")
|
1365 |
+
self.async_writer = _AsyncIncrementalFileWriter(
|
1366 |
+
self.output_file, self.encoding, self.compresslevel,
|
1367 |
+
self.close, self.buffered, self.method)
|
1368 |
+
return self.async_writer
|
1369 |
+
|
1370 |
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
1371 |
+
if self.async_writer is not None:
|
1372 |
+
old_writer, self.async_writer = self.async_writer, None
|
1373 |
+
raise_on_error = exc_type is None
|
1374 |
+
await old_writer._close(raise_on_error)
|
1375 |
+
if self.close:
|
1376 |
+
self.output_file = None
|
1377 |
+
|
1378 |
+
|
1379 |
+
cdef class htmlfile(xmlfile):
|
1380 |
+
"""htmlfile(self, output_file, encoding=None, compression=None, close=False, buffered=True)
|
1381 |
+
|
1382 |
+
A simple mechanism for incremental HTML serialisation. Works the same as
|
1383 |
+
xmlfile.
|
1384 |
+
"""
|
1385 |
+
def __init__(self, *args, **kwargs):
|
1386 |
+
super().__init__(*args, **kwargs)
|
1387 |
+
self.method = OUTPUT_METHOD_HTML
|
1388 |
+
|
1389 |
+
|
1390 |
+
cdef enum _IncrementalFileWriterStatus:
|
1391 |
+
WRITER_STARTING = 0
|
1392 |
+
WRITER_DECL_WRITTEN = 1
|
1393 |
+
WRITER_DTD_WRITTEN = 2
|
1394 |
+
WRITER_IN_ELEMENT = 3
|
1395 |
+
WRITER_FINISHED = 4
|
1396 |
+
|
1397 |
+
|
1398 |
+
@cython.final
|
1399 |
+
@cython.internal
|
1400 |
+
cdef class _IncrementalFileWriter:
|
1401 |
+
cdef tree.xmlOutputBuffer* _c_out
|
1402 |
+
cdef bytes _encoding
|
1403 |
+
cdef const_char* _c_encoding
|
1404 |
+
cdef _FilelikeWriter _target
|
1405 |
+
cdef list _element_stack
|
1406 |
+
cdef int _status
|
1407 |
+
cdef int _method
|
1408 |
+
cdef bint _buffered
|
1409 |
+
|
1410 |
+
def __cinit__(self, outfile, bytes encoding, int compresslevel, bint close,
|
1411 |
+
bint buffered, int method):
|
1412 |
+
self._status = WRITER_STARTING
|
1413 |
+
self._element_stack = []
|
1414 |
+
if encoding is None:
|
1415 |
+
encoding = b'ASCII'
|
1416 |
+
self._encoding = encoding
|
1417 |
+
self._c_encoding = _cstr(encoding) if encoding is not None else NULL
|
1418 |
+
self._buffered = buffered
|
1419 |
+
self._target = _create_output_buffer(
|
1420 |
+
outfile, self._c_encoding, compresslevel, &self._c_out, close)
|
1421 |
+
self._method = method
|
1422 |
+
|
1423 |
+
def __dealloc__(self):
|
1424 |
+
if self._c_out is not NULL:
|
1425 |
+
tree.xmlOutputBufferClose(self._c_out)
|
1426 |
+
|
1427 |
+
def write_declaration(self, version=None, standalone=None, doctype=None):
|
1428 |
+
"""write_declaration(self, version=None, standalone=None, doctype=None)
|
1429 |
+
|
1430 |
+
Write an XML declaration and (optionally) a doctype into the file.
|
1431 |
+
"""
|
1432 |
+
assert self._c_out is not NULL
|
1433 |
+
cdef const_xmlChar* c_version
|
1434 |
+
cdef int c_standalone
|
1435 |
+
if self._method != OUTPUT_METHOD_XML:
|
1436 |
+
raise LxmlSyntaxError("only XML documents have declarations")
|
1437 |
+
if self._status >= WRITER_DECL_WRITTEN:
|
1438 |
+
raise LxmlSyntaxError("XML declaration already written")
|
1439 |
+
version = _utf8orNone(version)
|
1440 |
+
c_version = _xcstr(version) if version is not None else NULL
|
1441 |
+
doctype = _utf8orNone(doctype)
|
1442 |
+
if standalone is None:
|
1443 |
+
c_standalone = -1
|
1444 |
+
else:
|
1445 |
+
c_standalone = 1 if standalone else 0
|
1446 |
+
_writeDeclarationToBuffer(self._c_out, c_version, self._c_encoding, c_standalone)
|
1447 |
+
if doctype is not None:
|
1448 |
+
_writeDoctype(self._c_out, _xcstr(doctype))
|
1449 |
+
self._status = WRITER_DTD_WRITTEN
|
1450 |
+
else:
|
1451 |
+
self._status = WRITER_DECL_WRITTEN
|
1452 |
+
if not self._buffered:
|
1453 |
+
tree.xmlOutputBufferFlush(self._c_out)
|
1454 |
+
self._handle_error(self._c_out.error)
|
1455 |
+
|
1456 |
+
def write_doctype(self, doctype):
|
1457 |
+
"""write_doctype(self, doctype)
|
1458 |
+
|
1459 |
+
Writes the given doctype declaration verbatimly into the file.
|
1460 |
+
"""
|
1461 |
+
assert self._c_out is not NULL
|
1462 |
+
if doctype is None:
|
1463 |
+
return
|
1464 |
+
if self._status >= WRITER_DTD_WRITTEN:
|
1465 |
+
raise LxmlSyntaxError("DOCTYPE already written or cannot write it here")
|
1466 |
+
doctype = _utf8(doctype)
|
1467 |
+
_writeDoctype(self._c_out, _xcstr(doctype))
|
1468 |
+
self._status = WRITER_DTD_WRITTEN
|
1469 |
+
if not self._buffered:
|
1470 |
+
tree.xmlOutputBufferFlush(self._c_out)
|
1471 |
+
self._handle_error(self._c_out.error)
|
1472 |
+
|
1473 |
+
def method(self, method):
|
1474 |
+
"""method(self, method)
|
1475 |
+
|
1476 |
+
Returns a context manager that overrides and restores the output method.
|
1477 |
+
method is one of (None, 'xml', 'html') where None means 'xml'.
|
1478 |
+
"""
|
1479 |
+
assert self._c_out is not NULL
|
1480 |
+
c_method = self._method if method is None else _findOutputMethod(method)
|
1481 |
+
return _MethodChanger(self, c_method)
|
1482 |
+
|
1483 |
+
def element(self, tag, attrib=None, nsmap=None, method=None, **_extra):
|
1484 |
+
"""element(self, tag, attrib=None, nsmap=None, method, **_extra)
|
1485 |
+
|
1486 |
+
Returns a context manager that writes an opening and closing tag.
|
1487 |
+
method is one of (None, 'xml', 'html') where None means 'xml'.
|
1488 |
+
"""
|
1489 |
+
assert self._c_out is not NULL
|
1490 |
+
attributes = []
|
1491 |
+
if attrib is not None:
|
1492 |
+
for name, value in _iter_attrib(attrib):
|
1493 |
+
if name not in _extra:
|
1494 |
+
ns, name = _getNsTag(name)
|
1495 |
+
attributes.append((ns, name, _utf8(value)))
|
1496 |
+
if _extra:
|
1497 |
+
for name, value in _extra.iteritems():
|
1498 |
+
ns, name = _getNsTag(name)
|
1499 |
+
attributes.append((ns, name, _utf8(value)))
|
1500 |
+
reversed_nsmap = {}
|
1501 |
+
if nsmap:
|
1502 |
+
for prefix, ns in nsmap.items():
|
1503 |
+
if prefix is not None:
|
1504 |
+
prefix = _utf8(prefix)
|
1505 |
+
_prefixValidOrRaise(prefix)
|
1506 |
+
reversed_nsmap[_utf8(ns)] = prefix
|
1507 |
+
ns, name = _getNsTag(tag)
|
1508 |
+
|
1509 |
+
c_method = self._method if method is None else _findOutputMethod(method)
|
1510 |
+
|
1511 |
+
return _FileWriterElement(self, (ns, name, attributes, reversed_nsmap), c_method)
|
1512 |
+
|
1513 |
+
cdef _write_qname(self, bytes name, bytes prefix):
|
1514 |
+
if prefix: # empty bytes for no prefix (not None to allow sorting)
|
1515 |
+
tree.xmlOutputBufferWrite(self._c_out, len(prefix), _cstr(prefix))
|
1516 |
+
tree.xmlOutputBufferWrite(self._c_out, 1, ':')
|
1517 |
+
tree.xmlOutputBufferWrite(self._c_out, len(name), _cstr(name))
|
1518 |
+
|
1519 |
+
cdef _write_start_element(self, element_config):
|
1520 |
+
if self._status > WRITER_IN_ELEMENT:
|
1521 |
+
raise LxmlSyntaxError("cannot append trailing element to complete XML document")
|
1522 |
+
ns, name, attributes, nsmap = element_config
|
1523 |
+
flat_namespace_map, new_namespaces = self._collect_namespaces(nsmap)
|
1524 |
+
prefix = self._find_prefix(ns, flat_namespace_map, new_namespaces)
|
1525 |
+
tree.xmlOutputBufferWrite(self._c_out, 1, '<')
|
1526 |
+
self._write_qname(name, prefix)
|
1527 |
+
|
1528 |
+
self._write_attributes_and_namespaces(
|
1529 |
+
attributes, flat_namespace_map, new_namespaces)
|
1530 |
+
|
1531 |
+
tree.xmlOutputBufferWrite(self._c_out, 1, '>')
|
1532 |
+
if not self._buffered:
|
1533 |
+
tree.xmlOutputBufferFlush(self._c_out)
|
1534 |
+
self._handle_error(self._c_out.error)
|
1535 |
+
|
1536 |
+
self._element_stack.append((ns, name, prefix, flat_namespace_map))
|
1537 |
+
self._status = WRITER_IN_ELEMENT
|
1538 |
+
|
1539 |
+
cdef _write_attributes_and_namespaces(self, list attributes,
|
1540 |
+
dict flat_namespace_map,
|
1541 |
+
list new_namespaces):
|
1542 |
+
if attributes:
|
1543 |
+
# _find_prefix() may append to new_namespaces => build them first
|
1544 |
+
attributes = [
|
1545 |
+
(self._find_prefix(ns, flat_namespace_map, new_namespaces), name, value)
|
1546 |
+
for ns, name, value in attributes ]
|
1547 |
+
if new_namespaces:
|
1548 |
+
new_namespaces.sort()
|
1549 |
+
self._write_attributes_list(new_namespaces)
|
1550 |
+
if attributes:
|
1551 |
+
self._write_attributes_list(attributes)
|
1552 |
+
|
1553 |
+
cdef _write_attributes_list(self, list attributes):
|
1554 |
+
for prefix, name, value in attributes:
|
1555 |
+
tree.xmlOutputBufferWrite(self._c_out, 1, ' ')
|
1556 |
+
self._write_qname(name, prefix)
|
1557 |
+
tree.xmlOutputBufferWrite(self._c_out, 2, '="')
|
1558 |
+
_write_attr_string(self._c_out, _cstr(value))
|
1559 |
+
|
1560 |
+
tree.xmlOutputBufferWrite(self._c_out, 1, '"')
|
1561 |
+
|
1562 |
+
cdef _write_end_element(self, element_config):
|
1563 |
+
if self._status != WRITER_IN_ELEMENT:
|
1564 |
+
raise LxmlSyntaxError("not in an element")
|
1565 |
+
if not self._element_stack or self._element_stack[-1][:2] != element_config[:2]:
|
1566 |
+
raise LxmlSyntaxError("inconsistent exit action in context manager")
|
1567 |
+
|
1568 |
+
# If previous write operations failed, the context manager exit might still call us.
|
1569 |
+
# That is ok, but we stop writing closing tags and handling errors in that case.
|
1570 |
+
# For all non-I/O errors, we continue writing closing tags if we can.
|
1571 |
+
ok_to_write = self._c_out.error == xmlerror.XML_ERR_OK
|
1572 |
+
|
1573 |
+
name, prefix = self._element_stack.pop()[1:3]
|
1574 |
+
if ok_to_write:
|
1575 |
+
tree.xmlOutputBufferWrite(self._c_out, 2, '</')
|
1576 |
+
self._write_qname(name, prefix)
|
1577 |
+
tree.xmlOutputBufferWrite(self._c_out, 1, '>')
|
1578 |
+
|
1579 |
+
if not self._element_stack:
|
1580 |
+
self._status = WRITER_FINISHED
|
1581 |
+
if ok_to_write:
|
1582 |
+
if not self._buffered:
|
1583 |
+
tree.xmlOutputBufferFlush(self._c_out)
|
1584 |
+
self._handle_error(self._c_out.error)
|
1585 |
+
|
1586 |
+
cdef _find_prefix(self, bytes href, dict flat_namespaces_map, list new_namespaces):
|
1587 |
+
if href is None:
|
1588 |
+
return None
|
1589 |
+
if href in flat_namespaces_map:
|
1590 |
+
return flat_namespaces_map[href]
|
1591 |
+
# need to create a new prefix
|
1592 |
+
prefixes = flat_namespaces_map.values()
|
1593 |
+
i = 0
|
1594 |
+
while True:
|
1595 |
+
prefix = _utf8('ns%d' % i)
|
1596 |
+
if prefix not in prefixes:
|
1597 |
+
new_namespaces.append((b'xmlns', prefix, href))
|
1598 |
+
flat_namespaces_map[href] = prefix
|
1599 |
+
return prefix
|
1600 |
+
i += 1
|
1601 |
+
|
1602 |
+
cdef _collect_namespaces(self, dict nsmap):
|
1603 |
+
new_namespaces = []
|
1604 |
+
flat_namespaces_map = {}
|
1605 |
+
for ns, prefix in nsmap.iteritems():
|
1606 |
+
flat_namespaces_map[ns] = prefix
|
1607 |
+
if prefix is None:
|
1608 |
+
# use empty bytes rather than None to allow sorting
|
1609 |
+
new_namespaces.append((b'', b'xmlns', ns))
|
1610 |
+
else:
|
1611 |
+
new_namespaces.append((b'xmlns', prefix, ns))
|
1612 |
+
# merge in flat namespace map of parent
|
1613 |
+
if self._element_stack:
|
1614 |
+
for ns, prefix in (<dict>self._element_stack[-1][-1]).iteritems():
|
1615 |
+
if flat_namespaces_map.get(ns) is None:
|
1616 |
+
# unknown or empty prefix => prefer a 'real' prefix
|
1617 |
+
flat_namespaces_map[ns] = prefix
|
1618 |
+
return flat_namespaces_map, new_namespaces
|
1619 |
+
|
1620 |
+
def write(self, *args, bint with_tail=True, bint pretty_print=False, method=None):
|
1621 |
+
"""write(self, *args, with_tail=True, pretty_print=False, method=None)
|
1622 |
+
|
1623 |
+
Write subtrees or strings into the file.
|
1624 |
+
|
1625 |
+
If method is not None, it should be one of ('html', 'xml', 'text')
|
1626 |
+
to temporarily override the output method.
|
1627 |
+
"""
|
1628 |
+
assert self._c_out is not NULL
|
1629 |
+
c_method = self._method if method is None else _findOutputMethod(method)
|
1630 |
+
|
1631 |
+
for content in args:
|
1632 |
+
if _isString(content):
|
1633 |
+
if self._status != WRITER_IN_ELEMENT:
|
1634 |
+
if self._status > WRITER_IN_ELEMENT or content.strip():
|
1635 |
+
raise LxmlSyntaxError("not in an element")
|
1636 |
+
bstring = _utf8(content)
|
1637 |
+
if not bstring:
|
1638 |
+
continue
|
1639 |
+
|
1640 |
+
ns, name, _, _ = self._element_stack[-1]
|
1641 |
+
if (c_method == OUTPUT_METHOD_HTML and
|
1642 |
+
ns in (None, b'http://www.w3.org/1999/xhtml') and
|
1643 |
+
name in (b'script', b'style')):
|
1644 |
+
tree.xmlOutputBufferWrite(self._c_out, len(bstring), _cstr(bstring))
|
1645 |
+
|
1646 |
+
else:
|
1647 |
+
tree.xmlOutputBufferWriteEscape(self._c_out, _xcstr(bstring), NULL)
|
1648 |
+
|
1649 |
+
elif iselement(content):
|
1650 |
+
if self._status > WRITER_IN_ELEMENT:
|
1651 |
+
raise LxmlSyntaxError("cannot append trailing element to complete XML document")
|
1652 |
+
_writeNodeToBuffer(self._c_out, (<_Element>content)._c_node,
|
1653 |
+
self._c_encoding, NULL, c_method,
|
1654 |
+
False, False, pretty_print, with_tail, False)
|
1655 |
+
if (<_Element>content)._c_node.type == tree.XML_ELEMENT_NODE:
|
1656 |
+
if not self._element_stack:
|
1657 |
+
self._status = WRITER_FINISHED
|
1658 |
+
|
1659 |
+
elif content is not None:
|
1660 |
+
raise TypeError(
|
1661 |
+
f"got invalid input value of type {type(content)}, expected string or Element")
|
1662 |
+
self._handle_error(self._c_out.error)
|
1663 |
+
if not self._buffered:
|
1664 |
+
tree.xmlOutputBufferFlush(self._c_out)
|
1665 |
+
self._handle_error(self._c_out.error)
|
1666 |
+
|
1667 |
+
def flush(self):
|
1668 |
+
"""flush(self)
|
1669 |
+
|
1670 |
+
Write any pending content of the current output buffer to the stream.
|
1671 |
+
"""
|
1672 |
+
assert self._c_out is not NULL
|
1673 |
+
tree.xmlOutputBufferFlush(self._c_out)
|
1674 |
+
self._handle_error(self._c_out.error)
|
1675 |
+
|
1676 |
+
cdef _close(self, bint raise_on_error):
|
1677 |
+
if raise_on_error:
|
1678 |
+
if self._status < WRITER_IN_ELEMENT:
|
1679 |
+
raise LxmlSyntaxError("no content written")
|
1680 |
+
if self._element_stack:
|
1681 |
+
raise LxmlSyntaxError("pending open tags on close")
|
1682 |
+
error_result = self._c_out.error
|
1683 |
+
if error_result == xmlerror.XML_ERR_OK:
|
1684 |
+
error_result = tree.xmlOutputBufferClose(self._c_out)
|
1685 |
+
if error_result != -1:
|
1686 |
+
error_result = xmlerror.XML_ERR_OK
|
1687 |
+
else:
|
1688 |
+
tree.xmlOutputBufferClose(self._c_out)
|
1689 |
+
self._status = WRITER_FINISHED
|
1690 |
+
self._c_out = NULL
|
1691 |
+
del self._element_stack[:]
|
1692 |
+
if raise_on_error:
|
1693 |
+
self._handle_error(error_result)
|
1694 |
+
|
1695 |
+
cdef _handle_error(self, int error_result):
|
1696 |
+
if error_result != xmlerror.XML_ERR_OK:
|
1697 |
+
if self._target is not None:
|
1698 |
+
self._target._exc_context._raise_if_stored()
|
1699 |
+
_raiseSerialisationError(error_result)
|
1700 |
+
|
1701 |
+
|
1702 |
+
@cython.final
|
1703 |
+
@cython.internal
|
1704 |
+
cdef class _AsyncDataWriter:
|
1705 |
+
cdef list _data
|
1706 |
+
def __cinit__(self):
|
1707 |
+
self._data = []
|
1708 |
+
|
1709 |
+
cdef bytes collect(self):
|
1710 |
+
data = b''.join(self._data)
|
1711 |
+
del self._data[:]
|
1712 |
+
return data
|
1713 |
+
|
1714 |
+
def write(self, data):
|
1715 |
+
self._data.append(data)
|
1716 |
+
|
1717 |
+
def close(self):
|
1718 |
+
pass
|
1719 |
+
|
1720 |
+
|
1721 |
+
@cython.final
|
1722 |
+
@cython.internal
|
1723 |
+
cdef class _AsyncIncrementalFileWriter:
|
1724 |
+
cdef _IncrementalFileWriter _writer
|
1725 |
+
cdef _AsyncDataWriter _buffer
|
1726 |
+
cdef object _async_outfile
|
1727 |
+
cdef int _flush_after_writes
|
1728 |
+
cdef bint _should_close
|
1729 |
+
cdef bint _buffered
|
1730 |
+
|
1731 |
+
def __cinit__(self, async_outfile, bytes encoding, int compresslevel, bint close,
|
1732 |
+
bint buffered, int method):
|
1733 |
+
self._flush_after_writes = 20
|
1734 |
+
self._async_outfile = async_outfile
|
1735 |
+
self._should_close = close
|
1736 |
+
self._buffered = buffered
|
1737 |
+
self._buffer = _AsyncDataWriter()
|
1738 |
+
self._writer = _IncrementalFileWriter(
|
1739 |
+
self._buffer, encoding, compresslevel, close=True, buffered=False, method=method)
|
1740 |
+
|
1741 |
+
cdef bytes _flush(self):
|
1742 |
+
if not self._buffered or len(self._buffer._data) > self._flush_after_writes:
|
1743 |
+
return self._buffer.collect()
|
1744 |
+
return None
|
1745 |
+
|
1746 |
+
async def flush(self):
|
1747 |
+
self._writer.flush()
|
1748 |
+
data = self._buffer.collect()
|
1749 |
+
if data:
|
1750 |
+
await self._async_outfile.write(data)
|
1751 |
+
|
1752 |
+
async def write_declaration(self, version=None, standalone=None, doctype=None):
|
1753 |
+
self._writer.write_declaration(version, standalone, doctype)
|
1754 |
+
data = self._flush()
|
1755 |
+
if data:
|
1756 |
+
await self._async_outfile.write(data)
|
1757 |
+
|
1758 |
+
async def write_doctype(self, doctype):
|
1759 |
+
self._writer.write_doctype(doctype)
|
1760 |
+
data = self._flush()
|
1761 |
+
if data:
|
1762 |
+
await self._async_outfile.write(data)
|
1763 |
+
|
1764 |
+
async def write(self, *args, with_tail=True, pretty_print=False, method=None):
|
1765 |
+
self._writer.write(*args, with_tail=with_tail, pretty_print=pretty_print, method=method)
|
1766 |
+
data = self._flush()
|
1767 |
+
if data:
|
1768 |
+
await self._async_outfile.write(data)
|
1769 |
+
|
1770 |
+
def method(self, method):
|
1771 |
+
return self._writer.method(method)
|
1772 |
+
|
1773 |
+
def element(self, tag, attrib=None, nsmap=None, method=None, **_extra):
|
1774 |
+
element_writer = self._writer.element(tag, attrib, nsmap, method, **_extra)
|
1775 |
+
return _AsyncFileWriterElement(element_writer, self)
|
1776 |
+
|
1777 |
+
async def _close(self, bint raise_on_error):
|
1778 |
+
self._writer._close(raise_on_error)
|
1779 |
+
data = self._buffer.collect()
|
1780 |
+
if data:
|
1781 |
+
await self._async_outfile.write(data)
|
1782 |
+
if self._should_close:
|
1783 |
+
await self._async_outfile.close()
|
1784 |
+
|
1785 |
+
|
1786 |
+
@cython.final
|
1787 |
+
@cython.internal
|
1788 |
+
cdef class _AsyncFileWriterElement:
|
1789 |
+
cdef _FileWriterElement _element_writer
|
1790 |
+
cdef _AsyncIncrementalFileWriter _writer
|
1791 |
+
|
1792 |
+
def __cinit__(self, _FileWriterElement element_writer not None,
|
1793 |
+
_AsyncIncrementalFileWriter writer not None):
|
1794 |
+
self._element_writer = element_writer
|
1795 |
+
self._writer = writer
|
1796 |
+
|
1797 |
+
async def __aenter__(self):
|
1798 |
+
self._element_writer.__enter__()
|
1799 |
+
data = self._writer._flush()
|
1800 |
+
if data:
|
1801 |
+
await self._writer._async_outfile.write(data)
|
1802 |
+
|
1803 |
+
async def __aexit__(self, *args):
|
1804 |
+
self._element_writer.__exit__(*args)
|
1805 |
+
data = self._writer._flush()
|
1806 |
+
if data:
|
1807 |
+
await self._writer._async_outfile.write(data)
|
1808 |
+
|
1809 |
+
|
1810 |
+
@cython.final
|
1811 |
+
@cython.internal
|
1812 |
+
@cython.freelist(8)
|
1813 |
+
cdef class _FileWriterElement:
|
1814 |
+
cdef _IncrementalFileWriter _writer
|
1815 |
+
cdef object _element
|
1816 |
+
cdef int _new_method
|
1817 |
+
cdef int _old_method
|
1818 |
+
|
1819 |
+
def __cinit__(self, _IncrementalFileWriter writer not None, element_config, int method):
|
1820 |
+
self._writer = writer
|
1821 |
+
self._element = element_config
|
1822 |
+
self._new_method = method
|
1823 |
+
self._old_method = writer._method
|
1824 |
+
|
1825 |
+
def __enter__(self):
|
1826 |
+
self._writer._method = self._new_method
|
1827 |
+
self._writer._write_start_element(self._element)
|
1828 |
+
|
1829 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
1830 |
+
self._writer._write_end_element(self._element)
|
1831 |
+
self._writer._method = self._old_method
|
1832 |
+
|
1833 |
+
|
1834 |
+
@cython.final
|
1835 |
+
@cython.internal
|
1836 |
+
@cython.freelist(8)
|
1837 |
+
cdef class _MethodChanger:
|
1838 |
+
cdef _IncrementalFileWriter _writer
|
1839 |
+
cdef int _new_method
|
1840 |
+
cdef int _old_method
|
1841 |
+
cdef bint _entered
|
1842 |
+
cdef bint _exited
|
1843 |
+
|
1844 |
+
def __cinit__(self, _IncrementalFileWriter writer not None, int method):
|
1845 |
+
self._writer = writer
|
1846 |
+
self._new_method = method
|
1847 |
+
self._old_method = writer._method
|
1848 |
+
self._entered = False
|
1849 |
+
self._exited = False
|
1850 |
+
|
1851 |
+
def __enter__(self):
|
1852 |
+
if self._entered:
|
1853 |
+
raise LxmlSyntaxError("Inconsistent enter action in context manager")
|
1854 |
+
self._writer._method = self._new_method
|
1855 |
+
self._entered = True
|
1856 |
+
|
1857 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
1858 |
+
if self._exited:
|
1859 |
+
raise LxmlSyntaxError("Inconsistent exit action in context manager")
|
1860 |
+
if self._writer._method != self._new_method:
|
1861 |
+
raise LxmlSyntaxError("Method changed outside of context manager")
|
1862 |
+
self._writer._method = self._old_method
|
1863 |
+
self._exited = True
|
1864 |
+
|
1865 |
+
async def __aenter__(self):
|
1866 |
+
# for your async convenience
|
1867 |
+
return self.__enter__()
|
1868 |
+
|
1869 |
+
async def __aexit__(self, *args):
|
1870 |
+
# for your async convenience
|
1871 |
+
return self.__exit__(*args)
|
env-llmeval/lib/python3.10/site-packages/lxml/xinclude.pxi
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# XInclude processing
|
2 |
+
|
3 |
+
from lxml.includes cimport xinclude
|
4 |
+
|
5 |
+
|
6 |
+
cdef class XIncludeError(LxmlError):
|
7 |
+
"""Error during XInclude processing.
|
8 |
+
"""
|
9 |
+
|
10 |
+
|
11 |
+
cdef class XInclude:
|
12 |
+
"""XInclude(self)
|
13 |
+
XInclude processor.
|
14 |
+
|
15 |
+
Create an instance and call it on an Element to run XInclude
|
16 |
+
processing.
|
17 |
+
"""
|
18 |
+
cdef _ErrorLog _error_log
|
19 |
+
def __init__(self):
|
20 |
+
self._error_log = _ErrorLog()
|
21 |
+
|
22 |
+
@property
|
23 |
+
def error_log(self):
|
24 |
+
assert self._error_log is not None, "XInclude instance not initialised"
|
25 |
+
return self._error_log.copy()
|
26 |
+
|
27 |
+
def __call__(self, _Element node not None):
|
28 |
+
"__call__(self, node)"
|
29 |
+
# We cannot pass the XML_PARSE_NOXINCNODE option as this would free
|
30 |
+
# the XInclude nodes - there may still be Python references to them!
|
31 |
+
# Therefore, we allow XInclude nodes to be converted to
|
32 |
+
# XML_XINCLUDE_START nodes. XML_XINCLUDE_END nodes are added as
|
33 |
+
# siblings. Tree traversal will simply ignore them as they are not
|
34 |
+
# typed as elements. The included fragment is added between the two,
|
35 |
+
# i.e. as a sibling, which does not conflict with traversal.
|
36 |
+
cdef int result
|
37 |
+
_assertValidNode(node)
|
38 |
+
assert self._error_log is not None, "XInclude processor not initialised"
|
39 |
+
if node._doc._parser is not None:
|
40 |
+
parse_options = node._doc._parser._parse_options
|
41 |
+
context = node._doc._parser._getParserContext()
|
42 |
+
c_context = <void*>context
|
43 |
+
else:
|
44 |
+
parse_options = 0
|
45 |
+
context = None
|
46 |
+
c_context = NULL
|
47 |
+
|
48 |
+
self._error_log.connect()
|
49 |
+
if tree.LIBXML_VERSION < 20704 or not c_context:
|
50 |
+
__GLOBAL_PARSER_CONTEXT.pushImpliedContext(context)
|
51 |
+
with nogil:
|
52 |
+
orig_loader = _register_document_loader()
|
53 |
+
if c_context:
|
54 |
+
result = xinclude.xmlXIncludeProcessTreeFlagsData(
|
55 |
+
node._c_node, parse_options, c_context)
|
56 |
+
else:
|
57 |
+
result = xinclude.xmlXIncludeProcessTree(node._c_node)
|
58 |
+
_reset_document_loader(orig_loader)
|
59 |
+
if tree.LIBXML_VERSION < 20704 or not c_context:
|
60 |
+
__GLOBAL_PARSER_CONTEXT.popImpliedContext()
|
61 |
+
self._error_log.disconnect()
|
62 |
+
|
63 |
+
if result == -1:
|
64 |
+
raise XIncludeError(
|
65 |
+
self._error_log._buildExceptionMessage(
|
66 |
+
"XInclude processing failed"),
|
67 |
+
self._error_log)
|
env-llmeval/lib/python3.10/site-packages/lxml/xmlerror.pxi
ADDED
@@ -0,0 +1,1654 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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2 |
+
|
3 |
+
from lxml.includes cimport xmlerror
|
4 |
+
from lxml cimport cvarargs
|
5 |
+
|
6 |
+
DEF GLOBAL_ERROR_LOG = "_GlobalErrorLog"
|
7 |
+
DEF XSLT_ERROR_LOG = "_XSLTErrorLog"
|
8 |
+
|
9 |
+
# module level API functions
|
10 |
+
|
11 |
+
def clear_error_log():
|
12 |
+
"""clear_error_log()
|
13 |
+
|
14 |
+
Clear the global error log. Note that this log is already bound to a
|
15 |
+
fixed size.
|
16 |
+
|
17 |
+
Note: since lxml 2.2, the global error log is local to a thread
|
18 |
+
and this function will only clear the global error log of the
|
19 |
+
current thread.
|
20 |
+
"""
|
21 |
+
_getThreadErrorLog(GLOBAL_ERROR_LOG).clear()
|
22 |
+
|
23 |
+
|
24 |
+
# setup for global log:
|
25 |
+
|
26 |
+
cdef void _initThreadLogging() noexcept:
|
27 |
+
# Disable generic error lines from libxml2.
|
28 |
+
_connectGenericErrorLog(None)
|
29 |
+
|
30 |
+
# Divert XSLT error messages to the global XSLT error log instead of stderr.
|
31 |
+
xslt.xsltSetGenericErrorFunc(NULL, <xmlerror.xmlGenericErrorFunc>_receiveXSLTError)
|
32 |
+
|
33 |
+
|
34 |
+
# Logging classes
|
35 |
+
|
36 |
+
@cython.final
|
37 |
+
@cython.freelist(16)
|
38 |
+
cdef class _LogEntry:
|
39 |
+
"""A log message entry from an error log.
|
40 |
+
|
41 |
+
Attributes:
|
42 |
+
|
43 |
+
- message: the message text
|
44 |
+
- domain: the domain ID (see lxml.etree.ErrorDomains)
|
45 |
+
- type: the message type ID (see lxml.etree.ErrorTypes)
|
46 |
+
- level: the log level ID (see lxml.etree.ErrorLevels)
|
47 |
+
- line: the line at which the message originated (if applicable)
|
48 |
+
- column: the character column at which the message originated (if applicable)
|
49 |
+
- filename: the name of the file in which the message originated (if applicable)
|
50 |
+
- path: the location in which the error was found (if available)
|
51 |
+
"""
|
52 |
+
cdef readonly int domain
|
53 |
+
cdef readonly int type
|
54 |
+
cdef readonly int level
|
55 |
+
cdef readonly long line
|
56 |
+
cdef readonly int column
|
57 |
+
cdef basestring _message
|
58 |
+
cdef basestring _filename
|
59 |
+
cdef char* _c_message
|
60 |
+
cdef xmlChar* _c_filename
|
61 |
+
cdef xmlChar* _c_path
|
62 |
+
|
63 |
+
def __dealloc__(self):
|
64 |
+
tree.xmlFree(self._c_message)
|
65 |
+
tree.xmlFree(self._c_filename)
|
66 |
+
tree.xmlFree(self._c_path)
|
67 |
+
|
68 |
+
@cython.final
|
69 |
+
cdef int _setError(self, const xmlerror.xmlError* error) except -1:
|
70 |
+
self.domain = error.domain
|
71 |
+
self.type = error.code
|
72 |
+
self.level = <int>error.level
|
73 |
+
self.line = <long>error.line
|
74 |
+
self.column = error.int2
|
75 |
+
self._c_message = NULL
|
76 |
+
self._c_filename = NULL
|
77 |
+
self._c_path = NULL
|
78 |
+
if (error.message is NULL or
|
79 |
+
error.message[0] == b'\0' or
|
80 |
+
error.message[0] == b'\n' and error.message[1] == b'\0'):
|
81 |
+
self._message = "unknown error"
|
82 |
+
else:
|
83 |
+
self._message = None
|
84 |
+
self._c_message = <char*> tree.xmlStrdup(
|
85 |
+
<const_xmlChar*> error.message)
|
86 |
+
if not self._c_message:
|
87 |
+
raise MemoryError()
|
88 |
+
if error.file is NULL:
|
89 |
+
self._filename = '<string>'
|
90 |
+
else:
|
91 |
+
self._filename = None
|
92 |
+
self._c_filename = tree.xmlStrdup(<const_xmlChar*> error.file)
|
93 |
+
if not self._c_filename:
|
94 |
+
raise MemoryError()
|
95 |
+
if error.node is not NULL:
|
96 |
+
self._c_path = tree.xmlGetNodePath(<xmlNode*> error.node)
|
97 |
+
c_line = tree.xmlGetLineNo(<xmlNode*> error.node)
|
98 |
+
if c_line > limits.INT_MAX:
|
99 |
+
self.line = c_line
|
100 |
+
|
101 |
+
@cython.final
|
102 |
+
cdef _setGeneric(self, int domain, int type, int level, long line,
|
103 |
+
message, filename):
|
104 |
+
self.domain = domain
|
105 |
+
self.type = type
|
106 |
+
self.level = level
|
107 |
+
self.line = line
|
108 |
+
self.column = 0
|
109 |
+
self._message = message
|
110 |
+
self._filename = filename
|
111 |
+
self._c_path = NULL
|
112 |
+
|
113 |
+
def __repr__(self):
|
114 |
+
return "%s:%d:%d:%s:%s:%s: %s" % (
|
115 |
+
self.filename, self.line, self.column, self.level_name,
|
116 |
+
self.domain_name, self.type_name, self.message)
|
117 |
+
|
118 |
+
@property
|
119 |
+
def domain_name(self):
|
120 |
+
"""The name of the error domain. See lxml.etree.ErrorDomains
|
121 |
+
"""
|
122 |
+
return ErrorDomains._getName(self.domain, "unknown")
|
123 |
+
|
124 |
+
@property
|
125 |
+
def type_name(self):
|
126 |
+
"""The name of the error type. See lxml.etree.ErrorTypes
|
127 |
+
"""
|
128 |
+
if self.domain == ErrorDomains.RELAXNGV:
|
129 |
+
getName = RelaxNGErrorTypes._getName
|
130 |
+
else:
|
131 |
+
getName = ErrorTypes._getName
|
132 |
+
return getName(self.type, "unknown")
|
133 |
+
|
134 |
+
@property
|
135 |
+
def level_name(self):
|
136 |
+
"""The name of the error level. See lxml.etree.ErrorLevels
|
137 |
+
"""
|
138 |
+
return ErrorLevels._getName(self.level, "unknown")
|
139 |
+
|
140 |
+
@property
|
141 |
+
def message(self):
|
142 |
+
"""The log message string.
|
143 |
+
"""
|
144 |
+
cdef size_t size
|
145 |
+
if self._message is not None:
|
146 |
+
return self._message
|
147 |
+
if self._c_message is NULL:
|
148 |
+
return None
|
149 |
+
size = cstring_h.strlen(self._c_message)
|
150 |
+
if size > 0 and self._c_message[size-1] == b'\n':
|
151 |
+
size -= 1 # strip EOL
|
152 |
+
# cannot use funicode() here because the message may contain
|
153 |
+
# byte encoded file paths etc.
|
154 |
+
try:
|
155 |
+
self._message = self._c_message[:size].decode('utf8')
|
156 |
+
except UnicodeDecodeError:
|
157 |
+
try:
|
158 |
+
self._message = self._c_message[:size].decode(
|
159 |
+
'ascii', 'backslashreplace')
|
160 |
+
except UnicodeDecodeError:
|
161 |
+
self._message = '<undecodable error message>'
|
162 |
+
if self._c_message:
|
163 |
+
# clean up early
|
164 |
+
tree.xmlFree(self._c_message)
|
165 |
+
self._c_message = NULL
|
166 |
+
return self._message
|
167 |
+
|
168 |
+
@property
|
169 |
+
def filename(self):
|
170 |
+
"""The file path where the report originated, if any.
|
171 |
+
"""
|
172 |
+
if self._filename is None:
|
173 |
+
if self._c_filename is not NULL:
|
174 |
+
self._filename = _decodeFilename(self._c_filename)
|
175 |
+
# clean up early
|
176 |
+
tree.xmlFree(self._c_filename)
|
177 |
+
self._c_filename = NULL
|
178 |
+
return self._filename
|
179 |
+
|
180 |
+
@property
|
181 |
+
def path(self):
|
182 |
+
"""The XPath for the node where the error was detected.
|
183 |
+
"""
|
184 |
+
return funicode(self._c_path) if self._c_path is not NULL else None
|
185 |
+
|
186 |
+
|
187 |
+
cdef class _BaseErrorLog:
|
188 |
+
cdef _LogEntry _first_error
|
189 |
+
cdef readonly object last_error
|
190 |
+
def __init__(self, first_error, last_error):
|
191 |
+
self._first_error = first_error
|
192 |
+
self.last_error = last_error
|
193 |
+
|
194 |
+
cpdef copy(self):
|
195 |
+
return _BaseErrorLog(self._first_error, self.last_error)
|
196 |
+
|
197 |
+
def __repr__(self):
|
198 |
+
return ''
|
199 |
+
|
200 |
+
cpdef receive(self, _LogEntry entry):
|
201 |
+
pass
|
202 |
+
|
203 |
+
@cython.final
|
204 |
+
cdef int _receive(self, const xmlerror.xmlError* error) except -1:
|
205 |
+
cdef bint is_error
|
206 |
+
cdef _LogEntry entry
|
207 |
+
cdef _BaseErrorLog global_log
|
208 |
+
entry = _LogEntry.__new__(_LogEntry)
|
209 |
+
entry._setError(error)
|
210 |
+
is_error = error.level == xmlerror.XML_ERR_ERROR or \
|
211 |
+
error.level == xmlerror.XML_ERR_FATAL
|
212 |
+
global_log = _getThreadErrorLog(GLOBAL_ERROR_LOG)
|
213 |
+
if global_log is not self:
|
214 |
+
global_log.receive(entry)
|
215 |
+
if is_error:
|
216 |
+
global_log.last_error = entry
|
217 |
+
self.receive(entry)
|
218 |
+
if is_error:
|
219 |
+
self.last_error = entry
|
220 |
+
|
221 |
+
@cython.final
|
222 |
+
cdef int _receiveGeneric(self, int domain, int type, int level, long line,
|
223 |
+
message, filename) except -1:
|
224 |
+
cdef bint is_error
|
225 |
+
cdef _LogEntry entry
|
226 |
+
cdef _BaseErrorLog global_log
|
227 |
+
entry = _LogEntry.__new__(_LogEntry)
|
228 |
+
entry._setGeneric(domain, type, level, line, message, filename)
|
229 |
+
is_error = level == xmlerror.XML_ERR_ERROR or \
|
230 |
+
level == xmlerror.XML_ERR_FATAL
|
231 |
+
global_log = _getThreadErrorLog(GLOBAL_ERROR_LOG)
|
232 |
+
if global_log is not self:
|
233 |
+
global_log.receive(entry)
|
234 |
+
if is_error:
|
235 |
+
global_log.last_error = entry
|
236 |
+
self.receive(entry)
|
237 |
+
if is_error:
|
238 |
+
self.last_error = entry
|
239 |
+
|
240 |
+
@cython.final
|
241 |
+
cdef _buildParseException(self, exctype, default_message):
|
242 |
+
code = xmlerror.XML_ERR_INTERNAL_ERROR
|
243 |
+
if self._first_error is None:
|
244 |
+
return exctype(default_message, code, 0, 0)
|
245 |
+
message = self._first_error.message
|
246 |
+
if message:
|
247 |
+
code = self._first_error.type
|
248 |
+
else:
|
249 |
+
message = default_message
|
250 |
+
line = self._first_error.line
|
251 |
+
column = self._first_error.column
|
252 |
+
filename = self._first_error.filename
|
253 |
+
if line > 0:
|
254 |
+
if column > 0:
|
255 |
+
message = f"{message}, line {line}, column {column}"
|
256 |
+
else:
|
257 |
+
message = f"{message}, line {line}"
|
258 |
+
return exctype(message, code, line, column, filename)
|
259 |
+
|
260 |
+
@cython.final
|
261 |
+
cdef _buildExceptionMessage(self, default_message):
|
262 |
+
if self._first_error is None:
|
263 |
+
return default_message
|
264 |
+
if self._first_error.message:
|
265 |
+
message = self._first_error.message
|
266 |
+
elif default_message is None:
|
267 |
+
return None
|
268 |
+
else:
|
269 |
+
message = default_message
|
270 |
+
if self._first_error.line > 0:
|
271 |
+
if self._first_error.column > 0:
|
272 |
+
message = f"{message}, line {self._first_error.line}, column {self._first_error.column}"
|
273 |
+
else:
|
274 |
+
message = f"{message}, line {self._first_error.line}"
|
275 |
+
return message
|
276 |
+
|
277 |
+
cdef class _ListErrorLog(_BaseErrorLog):
|
278 |
+
"Immutable base version of a list based error log."
|
279 |
+
cdef list _entries
|
280 |
+
cdef int _offset
|
281 |
+
def __init__(self, entries, first_error, last_error):
|
282 |
+
if entries:
|
283 |
+
if first_error is None:
|
284 |
+
first_error = entries[0]
|
285 |
+
if last_error is None:
|
286 |
+
last_error = entries[-1]
|
287 |
+
_BaseErrorLog.__init__(self, first_error, last_error)
|
288 |
+
self._entries = entries
|
289 |
+
|
290 |
+
cpdef copy(self):
|
291 |
+
"""Creates a shallow copy of this error log. Reuses the list of
|
292 |
+
entries.
|
293 |
+
"""
|
294 |
+
cdef _ListErrorLog log = _ListErrorLog(
|
295 |
+
self._entries, self._first_error, self.last_error)
|
296 |
+
log._offset = self._offset
|
297 |
+
return log
|
298 |
+
|
299 |
+
def __iter__(self):
|
300 |
+
entries = self._entries
|
301 |
+
if self._offset:
|
302 |
+
entries = islice(entries, self._offset)
|
303 |
+
return iter(entries)
|
304 |
+
|
305 |
+
def __repr__(self):
|
306 |
+
return '\n'.join([repr(entry) for entry in self])
|
307 |
+
|
308 |
+
def __getitem__(self, index):
|
309 |
+
if self._offset:
|
310 |
+
index += self._offset
|
311 |
+
return self._entries[index]
|
312 |
+
|
313 |
+
def __len__(self):
|
314 |
+
return len(self._entries) - self._offset
|
315 |
+
|
316 |
+
def __contains__(self, error_type):
|
317 |
+
cdef Py_ssize_t i
|
318 |
+
for i, entry in enumerate(self._entries):
|
319 |
+
if i < self._offset:
|
320 |
+
continue
|
321 |
+
if entry.type == error_type:
|
322 |
+
return True
|
323 |
+
return False
|
324 |
+
|
325 |
+
def __bool__(self):
|
326 |
+
return len(self._entries) > self._offset
|
327 |
+
|
328 |
+
def filter_domains(self, domains):
|
329 |
+
"""Filter the errors by the given domains and return a new error log
|
330 |
+
containing the matches.
|
331 |
+
"""
|
332 |
+
cdef _LogEntry entry
|
333 |
+
if isinstance(domains, int):
|
334 |
+
domains = (domains,)
|
335 |
+
filtered = [entry for entry in self if entry.domain in domains]
|
336 |
+
return _ListErrorLog(filtered, None, None)
|
337 |
+
|
338 |
+
def filter_types(self, types):
|
339 |
+
"""filter_types(self, types)
|
340 |
+
|
341 |
+
Filter the errors by the given types and return a new error
|
342 |
+
log containing the matches.
|
343 |
+
"""
|
344 |
+
cdef _LogEntry entry
|
345 |
+
if isinstance(types, int):
|
346 |
+
types = (types,)
|
347 |
+
filtered = [entry for entry in self if entry.type in types]
|
348 |
+
return _ListErrorLog(filtered, None, None)
|
349 |
+
|
350 |
+
def filter_levels(self, levels):
|
351 |
+
"""filter_levels(self, levels)
|
352 |
+
|
353 |
+
Filter the errors by the given error levels and return a new
|
354 |
+
error log containing the matches.
|
355 |
+
"""
|
356 |
+
cdef _LogEntry entry
|
357 |
+
if isinstance(levels, int):
|
358 |
+
levels = (levels,)
|
359 |
+
filtered = [entry for entry in self if entry.level in levels]
|
360 |
+
return _ListErrorLog(filtered, None, None)
|
361 |
+
|
362 |
+
def filter_from_level(self, level):
|
363 |
+
"""filter_from_level(self, level)
|
364 |
+
|
365 |
+
Return a log with all messages of the requested level of worse.
|
366 |
+
"""
|
367 |
+
cdef _LogEntry entry
|
368 |
+
filtered = [entry for entry in self if entry.level >= level]
|
369 |
+
return _ListErrorLog(filtered, None, None)
|
370 |
+
|
371 |
+
def filter_from_fatals(self):
|
372 |
+
"""filter_from_fatals(self)
|
373 |
+
|
374 |
+
Convenience method to get all fatal error messages.
|
375 |
+
"""
|
376 |
+
return self.filter_from_level(ErrorLevels.FATAL)
|
377 |
+
|
378 |
+
def filter_from_errors(self):
|
379 |
+
"""filter_from_errors(self)
|
380 |
+
|
381 |
+
Convenience method to get all error messages or worse.
|
382 |
+
"""
|
383 |
+
return self.filter_from_level(ErrorLevels.ERROR)
|
384 |
+
|
385 |
+
def filter_from_warnings(self):
|
386 |
+
"""filter_from_warnings(self)
|
387 |
+
|
388 |
+
Convenience method to get all warnings or worse.
|
389 |
+
"""
|
390 |
+
return self.filter_from_level(ErrorLevels.WARNING)
|
391 |
+
|
392 |
+
|
393 |
+
@cython.final
|
394 |
+
@cython.internal
|
395 |
+
cdef class _ErrorLogContext:
|
396 |
+
"""
|
397 |
+
Error log context for the 'with' statement.
|
398 |
+
Stores a reference to the current callbacks to allow for
|
399 |
+
recursively stacked log contexts.
|
400 |
+
"""
|
401 |
+
cdef xmlerror.xmlStructuredErrorFunc old_error_func
|
402 |
+
cdef void* old_error_context
|
403 |
+
cdef xmlerror.xmlGenericErrorFunc old_xslt_error_func
|
404 |
+
cdef void* old_xslt_error_context
|
405 |
+
cdef _BaseErrorLog old_xslt_error_log
|
406 |
+
|
407 |
+
cdef int push_error_log(self, _BaseErrorLog log) except -1:
|
408 |
+
self.old_error_func = xmlerror.xmlStructuredError
|
409 |
+
self.old_error_context = xmlerror.xmlStructuredErrorContext
|
410 |
+
xmlerror.xmlSetStructuredErrorFunc(
|
411 |
+
<void*>log, <xmlerror.xmlStructuredErrorFunc>_receiveError)
|
412 |
+
|
413 |
+
# xslt.xsltSetGenericErrorFunc() is not thread-local => keep error log in TLS
|
414 |
+
self.old_xslt_error_func = xslt.xsltGenericError
|
415 |
+
self.old_xslt_error_context = xslt.xsltGenericErrorContext
|
416 |
+
self.old_xslt_error_log = _getThreadErrorLog(XSLT_ERROR_LOG)
|
417 |
+
_setThreadErrorLog(XSLT_ERROR_LOG, log)
|
418 |
+
xslt.xsltSetGenericErrorFunc(
|
419 |
+
NULL, <xmlerror.xmlGenericErrorFunc>_receiveXSLTError)
|
420 |
+
return 0
|
421 |
+
|
422 |
+
cdef int pop_error_log(self) except -1:
|
423 |
+
xmlerror.xmlSetStructuredErrorFunc(
|
424 |
+
self.old_error_context, self.old_error_func)
|
425 |
+
xslt.xsltSetGenericErrorFunc(
|
426 |
+
self.old_xslt_error_context, self.old_xslt_error_func)
|
427 |
+
_setThreadErrorLog(XSLT_ERROR_LOG, self.old_xslt_error_log)
|
428 |
+
self.old_xslt_error_log= None
|
429 |
+
return 0
|
430 |
+
|
431 |
+
|
432 |
+
cdef class _ErrorLog(_ListErrorLog):
|
433 |
+
cdef list _logContexts
|
434 |
+
def __cinit__(self):
|
435 |
+
self._logContexts = []
|
436 |
+
|
437 |
+
def __init__(self):
|
438 |
+
_ListErrorLog.__init__(self, [], None, None)
|
439 |
+
|
440 |
+
@cython.final
|
441 |
+
cdef int __enter__(self) except -1:
|
442 |
+
return self.connect()
|
443 |
+
|
444 |
+
def __exit__(self, *args):
|
445 |
+
# TODO: make this a cdef function when Cython supports it
|
446 |
+
self.disconnect()
|
447 |
+
|
448 |
+
@cython.final
|
449 |
+
cdef int connect(self) except -1:
|
450 |
+
self._first_error = None
|
451 |
+
del self._entries[:]
|
452 |
+
|
453 |
+
cdef _ErrorLogContext context = _ErrorLogContext.__new__(_ErrorLogContext)
|
454 |
+
context.push_error_log(self)
|
455 |
+
self._logContexts.append(context)
|
456 |
+
return 0
|
457 |
+
|
458 |
+
@cython.final
|
459 |
+
cdef int disconnect(self) except -1:
|
460 |
+
cdef _ErrorLogContext context = self._logContexts.pop()
|
461 |
+
context.pop_error_log()
|
462 |
+
return 0
|
463 |
+
|
464 |
+
cpdef clear(self):
|
465 |
+
self._first_error = None
|
466 |
+
self.last_error = None
|
467 |
+
self._offset = 0
|
468 |
+
del self._entries[:]
|
469 |
+
|
470 |
+
cpdef copy(self):
|
471 |
+
"""Creates a shallow copy of this error log and the list of entries.
|
472 |
+
"""
|
473 |
+
return _ListErrorLog(
|
474 |
+
self._entries[self._offset:],
|
475 |
+
self._first_error, self.last_error)
|
476 |
+
|
477 |
+
def __iter__(self):
|
478 |
+
return iter(self._entries[self._offset:])
|
479 |
+
|
480 |
+
cpdef receive(self, _LogEntry entry):
|
481 |
+
if self._first_error is None and entry.level >= xmlerror.XML_ERR_ERROR:
|
482 |
+
self._first_error = entry
|
483 |
+
self._entries.append(entry)
|
484 |
+
|
485 |
+
cdef class _DomainErrorLog(_ErrorLog):
|
486 |
+
def __init__(self, domains):
|
487 |
+
_ErrorLog.__init__(self)
|
488 |
+
self._accepted_domains = tuple(domains)
|
489 |
+
|
490 |
+
cpdef receive(self, _LogEntry entry):
|
491 |
+
if entry.domain in self._accepted_domains:
|
492 |
+
_ErrorLog.receive(self, entry)
|
493 |
+
|
494 |
+
cdef class _RotatingErrorLog(_ErrorLog):
|
495 |
+
cdef int _max_len
|
496 |
+
def __init__(self, max_len):
|
497 |
+
_ErrorLog.__init__(self)
|
498 |
+
self._max_len = max_len
|
499 |
+
|
500 |
+
cpdef receive(self, _LogEntry entry):
|
501 |
+
if self._first_error is None and entry.level >= xmlerror.XML_ERR_ERROR:
|
502 |
+
self._first_error = entry
|
503 |
+
self._entries.append(entry)
|
504 |
+
|
505 |
+
if len(self._entries) > self._max_len:
|
506 |
+
self._offset += 1
|
507 |
+
if self._offset > self._max_len // 3:
|
508 |
+
offset = self._offset
|
509 |
+
self._offset = 0
|
510 |
+
del self._entries[:offset]
|
511 |
+
|
512 |
+
cdef class PyErrorLog(_BaseErrorLog):
|
513 |
+
"""PyErrorLog(self, logger_name=None, logger=None)
|
514 |
+
A global error log that connects to the Python stdlib logging package.
|
515 |
+
|
516 |
+
The constructor accepts an optional logger name or a readily
|
517 |
+
instantiated logger instance.
|
518 |
+
|
519 |
+
If you want to change the mapping between libxml2's ErrorLevels and Python
|
520 |
+
logging levels, you can modify the level_map dictionary from a subclass.
|
521 |
+
|
522 |
+
The default mapping is::
|
523 |
+
|
524 |
+
ErrorLevels.WARNING = logging.WARNING
|
525 |
+
ErrorLevels.ERROR = logging.ERROR
|
526 |
+
ErrorLevels.FATAL = logging.CRITICAL
|
527 |
+
|
528 |
+
You can also override the method ``receive()`` that takes a LogEntry
|
529 |
+
object and calls ``self.log(log_entry, format_string, arg1, arg2, ...)``
|
530 |
+
with appropriate data.
|
531 |
+
"""
|
532 |
+
cdef readonly dict level_map
|
533 |
+
cdef object _map_level
|
534 |
+
cdef object _log
|
535 |
+
def __init__(self, logger_name=None, logger=None):
|
536 |
+
_BaseErrorLog.__init__(self, None, None)
|
537 |
+
import logging
|
538 |
+
self.level_map = {
|
539 |
+
ErrorLevels.WARNING : logging.WARNING,
|
540 |
+
ErrorLevels.ERROR : logging.ERROR,
|
541 |
+
ErrorLevels.FATAL : logging.CRITICAL
|
542 |
+
}
|
543 |
+
self._map_level = self.level_map.get
|
544 |
+
if logger is None:
|
545 |
+
if logger_name:
|
546 |
+
logger = logging.getLogger(logger_name)
|
547 |
+
else:
|
548 |
+
logger = logging.getLogger()
|
549 |
+
self._log = logger.log
|
550 |
+
|
551 |
+
cpdef copy(self):
|
552 |
+
"""Dummy method that returns an empty error log.
|
553 |
+
"""
|
554 |
+
return _ListErrorLog([], None, None)
|
555 |
+
|
556 |
+
def log(self, log_entry, message, *args):
|
557 |
+
"""log(self, log_entry, message, *args)
|
558 |
+
|
559 |
+
Called by the .receive() method to log a _LogEntry instance to
|
560 |
+
the Python logging system. This handles the error level
|
561 |
+
mapping.
|
562 |
+
|
563 |
+
In the default implementation, the ``message`` argument
|
564 |
+
receives a complete log line, and there are no further
|
565 |
+
``args``. To change the message format, it is best to
|
566 |
+
override the .receive() method instead of this one.
|
567 |
+
"""
|
568 |
+
self._log(
|
569 |
+
self._map_level(log_entry.level, 0),
|
570 |
+
message, *args
|
571 |
+
)
|
572 |
+
|
573 |
+
cpdef receive(self, _LogEntry log_entry):
|
574 |
+
"""receive(self, log_entry)
|
575 |
+
|
576 |
+
Receive a _LogEntry instance from the logging system. Calls
|
577 |
+
the .log() method with appropriate parameters::
|
578 |
+
|
579 |
+
self.log(log_entry, repr(log_entry))
|
580 |
+
|
581 |
+
You can override this method to provide your own log output
|
582 |
+
format.
|
583 |
+
"""
|
584 |
+
self.log(log_entry, repr(log_entry))
|
585 |
+
|
586 |
+
# thread-local, global list log to collect error output messages from
|
587 |
+
# libxml2/libxslt
|
588 |
+
|
589 |
+
cdef _BaseErrorLog __GLOBAL_ERROR_LOG = _RotatingErrorLog(__MAX_LOG_SIZE)
|
590 |
+
|
591 |
+
|
592 |
+
cdef _BaseErrorLog _getThreadErrorLog(name):
|
593 |
+
"""Retrieve the current error log with name 'name' of this thread."""
|
594 |
+
cdef python.PyObject* thread_dict
|
595 |
+
thread_dict = python.PyThreadState_GetDict()
|
596 |
+
if thread_dict is NULL:
|
597 |
+
return __GLOBAL_ERROR_LOG
|
598 |
+
try:
|
599 |
+
return (<object>thread_dict)[name]
|
600 |
+
except KeyError:
|
601 |
+
log = (<object>thread_dict)[name] = \
|
602 |
+
_RotatingErrorLog(__MAX_LOG_SIZE)
|
603 |
+
return log
|
604 |
+
|
605 |
+
|
606 |
+
cdef _setThreadErrorLog(name, _BaseErrorLog log):
|
607 |
+
"""Set the global error log of this thread."""
|
608 |
+
cdef python.PyObject* thread_dict
|
609 |
+
thread_dict = python.PyThreadState_GetDict()
|
610 |
+
if thread_dict is NULL:
|
611 |
+
if name == GLOBAL_ERROR_LOG:
|
612 |
+
global __GLOBAL_ERROR_LOG
|
613 |
+
__GLOBAL_ERROR_LOG = log
|
614 |
+
else:
|
615 |
+
(<object>thread_dict)[name] = log
|
616 |
+
|
617 |
+
|
618 |
+
cdef __copyGlobalErrorLog():
|
619 |
+
"Helper function for properties in exceptions."
|
620 |
+
return _getThreadErrorLog(GLOBAL_ERROR_LOG).copy()
|
621 |
+
|
622 |
+
|
623 |
+
def use_global_python_log(PyErrorLog log not None):
|
624 |
+
"""use_global_python_log(log)
|
625 |
+
|
626 |
+
Replace the global error log by an etree.PyErrorLog that uses the
|
627 |
+
standard Python logging package.
|
628 |
+
|
629 |
+
Note that this disables access to the global error log from exceptions.
|
630 |
+
Parsers, XSLT etc. will continue to provide their normal local error log.
|
631 |
+
|
632 |
+
Note: prior to lxml 2.2, this changed the error log globally.
|
633 |
+
Since lxml 2.2, the global error log is local to a thread and this
|
634 |
+
function will only set the global error log of the current thread.
|
635 |
+
"""
|
636 |
+
_setThreadErrorLog(GLOBAL_ERROR_LOG, log)
|
637 |
+
|
638 |
+
|
639 |
+
# local log functions: forward error to logger object
|
640 |
+
cdef void _forwardError(void* c_log_handler, const xmlerror.xmlError* error) noexcept with gil:
|
641 |
+
cdef _BaseErrorLog log_handler
|
642 |
+
if c_log_handler is not NULL:
|
643 |
+
log_handler = <_BaseErrorLog>c_log_handler
|
644 |
+
elif error.domain == xmlerror.XML_FROM_XSLT:
|
645 |
+
log_handler = _getThreadErrorLog(XSLT_ERROR_LOG)
|
646 |
+
else:
|
647 |
+
log_handler = _getThreadErrorLog(GLOBAL_ERROR_LOG)
|
648 |
+
log_handler._receive(error)
|
649 |
+
|
650 |
+
|
651 |
+
cdef void _receiveError(void* c_log_handler, const xmlerror.xmlError* error) noexcept nogil:
|
652 |
+
# no Python objects here, may be called without thread context !
|
653 |
+
if __DEBUG:
|
654 |
+
_forwardError(c_log_handler, error)
|
655 |
+
|
656 |
+
|
657 |
+
cdef void _receiveXSLTError(void* c_log_handler, char* msg, ...) noexcept nogil:
|
658 |
+
# no Python objects here, may be called without thread context !
|
659 |
+
cdef cvarargs.va_list args
|
660 |
+
cvarargs.va_start(args, msg)
|
661 |
+
_receiveGenericError(c_log_handler, xmlerror.XML_FROM_XSLT, msg, args)
|
662 |
+
cvarargs.va_end(args)
|
663 |
+
|
664 |
+
cdef void _receiveRelaxNGParseError(void* c_log_handler, char* msg, ...) noexcept nogil:
|
665 |
+
# no Python objects here, may be called without thread context !
|
666 |
+
cdef cvarargs.va_list args
|
667 |
+
cvarargs.va_start(args, msg)
|
668 |
+
_receiveGenericError(c_log_handler, xmlerror.XML_FROM_RELAXNGP, msg, args)
|
669 |
+
cvarargs.va_end(args)
|
670 |
+
|
671 |
+
cdef void _receiveRelaxNGValidationError(void* c_log_handler, char* msg, ...) noexcept nogil:
|
672 |
+
# no Python objects here, may be called without thread context !
|
673 |
+
cdef cvarargs.va_list args
|
674 |
+
cvarargs.va_start(args, msg)
|
675 |
+
_receiveGenericError(c_log_handler, xmlerror.XML_FROM_RELAXNGV, msg, args)
|
676 |
+
cvarargs.va_end(args)
|
677 |
+
|
678 |
+
# dummy function: no log output at all
|
679 |
+
cdef void _nullGenericErrorFunc(void* ctxt, char* msg, ...) noexcept nogil:
|
680 |
+
pass
|
681 |
+
|
682 |
+
|
683 |
+
cdef void _connectGenericErrorLog(log, int c_domain=-1) noexcept:
|
684 |
+
cdef xmlerror.xmlGenericErrorFunc error_func = NULL
|
685 |
+
c_log = <void*>log
|
686 |
+
if c_domain == xmlerror.XML_FROM_XSLT:
|
687 |
+
error_func = <xmlerror.xmlGenericErrorFunc>_receiveXSLTError
|
688 |
+
elif c_domain == xmlerror.XML_FROM_RELAXNGP:
|
689 |
+
error_func = <xmlerror.xmlGenericErrorFunc>_receiveRelaxNGParseError
|
690 |
+
elif c_domain == xmlerror.XML_FROM_RELAXNGV:
|
691 |
+
error_func = <xmlerror.xmlGenericErrorFunc>_receiveRelaxNGValidationError
|
692 |
+
|
693 |
+
if log is None or error_func is NULL:
|
694 |
+
c_log = NULL
|
695 |
+
error_func = <xmlerror.xmlGenericErrorFunc>_nullGenericErrorFunc
|
696 |
+
xmlerror.xmlSetGenericErrorFunc(c_log, error_func)
|
697 |
+
|
698 |
+
|
699 |
+
cdef void _receiveGenericError(void* c_log_handler, int c_domain,
|
700 |
+
char* msg, cvarargs.va_list args) noexcept nogil:
|
701 |
+
# no Python objects here, may be called without thread context !
|
702 |
+
cdef xmlerror.xmlError c_error
|
703 |
+
cdef char* c_text
|
704 |
+
cdef char* c_message
|
705 |
+
cdef char* c_element
|
706 |
+
cdef char* c_pos
|
707 |
+
cdef char* c_name_pos
|
708 |
+
cdef char* c_str
|
709 |
+
cdef int text_size, element_size, format_count, c_int
|
710 |
+
if not __DEBUG or msg is NULL:
|
711 |
+
return
|
712 |
+
if msg[0] in b'\n\0':
|
713 |
+
return
|
714 |
+
|
715 |
+
c_text = c_element = c_error.file = c_error.node = NULL
|
716 |
+
c_error.line = 0
|
717 |
+
|
718 |
+
# parse "NAME %s" chunks from the format string
|
719 |
+
c_name_pos = c_pos = msg
|
720 |
+
format_count = 0
|
721 |
+
while c_pos[0]:
|
722 |
+
if c_pos[0] == b'%':
|
723 |
+
c_pos += 1
|
724 |
+
if c_pos[0] == b's': # "%s"
|
725 |
+
format_count += 1
|
726 |
+
c_str = cvarargs.va_charptr(args)
|
727 |
+
if c_pos == msg + 1:
|
728 |
+
c_text = c_str # msg == "%s..."
|
729 |
+
elif c_name_pos[0] == b'e':
|
730 |
+
if cstring_h.strncmp(c_name_pos, 'element %s', 10) == 0:
|
731 |
+
c_element = c_str
|
732 |
+
elif c_name_pos[0] == b'f':
|
733 |
+
if cstring_h.strncmp(c_name_pos, 'file %s', 7) == 0:
|
734 |
+
if cstring_h.strncmp('string://__STRING__XSLT',
|
735 |
+
c_str, 23) == 0:
|
736 |
+
c_str = '<xslt>'
|
737 |
+
c_error.file = c_str
|
738 |
+
elif c_pos[0] == b'd': # "%d"
|
739 |
+
format_count += 1
|
740 |
+
c_int = cvarargs.va_int(args)
|
741 |
+
if cstring_h.strncmp(c_name_pos, 'line %d', 7) == 0:
|
742 |
+
c_error.line = c_int
|
743 |
+
elif c_pos[0] != b'%': # "%%" == "%"
|
744 |
+
format_count += 1
|
745 |
+
break # unexpected format or end of string => abort
|
746 |
+
elif c_pos[0] == b' ':
|
747 |
+
if c_pos[1] != b'%':
|
748 |
+
c_name_pos = c_pos + 1
|
749 |
+
c_pos += 1
|
750 |
+
|
751 |
+
c_message = NULL
|
752 |
+
if c_text is NULL:
|
753 |
+
if c_element is not NULL and format_count == 1:
|
754 |
+
# special case: a single occurrence of 'element %s'
|
755 |
+
text_size = cstring_h.strlen(msg)
|
756 |
+
element_size = cstring_h.strlen(c_element)
|
757 |
+
c_message = <char*>stdlib.malloc(
|
758 |
+
(text_size + element_size + 1) * sizeof(char))
|
759 |
+
stdio.sprintf(c_message, msg, c_element)
|
760 |
+
c_error.message = c_message
|
761 |
+
else:
|
762 |
+
c_error.message = ''
|
763 |
+
elif c_element is NULL:
|
764 |
+
c_error.message = c_text
|
765 |
+
else:
|
766 |
+
text_size = cstring_h.strlen(c_text)
|
767 |
+
element_size = cstring_h.strlen(c_element)
|
768 |
+
c_message = <char*>stdlib.malloc(
|
769 |
+
(text_size + 12 + element_size + 1) * sizeof(char))
|
770 |
+
if c_message is NULL:
|
771 |
+
c_error.message = c_text
|
772 |
+
else:
|
773 |
+
stdio.sprintf(c_message, "%s, element '%s'", c_text, c_element)
|
774 |
+
c_error.message = c_message
|
775 |
+
|
776 |
+
c_error.domain = c_domain
|
777 |
+
c_error.code = xmlerror.XML_ERR_OK # what else?
|
778 |
+
c_error.level = xmlerror.XML_ERR_ERROR # what else?
|
779 |
+
c_error.int2 = 0
|
780 |
+
|
781 |
+
_forwardError(c_log_handler, &c_error)
|
782 |
+
|
783 |
+
if c_message is not NULL:
|
784 |
+
stdlib.free(c_message)
|
785 |
+
|
786 |
+
################################################################################
|
787 |
+
## CONSTANTS FROM "xmlerror.h" (or rather libxml-xmlerror.html)
|
788 |
+
################################################################################
|
789 |
+
|
790 |
+
cdef __initErrorConstants():
|
791 |
+
"Called at setup time to parse the constants and build the classes below."
|
792 |
+
global __ERROR_LEVELS, __ERROR_DOMAINS, __PARSER_ERROR_TYPES, __RELAXNG_ERROR_TYPES
|
793 |
+
const_defs = ((ErrorLevels, __ERROR_LEVELS),
|
794 |
+
(ErrorDomains, __ERROR_DOMAINS),
|
795 |
+
(ErrorTypes, __PARSER_ERROR_TYPES),
|
796 |
+
(RelaxNGErrorTypes, __RELAXNG_ERROR_TYPES))
|
797 |
+
|
798 |
+
for cls, constants in const_defs:
|
799 |
+
reverse_dict = {}
|
800 |
+
cls._names = reverse_dict
|
801 |
+
cls._getName = reverse_dict.get
|
802 |
+
for line in constants.splitlines():
|
803 |
+
if not line:
|
804 |
+
continue
|
805 |
+
name, value = line.split('=')
|
806 |
+
value = int(value)
|
807 |
+
setattr(cls, name, value)
|
808 |
+
reverse_dict[value] = name
|
809 |
+
|
810 |
+
# discard the global string references after use
|
811 |
+
__ERROR_LEVELS = __ERROR_DOMAINS = __PARSER_ERROR_TYPES = __RELAXNG_ERROR_TYPES = None
|
812 |
+
|
813 |
+
|
814 |
+
class ErrorLevels(object):
|
815 |
+
"""Libxml2 error levels"""
|
816 |
+
|
817 |
+
class ErrorDomains(object):
|
818 |
+
"""Libxml2 error domains"""
|
819 |
+
|
820 |
+
class ErrorTypes(object):
|
821 |
+
"""Libxml2 error types"""
|
822 |
+
|
823 |
+
class RelaxNGErrorTypes(object):
|
824 |
+
"""Libxml2 RelaxNG error types"""
|
825 |
+
|
826 |
+
|
827 |
+
# --- BEGIN: GENERATED CONSTANTS ---
|
828 |
+
|
829 |
+
# This section is generated by the script 'update-error-constants.py'.
|
830 |
+
|
831 |
+
cdef object __ERROR_LEVELS = """\
|
832 |
+
NONE=0
|
833 |
+
WARNING=1
|
834 |
+
ERROR=2
|
835 |
+
FATAL=3
|
836 |
+
"""
|
837 |
+
|
838 |
+
cdef object __ERROR_DOMAINS = """\
|
839 |
+
NONE=0
|
840 |
+
PARSER=1
|
841 |
+
TREE=2
|
842 |
+
NAMESPACE=3
|
843 |
+
DTD=4
|
844 |
+
HTML=5
|
845 |
+
MEMORY=6
|
846 |
+
OUTPUT=7
|
847 |
+
IO=8
|
848 |
+
FTP=9
|
849 |
+
HTTP=10
|
850 |
+
XINCLUDE=11
|
851 |
+
XPATH=12
|
852 |
+
XPOINTER=13
|
853 |
+
REGEXP=14
|
854 |
+
DATATYPE=15
|
855 |
+
SCHEMASP=16
|
856 |
+
SCHEMASV=17
|
857 |
+
RELAXNGP=18
|
858 |
+
RELAXNGV=19
|
859 |
+
CATALOG=20
|
860 |
+
C14N=21
|
861 |
+
XSLT=22
|
862 |
+
VALID=23
|
863 |
+
CHECK=24
|
864 |
+
WRITER=25
|
865 |
+
MODULE=26
|
866 |
+
I18N=27
|
867 |
+
SCHEMATRONV=28
|
868 |
+
BUFFER=29
|
869 |
+
URI=30
|
870 |
+
"""
|
871 |
+
|
872 |
+
cdef object __PARSER_ERROR_TYPES = """\
|
873 |
+
ERR_OK=0
|
874 |
+
ERR_INTERNAL_ERROR=1
|
875 |
+
ERR_NO_MEMORY=2
|
876 |
+
ERR_DOCUMENT_START=3
|
877 |
+
ERR_DOCUMENT_EMPTY=4
|
878 |
+
ERR_DOCUMENT_END=5
|
879 |
+
ERR_INVALID_HEX_CHARREF=6
|
880 |
+
ERR_INVALID_DEC_CHARREF=7
|
881 |
+
ERR_INVALID_CHARREF=8
|
882 |
+
ERR_INVALID_CHAR=9
|
883 |
+
ERR_CHARREF_AT_EOF=10
|
884 |
+
ERR_CHARREF_IN_PROLOG=11
|
885 |
+
ERR_CHARREF_IN_EPILOG=12
|
886 |
+
ERR_CHARREF_IN_DTD=13
|
887 |
+
ERR_ENTITYREF_AT_EOF=14
|
888 |
+
ERR_ENTITYREF_IN_PROLOG=15
|
889 |
+
ERR_ENTITYREF_IN_EPILOG=16
|
890 |
+
ERR_ENTITYREF_IN_DTD=17
|
891 |
+
ERR_PEREF_AT_EOF=18
|
892 |
+
ERR_PEREF_IN_PROLOG=19
|
893 |
+
ERR_PEREF_IN_EPILOG=20
|
894 |
+
ERR_PEREF_IN_INT_SUBSET=21
|
895 |
+
ERR_ENTITYREF_NO_NAME=22
|
896 |
+
ERR_ENTITYREF_SEMICOL_MISSING=23
|
897 |
+
ERR_PEREF_NO_NAME=24
|
898 |
+
ERR_PEREF_SEMICOL_MISSING=25
|
899 |
+
ERR_UNDECLARED_ENTITY=26
|
900 |
+
WAR_UNDECLARED_ENTITY=27
|
901 |
+
ERR_UNPARSED_ENTITY=28
|
902 |
+
ERR_ENTITY_IS_EXTERNAL=29
|
903 |
+
ERR_ENTITY_IS_PARAMETER=30
|
904 |
+
ERR_UNKNOWN_ENCODING=31
|
905 |
+
ERR_UNSUPPORTED_ENCODING=32
|
906 |
+
ERR_STRING_NOT_STARTED=33
|
907 |
+
ERR_STRING_NOT_CLOSED=34
|
908 |
+
ERR_NS_DECL_ERROR=35
|
909 |
+
ERR_ENTITY_NOT_STARTED=36
|
910 |
+
ERR_ENTITY_NOT_FINISHED=37
|
911 |
+
ERR_LT_IN_ATTRIBUTE=38
|
912 |
+
ERR_ATTRIBUTE_NOT_STARTED=39
|
913 |
+
ERR_ATTRIBUTE_NOT_FINISHED=40
|
914 |
+
ERR_ATTRIBUTE_WITHOUT_VALUE=41
|
915 |
+
ERR_ATTRIBUTE_REDEFINED=42
|
916 |
+
ERR_LITERAL_NOT_STARTED=43
|
917 |
+
ERR_LITERAL_NOT_FINISHED=44
|
918 |
+
ERR_COMMENT_NOT_FINISHED=45
|
919 |
+
ERR_PI_NOT_STARTED=46
|
920 |
+
ERR_PI_NOT_FINISHED=47
|
921 |
+
ERR_NOTATION_NOT_STARTED=48
|
922 |
+
ERR_NOTATION_NOT_FINISHED=49
|
923 |
+
ERR_ATTLIST_NOT_STARTED=50
|
924 |
+
ERR_ATTLIST_NOT_FINISHED=51
|
925 |
+
ERR_MIXED_NOT_STARTED=52
|
926 |
+
ERR_MIXED_NOT_FINISHED=53
|
927 |
+
ERR_ELEMCONTENT_NOT_STARTED=54
|
928 |
+
ERR_ELEMCONTENT_NOT_FINISHED=55
|
929 |
+
ERR_XMLDECL_NOT_STARTED=56
|
930 |
+
ERR_XMLDECL_NOT_FINISHED=57
|
931 |
+
ERR_CONDSEC_NOT_STARTED=58
|
932 |
+
ERR_CONDSEC_NOT_FINISHED=59
|
933 |
+
ERR_EXT_SUBSET_NOT_FINISHED=60
|
934 |
+
ERR_DOCTYPE_NOT_FINISHED=61
|
935 |
+
ERR_MISPLACED_CDATA_END=62
|
936 |
+
ERR_CDATA_NOT_FINISHED=63
|
937 |
+
ERR_RESERVED_XML_NAME=64
|
938 |
+
ERR_SPACE_REQUIRED=65
|
939 |
+
ERR_SEPARATOR_REQUIRED=66
|
940 |
+
ERR_NMTOKEN_REQUIRED=67
|
941 |
+
ERR_NAME_REQUIRED=68
|
942 |
+
ERR_PCDATA_REQUIRED=69
|
943 |
+
ERR_URI_REQUIRED=70
|
944 |
+
ERR_PUBID_REQUIRED=71
|
945 |
+
ERR_LT_REQUIRED=72
|
946 |
+
ERR_GT_REQUIRED=73
|
947 |
+
ERR_LTSLASH_REQUIRED=74
|
948 |
+
ERR_EQUAL_REQUIRED=75
|
949 |
+
ERR_TAG_NAME_MISMATCH=76
|
950 |
+
ERR_TAG_NOT_FINISHED=77
|
951 |
+
ERR_STANDALONE_VALUE=78
|
952 |
+
ERR_ENCODING_NAME=79
|
953 |
+
ERR_HYPHEN_IN_COMMENT=80
|
954 |
+
ERR_INVALID_ENCODING=81
|
955 |
+
ERR_EXT_ENTITY_STANDALONE=82
|
956 |
+
ERR_CONDSEC_INVALID=83
|
957 |
+
ERR_VALUE_REQUIRED=84
|
958 |
+
ERR_NOT_WELL_BALANCED=85
|
959 |
+
ERR_EXTRA_CONTENT=86
|
960 |
+
ERR_ENTITY_CHAR_ERROR=87
|
961 |
+
ERR_ENTITY_PE_INTERNAL=88
|
962 |
+
ERR_ENTITY_LOOP=89
|
963 |
+
ERR_ENTITY_BOUNDARY=90
|
964 |
+
ERR_INVALID_URI=91
|
965 |
+
ERR_URI_FRAGMENT=92
|
966 |
+
WAR_CATALOG_PI=93
|
967 |
+
ERR_NO_DTD=94
|
968 |
+
ERR_CONDSEC_INVALID_KEYWORD=95
|
969 |
+
ERR_VERSION_MISSING=96
|
970 |
+
WAR_UNKNOWN_VERSION=97
|
971 |
+
WAR_LANG_VALUE=98
|
972 |
+
WAR_NS_URI=99
|
973 |
+
WAR_NS_URI_RELATIVE=100
|
974 |
+
ERR_MISSING_ENCODING=101
|
975 |
+
WAR_SPACE_VALUE=102
|
976 |
+
ERR_NOT_STANDALONE=103
|
977 |
+
ERR_ENTITY_PROCESSING=104
|
978 |
+
ERR_NOTATION_PROCESSING=105
|
979 |
+
WAR_NS_COLUMN=106
|
980 |
+
WAR_ENTITY_REDEFINED=107
|
981 |
+
ERR_UNKNOWN_VERSION=108
|
982 |
+
ERR_VERSION_MISMATCH=109
|
983 |
+
ERR_NAME_TOO_LONG=110
|
984 |
+
ERR_USER_STOP=111
|
985 |
+
ERR_COMMENT_ABRUPTLY_ENDED=112
|
986 |
+
NS_ERR_XML_NAMESPACE=200
|
987 |
+
NS_ERR_UNDEFINED_NAMESPACE=201
|
988 |
+
NS_ERR_QNAME=202
|
989 |
+
NS_ERR_ATTRIBUTE_REDEFINED=203
|
990 |
+
NS_ERR_EMPTY=204
|
991 |
+
NS_ERR_COLON=205
|
992 |
+
DTD_ATTRIBUTE_DEFAULT=500
|
993 |
+
DTD_ATTRIBUTE_REDEFINED=501
|
994 |
+
DTD_ATTRIBUTE_VALUE=502
|
995 |
+
DTD_CONTENT_ERROR=503
|
996 |
+
DTD_CONTENT_MODEL=504
|
997 |
+
DTD_CONTENT_NOT_DETERMINIST=505
|
998 |
+
DTD_DIFFERENT_PREFIX=506
|
999 |
+
DTD_ELEM_DEFAULT_NAMESPACE=507
|
1000 |
+
DTD_ELEM_NAMESPACE=508
|
1001 |
+
DTD_ELEM_REDEFINED=509
|
1002 |
+
DTD_EMPTY_NOTATION=510
|
1003 |
+
DTD_ENTITY_TYPE=511
|
1004 |
+
DTD_ID_FIXED=512
|
1005 |
+
DTD_ID_REDEFINED=513
|
1006 |
+
DTD_ID_SUBSET=514
|
1007 |
+
DTD_INVALID_CHILD=515
|
1008 |
+
DTD_INVALID_DEFAULT=516
|
1009 |
+
DTD_LOAD_ERROR=517
|
1010 |
+
DTD_MISSING_ATTRIBUTE=518
|
1011 |
+
DTD_MIXED_CORRUPT=519
|
1012 |
+
DTD_MULTIPLE_ID=520
|
1013 |
+
DTD_NO_DOC=521
|
1014 |
+
DTD_NO_DTD=522
|
1015 |
+
DTD_NO_ELEM_NAME=523
|
1016 |
+
DTD_NO_PREFIX=524
|
1017 |
+
DTD_NO_ROOT=525
|
1018 |
+
DTD_NOTATION_REDEFINED=526
|
1019 |
+
DTD_NOTATION_VALUE=527
|
1020 |
+
DTD_NOT_EMPTY=528
|
1021 |
+
DTD_NOT_PCDATA=529
|
1022 |
+
DTD_NOT_STANDALONE=530
|
1023 |
+
DTD_ROOT_NAME=531
|
1024 |
+
DTD_STANDALONE_WHITE_SPACE=532
|
1025 |
+
DTD_UNKNOWN_ATTRIBUTE=533
|
1026 |
+
DTD_UNKNOWN_ELEM=534
|
1027 |
+
DTD_UNKNOWN_ENTITY=535
|
1028 |
+
DTD_UNKNOWN_ID=536
|
1029 |
+
DTD_UNKNOWN_NOTATION=537
|
1030 |
+
DTD_STANDALONE_DEFAULTED=538
|
1031 |
+
DTD_XMLID_VALUE=539
|
1032 |
+
DTD_XMLID_TYPE=540
|
1033 |
+
DTD_DUP_TOKEN=541
|
1034 |
+
HTML_STRUCURE_ERROR=800
|
1035 |
+
HTML_UNKNOWN_TAG=801
|
1036 |
+
RNGP_ANYNAME_ATTR_ANCESTOR=1000
|
1037 |
+
RNGP_ATTR_CONFLICT=1001
|
1038 |
+
RNGP_ATTRIBUTE_CHILDREN=1002
|
1039 |
+
RNGP_ATTRIBUTE_CONTENT=1003
|
1040 |
+
RNGP_ATTRIBUTE_EMPTY=1004
|
1041 |
+
RNGP_ATTRIBUTE_NOOP=1005
|
1042 |
+
RNGP_CHOICE_CONTENT=1006
|
1043 |
+
RNGP_CHOICE_EMPTY=1007
|
1044 |
+
RNGP_CREATE_FAILURE=1008
|
1045 |
+
RNGP_DATA_CONTENT=1009
|
1046 |
+
RNGP_DEF_CHOICE_AND_INTERLEAVE=1010
|
1047 |
+
RNGP_DEFINE_CREATE_FAILED=1011
|
1048 |
+
RNGP_DEFINE_EMPTY=1012
|
1049 |
+
RNGP_DEFINE_MISSING=1013
|
1050 |
+
RNGP_DEFINE_NAME_MISSING=1014
|
1051 |
+
RNGP_ELEM_CONTENT_EMPTY=1015
|
1052 |
+
RNGP_ELEM_CONTENT_ERROR=1016
|
1053 |
+
RNGP_ELEMENT_EMPTY=1017
|
1054 |
+
RNGP_ELEMENT_CONTENT=1018
|
1055 |
+
RNGP_ELEMENT_NAME=1019
|
1056 |
+
RNGP_ELEMENT_NO_CONTENT=1020
|
1057 |
+
RNGP_ELEM_TEXT_CONFLICT=1021
|
1058 |
+
RNGP_EMPTY=1022
|
1059 |
+
RNGP_EMPTY_CONSTRUCT=1023
|
1060 |
+
RNGP_EMPTY_CONTENT=1024
|
1061 |
+
RNGP_EMPTY_NOT_EMPTY=1025
|
1062 |
+
RNGP_ERROR_TYPE_LIB=1026
|
1063 |
+
RNGP_EXCEPT_EMPTY=1027
|
1064 |
+
RNGP_EXCEPT_MISSING=1028
|
1065 |
+
RNGP_EXCEPT_MULTIPLE=1029
|
1066 |
+
RNGP_EXCEPT_NO_CONTENT=1030
|
1067 |
+
RNGP_EXTERNALREF_EMTPY=1031
|
1068 |
+
RNGP_EXTERNAL_REF_FAILURE=1032
|
1069 |
+
RNGP_EXTERNALREF_RECURSE=1033
|
1070 |
+
RNGP_FORBIDDEN_ATTRIBUTE=1034
|
1071 |
+
RNGP_FOREIGN_ELEMENT=1035
|
1072 |
+
RNGP_GRAMMAR_CONTENT=1036
|
1073 |
+
RNGP_GRAMMAR_EMPTY=1037
|
1074 |
+
RNGP_GRAMMAR_MISSING=1038
|
1075 |
+
RNGP_GRAMMAR_NO_START=1039
|
1076 |
+
RNGP_GROUP_ATTR_CONFLICT=1040
|
1077 |
+
RNGP_HREF_ERROR=1041
|
1078 |
+
RNGP_INCLUDE_EMPTY=1042
|
1079 |
+
RNGP_INCLUDE_FAILURE=1043
|
1080 |
+
RNGP_INCLUDE_RECURSE=1044
|
1081 |
+
RNGP_INTERLEAVE_ADD=1045
|
1082 |
+
RNGP_INTERLEAVE_CREATE_FAILED=1046
|
1083 |
+
RNGP_INTERLEAVE_EMPTY=1047
|
1084 |
+
RNGP_INTERLEAVE_NO_CONTENT=1048
|
1085 |
+
RNGP_INVALID_DEFINE_NAME=1049
|
1086 |
+
RNGP_INVALID_URI=1050
|
1087 |
+
RNGP_INVALID_VALUE=1051
|
1088 |
+
RNGP_MISSING_HREF=1052
|
1089 |
+
RNGP_NAME_MISSING=1053
|
1090 |
+
RNGP_NEED_COMBINE=1054
|
1091 |
+
RNGP_NOTALLOWED_NOT_EMPTY=1055
|
1092 |
+
RNGP_NSNAME_ATTR_ANCESTOR=1056
|
1093 |
+
RNGP_NSNAME_NO_NS=1057
|
1094 |
+
RNGP_PARAM_FORBIDDEN=1058
|
1095 |
+
RNGP_PARAM_NAME_MISSING=1059
|
1096 |
+
RNGP_PARENTREF_CREATE_FAILED=1060
|
1097 |
+
RNGP_PARENTREF_NAME_INVALID=1061
|
1098 |
+
RNGP_PARENTREF_NO_NAME=1062
|
1099 |
+
RNGP_PARENTREF_NO_PARENT=1063
|
1100 |
+
RNGP_PARENTREF_NOT_EMPTY=1064
|
1101 |
+
RNGP_PARSE_ERROR=1065
|
1102 |
+
RNGP_PAT_ANYNAME_EXCEPT_ANYNAME=1066
|
1103 |
+
RNGP_PAT_ATTR_ATTR=1067
|
1104 |
+
RNGP_PAT_ATTR_ELEM=1068
|
1105 |
+
RNGP_PAT_DATA_EXCEPT_ATTR=1069
|
1106 |
+
RNGP_PAT_DATA_EXCEPT_ELEM=1070
|
1107 |
+
RNGP_PAT_DATA_EXCEPT_EMPTY=1071
|
1108 |
+
RNGP_PAT_DATA_EXCEPT_GROUP=1072
|
1109 |
+
RNGP_PAT_DATA_EXCEPT_INTERLEAVE=1073
|
1110 |
+
RNGP_PAT_DATA_EXCEPT_LIST=1074
|
1111 |
+
RNGP_PAT_DATA_EXCEPT_ONEMORE=1075
|
1112 |
+
RNGP_PAT_DATA_EXCEPT_REF=1076
|
1113 |
+
RNGP_PAT_DATA_EXCEPT_TEXT=1077
|
1114 |
+
RNGP_PAT_LIST_ATTR=1078
|
1115 |
+
RNGP_PAT_LIST_ELEM=1079
|
1116 |
+
RNGP_PAT_LIST_INTERLEAVE=1080
|
1117 |
+
RNGP_PAT_LIST_LIST=1081
|
1118 |
+
RNGP_PAT_LIST_REF=1082
|
1119 |
+
RNGP_PAT_LIST_TEXT=1083
|
1120 |
+
RNGP_PAT_NSNAME_EXCEPT_ANYNAME=1084
|
1121 |
+
RNGP_PAT_NSNAME_EXCEPT_NSNAME=1085
|
1122 |
+
RNGP_PAT_ONEMORE_GROUP_ATTR=1086
|
1123 |
+
RNGP_PAT_ONEMORE_INTERLEAVE_ATTR=1087
|
1124 |
+
RNGP_PAT_START_ATTR=1088
|
1125 |
+
RNGP_PAT_START_DATA=1089
|
1126 |
+
RNGP_PAT_START_EMPTY=1090
|
1127 |
+
RNGP_PAT_START_GROUP=1091
|
1128 |
+
RNGP_PAT_START_INTERLEAVE=1092
|
1129 |
+
RNGP_PAT_START_LIST=1093
|
1130 |
+
RNGP_PAT_START_ONEMORE=1094
|
1131 |
+
RNGP_PAT_START_TEXT=1095
|
1132 |
+
RNGP_PAT_START_VALUE=1096
|
1133 |
+
RNGP_PREFIX_UNDEFINED=1097
|
1134 |
+
RNGP_REF_CREATE_FAILED=1098
|
1135 |
+
RNGP_REF_CYCLE=1099
|
1136 |
+
RNGP_REF_NAME_INVALID=1100
|
1137 |
+
RNGP_REF_NO_DEF=1101
|
1138 |
+
RNGP_REF_NO_NAME=1102
|
1139 |
+
RNGP_REF_NOT_EMPTY=1103
|
1140 |
+
RNGP_START_CHOICE_AND_INTERLEAVE=1104
|
1141 |
+
RNGP_START_CONTENT=1105
|
1142 |
+
RNGP_START_EMPTY=1106
|
1143 |
+
RNGP_START_MISSING=1107
|
1144 |
+
RNGP_TEXT_EXPECTED=1108
|
1145 |
+
RNGP_TEXT_HAS_CHILD=1109
|
1146 |
+
RNGP_TYPE_MISSING=1110
|
1147 |
+
RNGP_TYPE_NOT_FOUND=1111
|
1148 |
+
RNGP_TYPE_VALUE=1112
|
1149 |
+
RNGP_UNKNOWN_ATTRIBUTE=1113
|
1150 |
+
RNGP_UNKNOWN_COMBINE=1114
|
1151 |
+
RNGP_UNKNOWN_CONSTRUCT=1115
|
1152 |
+
RNGP_UNKNOWN_TYPE_LIB=1116
|
1153 |
+
RNGP_URI_FRAGMENT=1117
|
1154 |
+
RNGP_URI_NOT_ABSOLUTE=1118
|
1155 |
+
RNGP_VALUE_EMPTY=1119
|
1156 |
+
RNGP_VALUE_NO_CONTENT=1120
|
1157 |
+
RNGP_XMLNS_NAME=1121
|
1158 |
+
RNGP_XML_NS=1122
|
1159 |
+
XPATH_EXPRESSION_OK=1200
|
1160 |
+
XPATH_NUMBER_ERROR=1201
|
1161 |
+
XPATH_UNFINISHED_LITERAL_ERROR=1202
|
1162 |
+
XPATH_START_LITERAL_ERROR=1203
|
1163 |
+
XPATH_VARIABLE_REF_ERROR=1204
|
1164 |
+
XPATH_UNDEF_VARIABLE_ERROR=1205
|
1165 |
+
XPATH_INVALID_PREDICATE_ERROR=1206
|
1166 |
+
XPATH_EXPR_ERROR=1207
|
1167 |
+
XPATH_UNCLOSED_ERROR=1208
|
1168 |
+
XPATH_UNKNOWN_FUNC_ERROR=1209
|
1169 |
+
XPATH_INVALID_OPERAND=1210
|
1170 |
+
XPATH_INVALID_TYPE=1211
|
1171 |
+
XPATH_INVALID_ARITY=1212
|
1172 |
+
XPATH_INVALID_CTXT_SIZE=1213
|
1173 |
+
XPATH_INVALID_CTXT_POSITION=1214
|
1174 |
+
XPATH_MEMORY_ERROR=1215
|
1175 |
+
XPTR_SYNTAX_ERROR=1216
|
1176 |
+
XPTR_RESOURCE_ERROR=1217
|
1177 |
+
XPTR_SUB_RESOURCE_ERROR=1218
|
1178 |
+
XPATH_UNDEF_PREFIX_ERROR=1219
|
1179 |
+
XPATH_ENCODING_ERROR=1220
|
1180 |
+
XPATH_INVALID_CHAR_ERROR=1221
|
1181 |
+
TREE_INVALID_HEX=1300
|
1182 |
+
TREE_INVALID_DEC=1301
|
1183 |
+
TREE_UNTERMINATED_ENTITY=1302
|
1184 |
+
TREE_NOT_UTF8=1303
|
1185 |
+
SAVE_NOT_UTF8=1400
|
1186 |
+
SAVE_CHAR_INVALID=1401
|
1187 |
+
SAVE_NO_DOCTYPE=1402
|
1188 |
+
SAVE_UNKNOWN_ENCODING=1403
|
1189 |
+
REGEXP_COMPILE_ERROR=1450
|
1190 |
+
IO_UNKNOWN=1500
|
1191 |
+
IO_EACCES=1501
|
1192 |
+
IO_EAGAIN=1502
|
1193 |
+
IO_EBADF=1503
|
1194 |
+
IO_EBADMSG=1504
|
1195 |
+
IO_EBUSY=1505
|
1196 |
+
IO_ECANCELED=1506
|
1197 |
+
IO_ECHILD=1507
|
1198 |
+
IO_EDEADLK=1508
|
1199 |
+
IO_EDOM=1509
|
1200 |
+
IO_EEXIST=1510
|
1201 |
+
IO_EFAULT=1511
|
1202 |
+
IO_EFBIG=1512
|
1203 |
+
IO_EINPROGRESS=1513
|
1204 |
+
IO_EINTR=1514
|
1205 |
+
IO_EINVAL=1515
|
1206 |
+
IO_EIO=1516
|
1207 |
+
IO_EISDIR=1517
|
1208 |
+
IO_EMFILE=1518
|
1209 |
+
IO_EMLINK=1519
|
1210 |
+
IO_EMSGSIZE=1520
|
1211 |
+
IO_ENAMETOOLONG=1521
|
1212 |
+
IO_ENFILE=1522
|
1213 |
+
IO_ENODEV=1523
|
1214 |
+
IO_ENOENT=1524
|
1215 |
+
IO_ENOEXEC=1525
|
1216 |
+
IO_ENOLCK=1526
|
1217 |
+
IO_ENOMEM=1527
|
1218 |
+
IO_ENOSPC=1528
|
1219 |
+
IO_ENOSYS=1529
|
1220 |
+
IO_ENOTDIR=1530
|
1221 |
+
IO_ENOTEMPTY=1531
|
1222 |
+
IO_ENOTSUP=1532
|
1223 |
+
IO_ENOTTY=1533
|
1224 |
+
IO_ENXIO=1534
|
1225 |
+
IO_EPERM=1535
|
1226 |
+
IO_EPIPE=1536
|
1227 |
+
IO_ERANGE=1537
|
1228 |
+
IO_EROFS=1538
|
1229 |
+
IO_ESPIPE=1539
|
1230 |
+
IO_ESRCH=1540
|
1231 |
+
IO_ETIMEDOUT=1541
|
1232 |
+
IO_EXDEV=1542
|
1233 |
+
IO_NETWORK_ATTEMPT=1543
|
1234 |
+
IO_ENCODER=1544
|
1235 |
+
IO_FLUSH=1545
|
1236 |
+
IO_WRITE=1546
|
1237 |
+
IO_NO_INPUT=1547
|
1238 |
+
IO_BUFFER_FULL=1548
|
1239 |
+
IO_LOAD_ERROR=1549
|
1240 |
+
IO_ENOTSOCK=1550
|
1241 |
+
IO_EISCONN=1551
|
1242 |
+
IO_ECONNREFUSED=1552
|
1243 |
+
IO_ENETUNREACH=1553
|
1244 |
+
IO_EADDRINUSE=1554
|
1245 |
+
IO_EALREADY=1555
|
1246 |
+
IO_EAFNOSUPPORT=1556
|
1247 |
+
XINCLUDE_RECURSION=1600
|
1248 |
+
XINCLUDE_PARSE_VALUE=1601
|
1249 |
+
XINCLUDE_ENTITY_DEF_MISMATCH=1602
|
1250 |
+
XINCLUDE_NO_HREF=1603
|
1251 |
+
XINCLUDE_NO_FALLBACK=1604
|
1252 |
+
XINCLUDE_HREF_URI=1605
|
1253 |
+
XINCLUDE_TEXT_FRAGMENT=1606
|
1254 |
+
XINCLUDE_TEXT_DOCUMENT=1607
|
1255 |
+
XINCLUDE_INVALID_CHAR=1608
|
1256 |
+
XINCLUDE_BUILD_FAILED=1609
|
1257 |
+
XINCLUDE_UNKNOWN_ENCODING=1610
|
1258 |
+
XINCLUDE_MULTIPLE_ROOT=1611
|
1259 |
+
XINCLUDE_XPTR_FAILED=1612
|
1260 |
+
XINCLUDE_XPTR_RESULT=1613
|
1261 |
+
XINCLUDE_INCLUDE_IN_INCLUDE=1614
|
1262 |
+
XINCLUDE_FALLBACKS_IN_INCLUDE=1615
|
1263 |
+
XINCLUDE_FALLBACK_NOT_IN_INCLUDE=1616
|
1264 |
+
XINCLUDE_DEPRECATED_NS=1617
|
1265 |
+
XINCLUDE_FRAGMENT_ID=1618
|
1266 |
+
CATALOG_MISSING_ATTR=1650
|
1267 |
+
CATALOG_ENTRY_BROKEN=1651
|
1268 |
+
CATALOG_PREFER_VALUE=1652
|
1269 |
+
CATALOG_NOT_CATALOG=1653
|
1270 |
+
CATALOG_RECURSION=1654
|
1271 |
+
SCHEMAP_PREFIX_UNDEFINED=1700
|
1272 |
+
SCHEMAP_ATTRFORMDEFAULT_VALUE=1701
|
1273 |
+
SCHEMAP_ATTRGRP_NONAME_NOREF=1702
|
1274 |
+
SCHEMAP_ATTR_NONAME_NOREF=1703
|
1275 |
+
SCHEMAP_COMPLEXTYPE_NONAME_NOREF=1704
|
1276 |
+
SCHEMAP_ELEMFORMDEFAULT_VALUE=1705
|
1277 |
+
SCHEMAP_ELEM_NONAME_NOREF=1706
|
1278 |
+
SCHEMAP_EXTENSION_NO_BASE=1707
|
1279 |
+
SCHEMAP_FACET_NO_VALUE=1708
|
1280 |
+
SCHEMAP_FAILED_BUILD_IMPORT=1709
|
1281 |
+
SCHEMAP_GROUP_NONAME_NOREF=1710
|
1282 |
+
SCHEMAP_IMPORT_NAMESPACE_NOT_URI=1711
|
1283 |
+
SCHEMAP_IMPORT_REDEFINE_NSNAME=1712
|
1284 |
+
SCHEMAP_IMPORT_SCHEMA_NOT_URI=1713
|
1285 |
+
SCHEMAP_INVALID_BOOLEAN=1714
|
1286 |
+
SCHEMAP_INVALID_ENUM=1715
|
1287 |
+
SCHEMAP_INVALID_FACET=1716
|
1288 |
+
SCHEMAP_INVALID_FACET_VALUE=1717
|
1289 |
+
SCHEMAP_INVALID_MAXOCCURS=1718
|
1290 |
+
SCHEMAP_INVALID_MINOCCURS=1719
|
1291 |
+
SCHEMAP_INVALID_REF_AND_SUBTYPE=1720
|
1292 |
+
SCHEMAP_INVALID_WHITE_SPACE=1721
|
1293 |
+
SCHEMAP_NOATTR_NOREF=1722
|
1294 |
+
SCHEMAP_NOTATION_NO_NAME=1723
|
1295 |
+
SCHEMAP_NOTYPE_NOREF=1724
|
1296 |
+
SCHEMAP_REF_AND_SUBTYPE=1725
|
1297 |
+
SCHEMAP_RESTRICTION_NONAME_NOREF=1726
|
1298 |
+
SCHEMAP_SIMPLETYPE_NONAME=1727
|
1299 |
+
SCHEMAP_TYPE_AND_SUBTYPE=1728
|
1300 |
+
SCHEMAP_UNKNOWN_ALL_CHILD=1729
|
1301 |
+
SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD=1730
|
1302 |
+
SCHEMAP_UNKNOWN_ATTR_CHILD=1731
|
1303 |
+
SCHEMAP_UNKNOWN_ATTRGRP_CHILD=1732
|
1304 |
+
SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP=1733
|
1305 |
+
SCHEMAP_UNKNOWN_BASE_TYPE=1734
|
1306 |
+
SCHEMAP_UNKNOWN_CHOICE_CHILD=1735
|
1307 |
+
SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD=1736
|
1308 |
+
SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD=1737
|
1309 |
+
SCHEMAP_UNKNOWN_ELEM_CHILD=1738
|
1310 |
+
SCHEMAP_UNKNOWN_EXTENSION_CHILD=1739
|
1311 |
+
SCHEMAP_UNKNOWN_FACET_CHILD=1740
|
1312 |
+
SCHEMAP_UNKNOWN_FACET_TYPE=1741
|
1313 |
+
SCHEMAP_UNKNOWN_GROUP_CHILD=1742
|
1314 |
+
SCHEMAP_UNKNOWN_IMPORT_CHILD=1743
|
1315 |
+
SCHEMAP_UNKNOWN_LIST_CHILD=1744
|
1316 |
+
SCHEMAP_UNKNOWN_NOTATION_CHILD=1745
|
1317 |
+
SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD=1746
|
1318 |
+
SCHEMAP_UNKNOWN_REF=1747
|
1319 |
+
SCHEMAP_UNKNOWN_RESTRICTION_CHILD=1748
|
1320 |
+
SCHEMAP_UNKNOWN_SCHEMAS_CHILD=1749
|
1321 |
+
SCHEMAP_UNKNOWN_SEQUENCE_CHILD=1750
|
1322 |
+
SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD=1751
|
1323 |
+
SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD=1752
|
1324 |
+
SCHEMAP_UNKNOWN_TYPE=1753
|
1325 |
+
SCHEMAP_UNKNOWN_UNION_CHILD=1754
|
1326 |
+
SCHEMAP_ELEM_DEFAULT_FIXED=1755
|
1327 |
+
SCHEMAP_REGEXP_INVALID=1756
|
1328 |
+
SCHEMAP_FAILED_LOAD=1757
|
1329 |
+
SCHEMAP_NOTHING_TO_PARSE=1758
|
1330 |
+
SCHEMAP_NOROOT=1759
|
1331 |
+
SCHEMAP_REDEFINED_GROUP=1760
|
1332 |
+
SCHEMAP_REDEFINED_TYPE=1761
|
1333 |
+
SCHEMAP_REDEFINED_ELEMENT=1762
|
1334 |
+
SCHEMAP_REDEFINED_ATTRGROUP=1763
|
1335 |
+
SCHEMAP_REDEFINED_ATTR=1764
|
1336 |
+
SCHEMAP_REDEFINED_NOTATION=1765
|
1337 |
+
SCHEMAP_FAILED_PARSE=1766
|
1338 |
+
SCHEMAP_UNKNOWN_PREFIX=1767
|
1339 |
+
SCHEMAP_DEF_AND_PREFIX=1768
|
1340 |
+
SCHEMAP_UNKNOWN_INCLUDE_CHILD=1769
|
1341 |
+
SCHEMAP_INCLUDE_SCHEMA_NOT_URI=1770
|
1342 |
+
SCHEMAP_INCLUDE_SCHEMA_NO_URI=1771
|
1343 |
+
SCHEMAP_NOT_SCHEMA=1772
|
1344 |
+
SCHEMAP_UNKNOWN_MEMBER_TYPE=1773
|
1345 |
+
SCHEMAP_INVALID_ATTR_USE=1774
|
1346 |
+
SCHEMAP_RECURSIVE=1775
|
1347 |
+
SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE=1776
|
1348 |
+
SCHEMAP_INVALID_ATTR_COMBINATION=1777
|
1349 |
+
SCHEMAP_INVALID_ATTR_INLINE_COMBINATION=1778
|
1350 |
+
SCHEMAP_MISSING_SIMPLETYPE_CHILD=1779
|
1351 |
+
SCHEMAP_INVALID_ATTR_NAME=1780
|
1352 |
+
SCHEMAP_REF_AND_CONTENT=1781
|
1353 |
+
SCHEMAP_CT_PROPS_CORRECT_1=1782
|
1354 |
+
SCHEMAP_CT_PROPS_CORRECT_2=1783
|
1355 |
+
SCHEMAP_CT_PROPS_CORRECT_3=1784
|
1356 |
+
SCHEMAP_CT_PROPS_CORRECT_4=1785
|
1357 |
+
SCHEMAP_CT_PROPS_CORRECT_5=1786
|
1358 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_1=1787
|
1359 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1=1788
|
1360 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2=1789
|
1361 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_2_2=1790
|
1362 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_3=1791
|
1363 |
+
SCHEMAP_WILDCARD_INVALID_NS_MEMBER=1792
|
1364 |
+
SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE=1793
|
1365 |
+
SCHEMAP_UNION_NOT_EXPRESSIBLE=1794
|
1366 |
+
SCHEMAP_SRC_IMPORT_3_1=1795
|
1367 |
+
SCHEMAP_SRC_IMPORT_3_2=1796
|
1368 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_4_1=1797
|
1369 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_4_2=1798
|
1370 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_4_3=1799
|
1371 |
+
SCHEMAP_COS_CT_EXTENDS_1_3=1800
|
1372 |
+
SCHEMAV_NOROOT=1801
|
1373 |
+
SCHEMAV_UNDECLAREDELEM=1802
|
1374 |
+
SCHEMAV_NOTTOPLEVEL=1803
|
1375 |
+
SCHEMAV_MISSING=1804
|
1376 |
+
SCHEMAV_WRONGELEM=1805
|
1377 |
+
SCHEMAV_NOTYPE=1806
|
1378 |
+
SCHEMAV_NOROLLBACK=1807
|
1379 |
+
SCHEMAV_ISABSTRACT=1808
|
1380 |
+
SCHEMAV_NOTEMPTY=1809
|
1381 |
+
SCHEMAV_ELEMCONT=1810
|
1382 |
+
SCHEMAV_HAVEDEFAULT=1811
|
1383 |
+
SCHEMAV_NOTNILLABLE=1812
|
1384 |
+
SCHEMAV_EXTRACONTENT=1813
|
1385 |
+
SCHEMAV_INVALIDATTR=1814
|
1386 |
+
SCHEMAV_INVALIDELEM=1815
|
1387 |
+
SCHEMAV_NOTDETERMINIST=1816
|
1388 |
+
SCHEMAV_CONSTRUCT=1817
|
1389 |
+
SCHEMAV_INTERNAL=1818
|
1390 |
+
SCHEMAV_NOTSIMPLE=1819
|
1391 |
+
SCHEMAV_ATTRUNKNOWN=1820
|
1392 |
+
SCHEMAV_ATTRINVALID=1821
|
1393 |
+
SCHEMAV_VALUE=1822
|
1394 |
+
SCHEMAV_FACET=1823
|
1395 |
+
SCHEMAV_CVC_DATATYPE_VALID_1_2_1=1824
|
1396 |
+
SCHEMAV_CVC_DATATYPE_VALID_1_2_2=1825
|
1397 |
+
SCHEMAV_CVC_DATATYPE_VALID_1_2_3=1826
|
1398 |
+
SCHEMAV_CVC_TYPE_3_1_1=1827
|
1399 |
+
SCHEMAV_CVC_TYPE_3_1_2=1828
|
1400 |
+
SCHEMAV_CVC_FACET_VALID=1829
|
1401 |
+
SCHEMAV_CVC_LENGTH_VALID=1830
|
1402 |
+
SCHEMAV_CVC_MINLENGTH_VALID=1831
|
1403 |
+
SCHEMAV_CVC_MAXLENGTH_VALID=1832
|
1404 |
+
SCHEMAV_CVC_MININCLUSIVE_VALID=1833
|
1405 |
+
SCHEMAV_CVC_MAXINCLUSIVE_VALID=1834
|
1406 |
+
SCHEMAV_CVC_MINEXCLUSIVE_VALID=1835
|
1407 |
+
SCHEMAV_CVC_MAXEXCLUSIVE_VALID=1836
|
1408 |
+
SCHEMAV_CVC_TOTALDIGITS_VALID=1837
|
1409 |
+
SCHEMAV_CVC_FRACTIONDIGITS_VALID=1838
|
1410 |
+
SCHEMAV_CVC_PATTERN_VALID=1839
|
1411 |
+
SCHEMAV_CVC_ENUMERATION_VALID=1840
|
1412 |
+
SCHEMAV_CVC_COMPLEX_TYPE_2_1=1841
|
1413 |
+
SCHEMAV_CVC_COMPLEX_TYPE_2_2=1842
|
1414 |
+
SCHEMAV_CVC_COMPLEX_TYPE_2_3=1843
|
1415 |
+
SCHEMAV_CVC_COMPLEX_TYPE_2_4=1844
|
1416 |
+
SCHEMAV_CVC_ELT_1=1845
|
1417 |
+
SCHEMAV_CVC_ELT_2=1846
|
1418 |
+
SCHEMAV_CVC_ELT_3_1=1847
|
1419 |
+
SCHEMAV_CVC_ELT_3_2_1=1848
|
1420 |
+
SCHEMAV_CVC_ELT_3_2_2=1849
|
1421 |
+
SCHEMAV_CVC_ELT_4_1=1850
|
1422 |
+
SCHEMAV_CVC_ELT_4_2=1851
|
1423 |
+
SCHEMAV_CVC_ELT_4_3=1852
|
1424 |
+
SCHEMAV_CVC_ELT_5_1_1=1853
|
1425 |
+
SCHEMAV_CVC_ELT_5_1_2=1854
|
1426 |
+
SCHEMAV_CVC_ELT_5_2_1=1855
|
1427 |
+
SCHEMAV_CVC_ELT_5_2_2_1=1856
|
1428 |
+
SCHEMAV_CVC_ELT_5_2_2_2_1=1857
|
1429 |
+
SCHEMAV_CVC_ELT_5_2_2_2_2=1858
|
1430 |
+
SCHEMAV_CVC_ELT_6=1859
|
1431 |
+
SCHEMAV_CVC_ELT_7=1860
|
1432 |
+
SCHEMAV_CVC_ATTRIBUTE_1=1861
|
1433 |
+
SCHEMAV_CVC_ATTRIBUTE_2=1862
|
1434 |
+
SCHEMAV_CVC_ATTRIBUTE_3=1863
|
1435 |
+
SCHEMAV_CVC_ATTRIBUTE_4=1864
|
1436 |
+
SCHEMAV_CVC_COMPLEX_TYPE_3_1=1865
|
1437 |
+
SCHEMAV_CVC_COMPLEX_TYPE_3_2_1=1866
|
1438 |
+
SCHEMAV_CVC_COMPLEX_TYPE_3_2_2=1867
|
1439 |
+
SCHEMAV_CVC_COMPLEX_TYPE_4=1868
|
1440 |
+
SCHEMAV_CVC_COMPLEX_TYPE_5_1=1869
|
1441 |
+
SCHEMAV_CVC_COMPLEX_TYPE_5_2=1870
|
1442 |
+
SCHEMAV_ELEMENT_CONTENT=1871
|
1443 |
+
SCHEMAV_DOCUMENT_ELEMENT_MISSING=1872
|
1444 |
+
SCHEMAV_CVC_COMPLEX_TYPE_1=1873
|
1445 |
+
SCHEMAV_CVC_AU=1874
|
1446 |
+
SCHEMAV_CVC_TYPE_1=1875
|
1447 |
+
SCHEMAV_CVC_TYPE_2=1876
|
1448 |
+
SCHEMAV_CVC_IDC=1877
|
1449 |
+
SCHEMAV_CVC_WILDCARD=1878
|
1450 |
+
SCHEMAV_MISC=1879
|
1451 |
+
XPTR_UNKNOWN_SCHEME=1900
|
1452 |
+
XPTR_CHILDSEQ_START=1901
|
1453 |
+
XPTR_EVAL_FAILED=1902
|
1454 |
+
XPTR_EXTRA_OBJECTS=1903
|
1455 |
+
C14N_CREATE_CTXT=1950
|
1456 |
+
C14N_REQUIRES_UTF8=1951
|
1457 |
+
C14N_CREATE_STACK=1952
|
1458 |
+
C14N_INVALID_NODE=1953
|
1459 |
+
C14N_UNKNOW_NODE=1954
|
1460 |
+
C14N_RELATIVE_NAMESPACE=1955
|
1461 |
+
FTP_PASV_ANSWER=2000
|
1462 |
+
FTP_EPSV_ANSWER=2001
|
1463 |
+
FTP_ACCNT=2002
|
1464 |
+
FTP_URL_SYNTAX=2003
|
1465 |
+
HTTP_URL_SYNTAX=2020
|
1466 |
+
HTTP_USE_IP=2021
|
1467 |
+
HTTP_UNKNOWN_HOST=2022
|
1468 |
+
SCHEMAP_SRC_SIMPLE_TYPE_1=3000
|
1469 |
+
SCHEMAP_SRC_SIMPLE_TYPE_2=3001
|
1470 |
+
SCHEMAP_SRC_SIMPLE_TYPE_3=3002
|
1471 |
+
SCHEMAP_SRC_SIMPLE_TYPE_4=3003
|
1472 |
+
SCHEMAP_SRC_RESOLVE=3004
|
1473 |
+
SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE=3005
|
1474 |
+
SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE=3006
|
1475 |
+
SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES=3007
|
1476 |
+
SCHEMAP_ST_PROPS_CORRECT_1=3008
|
1477 |
+
SCHEMAP_ST_PROPS_CORRECT_2=3009
|
1478 |
+
SCHEMAP_ST_PROPS_CORRECT_3=3010
|
1479 |
+
SCHEMAP_COS_ST_RESTRICTS_1_1=3011
|
1480 |
+
SCHEMAP_COS_ST_RESTRICTS_1_2=3012
|
1481 |
+
SCHEMAP_COS_ST_RESTRICTS_1_3_1=3013
|
1482 |
+
SCHEMAP_COS_ST_RESTRICTS_1_3_2=3014
|
1483 |
+
SCHEMAP_COS_ST_RESTRICTS_2_1=3015
|
1484 |
+
SCHEMAP_COS_ST_RESTRICTS_2_3_1_1=3016
|
1485 |
+
SCHEMAP_COS_ST_RESTRICTS_2_3_1_2=3017
|
1486 |
+
SCHEMAP_COS_ST_RESTRICTS_2_3_2_1=3018
|
1487 |
+
SCHEMAP_COS_ST_RESTRICTS_2_3_2_2=3019
|
1488 |
+
SCHEMAP_COS_ST_RESTRICTS_2_3_2_3=3020
|
1489 |
+
SCHEMAP_COS_ST_RESTRICTS_2_3_2_4=3021
|
1490 |
+
SCHEMAP_COS_ST_RESTRICTS_2_3_2_5=3022
|
1491 |
+
SCHEMAP_COS_ST_RESTRICTS_3_1=3023
|
1492 |
+
SCHEMAP_COS_ST_RESTRICTS_3_3_1=3024
|
1493 |
+
SCHEMAP_COS_ST_RESTRICTS_3_3_1_2=3025
|
1494 |
+
SCHEMAP_COS_ST_RESTRICTS_3_3_2_2=3026
|
1495 |
+
SCHEMAP_COS_ST_RESTRICTS_3_3_2_1=3027
|
1496 |
+
SCHEMAP_COS_ST_RESTRICTS_3_3_2_3=3028
|
1497 |
+
SCHEMAP_COS_ST_RESTRICTS_3_3_2_4=3029
|
1498 |
+
SCHEMAP_COS_ST_RESTRICTS_3_3_2_5=3030
|
1499 |
+
SCHEMAP_COS_ST_DERIVED_OK_2_1=3031
|
1500 |
+
SCHEMAP_COS_ST_DERIVED_OK_2_2=3032
|
1501 |
+
SCHEMAP_S4S_ELEM_NOT_ALLOWED=3033
|
1502 |
+
SCHEMAP_S4S_ELEM_MISSING=3034
|
1503 |
+
SCHEMAP_S4S_ATTR_NOT_ALLOWED=3035
|
1504 |
+
SCHEMAP_S4S_ATTR_MISSING=3036
|
1505 |
+
SCHEMAP_S4S_ATTR_INVALID_VALUE=3037
|
1506 |
+
SCHEMAP_SRC_ELEMENT_1=3038
|
1507 |
+
SCHEMAP_SRC_ELEMENT_2_1=3039
|
1508 |
+
SCHEMAP_SRC_ELEMENT_2_2=3040
|
1509 |
+
SCHEMAP_SRC_ELEMENT_3=3041
|
1510 |
+
SCHEMAP_P_PROPS_CORRECT_1=3042
|
1511 |
+
SCHEMAP_P_PROPS_CORRECT_2_1=3043
|
1512 |
+
SCHEMAP_P_PROPS_CORRECT_2_2=3044
|
1513 |
+
SCHEMAP_E_PROPS_CORRECT_2=3045
|
1514 |
+
SCHEMAP_E_PROPS_CORRECT_3=3046
|
1515 |
+
SCHEMAP_E_PROPS_CORRECT_4=3047
|
1516 |
+
SCHEMAP_E_PROPS_CORRECT_5=3048
|
1517 |
+
SCHEMAP_E_PROPS_CORRECT_6=3049
|
1518 |
+
SCHEMAP_SRC_INCLUDE=3050
|
1519 |
+
SCHEMAP_SRC_ATTRIBUTE_1=3051
|
1520 |
+
SCHEMAP_SRC_ATTRIBUTE_2=3052
|
1521 |
+
SCHEMAP_SRC_ATTRIBUTE_3_1=3053
|
1522 |
+
SCHEMAP_SRC_ATTRIBUTE_3_2=3054
|
1523 |
+
SCHEMAP_SRC_ATTRIBUTE_4=3055
|
1524 |
+
SCHEMAP_NO_XMLNS=3056
|
1525 |
+
SCHEMAP_NO_XSI=3057
|
1526 |
+
SCHEMAP_COS_VALID_DEFAULT_1=3058
|
1527 |
+
SCHEMAP_COS_VALID_DEFAULT_2_1=3059
|
1528 |
+
SCHEMAP_COS_VALID_DEFAULT_2_2_1=3060
|
1529 |
+
SCHEMAP_COS_VALID_DEFAULT_2_2_2=3061
|
1530 |
+
SCHEMAP_CVC_SIMPLE_TYPE=3062
|
1531 |
+
SCHEMAP_COS_CT_EXTENDS_1_1=3063
|
1532 |
+
SCHEMAP_SRC_IMPORT_1_1=3064
|
1533 |
+
SCHEMAP_SRC_IMPORT_1_2=3065
|
1534 |
+
SCHEMAP_SRC_IMPORT_2=3066
|
1535 |
+
SCHEMAP_SRC_IMPORT_2_1=3067
|
1536 |
+
SCHEMAP_SRC_IMPORT_2_2=3068
|
1537 |
+
SCHEMAP_INTERNAL=3069
|
1538 |
+
SCHEMAP_NOT_DETERMINISTIC=3070
|
1539 |
+
SCHEMAP_SRC_ATTRIBUTE_GROUP_1=3071
|
1540 |
+
SCHEMAP_SRC_ATTRIBUTE_GROUP_2=3072
|
1541 |
+
SCHEMAP_SRC_ATTRIBUTE_GROUP_3=3073
|
1542 |
+
SCHEMAP_MG_PROPS_CORRECT_1=3074
|
1543 |
+
SCHEMAP_MG_PROPS_CORRECT_2=3075
|
1544 |
+
SCHEMAP_SRC_CT_1=3076
|
1545 |
+
SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3=3077
|
1546 |
+
SCHEMAP_AU_PROPS_CORRECT_2=3078
|
1547 |
+
SCHEMAP_A_PROPS_CORRECT_2=3079
|
1548 |
+
SCHEMAP_C_PROPS_CORRECT=3080
|
1549 |
+
SCHEMAP_SRC_REDEFINE=3081
|
1550 |
+
SCHEMAP_SRC_IMPORT=3082
|
1551 |
+
SCHEMAP_WARN_SKIP_SCHEMA=3083
|
1552 |
+
SCHEMAP_WARN_UNLOCATED_SCHEMA=3084
|
1553 |
+
SCHEMAP_WARN_ATTR_REDECL_PROH=3085
|
1554 |
+
SCHEMAP_WARN_ATTR_POINTLESS_PROH=3086
|
1555 |
+
SCHEMAP_AG_PROPS_CORRECT=3087
|
1556 |
+
SCHEMAP_COS_CT_EXTENDS_1_2=3088
|
1557 |
+
SCHEMAP_AU_PROPS_CORRECT=3089
|
1558 |
+
SCHEMAP_A_PROPS_CORRECT_3=3090
|
1559 |
+
SCHEMAP_COS_ALL_LIMITED=3091
|
1560 |
+
SCHEMATRONV_ASSERT=4000
|
1561 |
+
SCHEMATRONV_REPORT=4001
|
1562 |
+
MODULE_OPEN=4900
|
1563 |
+
MODULE_CLOSE=4901
|
1564 |
+
CHECK_FOUND_ELEMENT=5000
|
1565 |
+
CHECK_FOUND_ATTRIBUTE=5001
|
1566 |
+
CHECK_FOUND_TEXT=5002
|
1567 |
+
CHECK_FOUND_CDATA=5003
|
1568 |
+
CHECK_FOUND_ENTITYREF=5004
|
1569 |
+
CHECK_FOUND_ENTITY=5005
|
1570 |
+
CHECK_FOUND_PI=5006
|
1571 |
+
CHECK_FOUND_COMMENT=5007
|
1572 |
+
CHECK_FOUND_DOCTYPE=5008
|
1573 |
+
CHECK_FOUND_FRAGMENT=5009
|
1574 |
+
CHECK_FOUND_NOTATION=5010
|
1575 |
+
CHECK_UNKNOWN_NODE=5011
|
1576 |
+
CHECK_ENTITY_TYPE=5012
|
1577 |
+
CHECK_NO_PARENT=5013
|
1578 |
+
CHECK_NO_DOC=5014
|
1579 |
+
CHECK_NO_NAME=5015
|
1580 |
+
CHECK_NO_ELEM=5016
|
1581 |
+
CHECK_WRONG_DOC=5017
|
1582 |
+
CHECK_NO_PREV=5018
|
1583 |
+
CHECK_WRONG_PREV=5019
|
1584 |
+
CHECK_NO_NEXT=5020
|
1585 |
+
CHECK_WRONG_NEXT=5021
|
1586 |
+
CHECK_NOT_DTD=5022
|
1587 |
+
CHECK_NOT_ATTR=5023
|
1588 |
+
CHECK_NOT_ATTR_DECL=5024
|
1589 |
+
CHECK_NOT_ELEM_DECL=5025
|
1590 |
+
CHECK_NOT_ENTITY_DECL=5026
|
1591 |
+
CHECK_NOT_NS_DECL=5027
|
1592 |
+
CHECK_NO_HREF=5028
|
1593 |
+
CHECK_WRONG_PARENT=5029
|
1594 |
+
CHECK_NS_SCOPE=5030
|
1595 |
+
CHECK_NS_ANCESTOR=5031
|
1596 |
+
CHECK_NOT_UTF8=5032
|
1597 |
+
CHECK_NO_DICT=5033
|
1598 |
+
CHECK_NOT_NCNAME=5034
|
1599 |
+
CHECK_OUTSIDE_DICT=5035
|
1600 |
+
CHECK_WRONG_NAME=5036
|
1601 |
+
CHECK_NAME_NOT_NULL=5037
|
1602 |
+
I18N_NO_NAME=6000
|
1603 |
+
I18N_NO_HANDLER=6001
|
1604 |
+
I18N_EXCESS_HANDLER=6002
|
1605 |
+
I18N_CONV_FAILED=6003
|
1606 |
+
I18N_NO_OUTPUT=6004
|
1607 |
+
BUF_OVERFLOW=7000
|
1608 |
+
"""
|
1609 |
+
|
1610 |
+
cdef object __RELAXNG_ERROR_TYPES = """\
|
1611 |
+
RELAXNG_OK=0
|
1612 |
+
RELAXNG_ERR_MEMORY=1
|
1613 |
+
RELAXNG_ERR_TYPE=2
|
1614 |
+
RELAXNG_ERR_TYPEVAL=3
|
1615 |
+
RELAXNG_ERR_DUPID=4
|
1616 |
+
RELAXNG_ERR_TYPECMP=5
|
1617 |
+
RELAXNG_ERR_NOSTATE=6
|
1618 |
+
RELAXNG_ERR_NODEFINE=7
|
1619 |
+
RELAXNG_ERR_LISTEXTRA=8
|
1620 |
+
RELAXNG_ERR_LISTEMPTY=9
|
1621 |
+
RELAXNG_ERR_INTERNODATA=10
|
1622 |
+
RELAXNG_ERR_INTERSEQ=11
|
1623 |
+
RELAXNG_ERR_INTEREXTRA=12
|
1624 |
+
RELAXNG_ERR_ELEMNAME=13
|
1625 |
+
RELAXNG_ERR_ATTRNAME=14
|
1626 |
+
RELAXNG_ERR_ELEMNONS=15
|
1627 |
+
RELAXNG_ERR_ATTRNONS=16
|
1628 |
+
RELAXNG_ERR_ELEMWRONGNS=17
|
1629 |
+
RELAXNG_ERR_ATTRWRONGNS=18
|
1630 |
+
RELAXNG_ERR_ELEMEXTRANS=19
|
1631 |
+
RELAXNG_ERR_ATTREXTRANS=20
|
1632 |
+
RELAXNG_ERR_ELEMNOTEMPTY=21
|
1633 |
+
RELAXNG_ERR_NOELEM=22
|
1634 |
+
RELAXNG_ERR_NOTELEM=23
|
1635 |
+
RELAXNG_ERR_ATTRVALID=24
|
1636 |
+
RELAXNG_ERR_CONTENTVALID=25
|
1637 |
+
RELAXNG_ERR_EXTRACONTENT=26
|
1638 |
+
RELAXNG_ERR_INVALIDATTR=27
|
1639 |
+
RELAXNG_ERR_DATAELEM=28
|
1640 |
+
RELAXNG_ERR_VALELEM=29
|
1641 |
+
RELAXNG_ERR_LISTELEM=30
|
1642 |
+
RELAXNG_ERR_DATATYPE=31
|
1643 |
+
RELAXNG_ERR_VALUE=32
|
1644 |
+
RELAXNG_ERR_LIST=33
|
1645 |
+
RELAXNG_ERR_NOGRAMMAR=34
|
1646 |
+
RELAXNG_ERR_EXTRADATA=35
|
1647 |
+
RELAXNG_ERR_LACKDATA=36
|
1648 |
+
RELAXNG_ERR_INTERNAL=37
|
1649 |
+
RELAXNG_ERR_ELEMWRONG=38
|
1650 |
+
RELAXNG_ERR_TEXTWRONG=39
|
1651 |
+
"""
|
1652 |
+
# --- END: GENERATED CONSTANTS ---
|
1653 |
+
|
1654 |
+
__initErrorConstants()
|
env-llmeval/lib/python3.10/site-packages/lxml/xmlid.pxi
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
cdef object _find_id_attributes
|
2 |
+
|
3 |
+
def XMLID(text, parser=None, *, base_url=None):
|
4 |
+
"""XMLID(text, parser=None, base_url=None)
|
5 |
+
|
6 |
+
Parse the text and return a tuple (root node, ID dictionary). The root
|
7 |
+
node is the same as returned by the XML() function. The dictionary
|
8 |
+
contains string-element pairs. The dictionary keys are the values of 'id'
|
9 |
+
attributes. The elements referenced by the ID are stored as dictionary
|
10 |
+
values.
|
11 |
+
"""
|
12 |
+
cdef dict dic
|
13 |
+
global _find_id_attributes
|
14 |
+
if _find_id_attributes is None:
|
15 |
+
_find_id_attributes = XPath('//*[string(@id)]')
|
16 |
+
|
17 |
+
# ElementTree compatible implementation: parse and look for 'id' attributes
|
18 |
+
root = XML(text, parser, base_url=base_url)
|
19 |
+
dic = {}
|
20 |
+
for elem in _find_id_attributes(root):
|
21 |
+
dic[elem.get('id')] = elem
|
22 |
+
return root, dic
|
23 |
+
|
24 |
+
def XMLDTDID(text, parser=None, *, base_url=None):
|
25 |
+
"""XMLDTDID(text, parser=None, base_url=None)
|
26 |
+
|
27 |
+
Parse the text and return a tuple (root node, ID dictionary). The root
|
28 |
+
node is the same as returned by the XML() function. The dictionary
|
29 |
+
contains string-element pairs. The dictionary keys are the values of ID
|
30 |
+
attributes as defined by the DTD. The elements referenced by the ID are
|
31 |
+
stored as dictionary values.
|
32 |
+
|
33 |
+
Note that you must not modify the XML tree if you use the ID dictionary.
|
34 |
+
The results are undefined.
|
35 |
+
"""
|
36 |
+
cdef _Element root
|
37 |
+
root = XML(text, parser, base_url=base_url)
|
38 |
+
# xml:id spec compatible implementation: use DTD ID attributes from libxml2
|
39 |
+
if root._doc._c_doc.ids is NULL:
|
40 |
+
return root, {}
|
41 |
+
else:
|
42 |
+
return root, _IDDict(root)
|
43 |
+
|
44 |
+
def parseid(source, parser=None, *, base_url=None):
|
45 |
+
"""parseid(source, parser=None)
|
46 |
+
|
47 |
+
Parses the source into a tuple containing an ElementTree object and an
|
48 |
+
ID dictionary. If no parser is provided as second argument, the default
|
49 |
+
parser is used.
|
50 |
+
|
51 |
+
Note that you must not modify the XML tree if you use the ID dictionary.
|
52 |
+
The results are undefined.
|
53 |
+
"""
|
54 |
+
cdef _Document doc
|
55 |
+
doc = _parseDocument(source, parser, base_url)
|
56 |
+
return _elementTreeFactory(doc, None), _IDDict(doc)
|
57 |
+
|
58 |
+
cdef class _IDDict:
|
59 |
+
"""IDDict(self, etree)
|
60 |
+
A dictionary-like proxy class that mapps ID attributes to elements.
|
61 |
+
|
62 |
+
The dictionary must be instantiated with the root element of a parsed XML
|
63 |
+
document, otherwise the behaviour is undefined. Elements and XML trees
|
64 |
+
that were created or modified 'by hand' are not supported.
|
65 |
+
"""
|
66 |
+
cdef _Document _doc
|
67 |
+
cdef object _keys
|
68 |
+
cdef object _items
|
69 |
+
def __cinit__(self, etree):
|
70 |
+
cdef _Document doc
|
71 |
+
doc = _documentOrRaise(etree)
|
72 |
+
if doc._c_doc.ids is NULL:
|
73 |
+
raise ValueError, "No ID dictionary available."
|
74 |
+
self._doc = doc
|
75 |
+
self._keys = None
|
76 |
+
self._items = None
|
77 |
+
|
78 |
+
def copy(self):
|
79 |
+
return _IDDict(self._doc)
|
80 |
+
|
81 |
+
def __getitem__(self, id_name):
|
82 |
+
cdef tree.xmlHashTable* c_ids
|
83 |
+
cdef tree.xmlID* c_id
|
84 |
+
cdef xmlAttr* c_attr
|
85 |
+
c_ids = self._doc._c_doc.ids
|
86 |
+
id_utf = _utf8(id_name)
|
87 |
+
c_id = <tree.xmlID*>tree.xmlHashLookup(c_ids, _xcstr(id_utf))
|
88 |
+
if c_id is NULL:
|
89 |
+
raise KeyError, "key not found."
|
90 |
+
c_attr = c_id.attr
|
91 |
+
if c_attr is NULL or c_attr.parent is NULL:
|
92 |
+
raise KeyError, "ID attribute not found."
|
93 |
+
return _elementFactory(self._doc, c_attr.parent)
|
94 |
+
|
95 |
+
def get(self, id_name):
|
96 |
+
return self[id_name]
|
97 |
+
|
98 |
+
def __contains__(self, id_name):
|
99 |
+
cdef tree.xmlID* c_id
|
100 |
+
id_utf = _utf8(id_name)
|
101 |
+
c_id = <tree.xmlID*>tree.xmlHashLookup(
|
102 |
+
self._doc._c_doc.ids, _xcstr(id_utf))
|
103 |
+
return c_id is not NULL
|
104 |
+
|
105 |
+
def has_key(self, id_name):
|
106 |
+
return id_name in self
|
107 |
+
|
108 |
+
def __repr__(self):
|
109 |
+
return repr(dict(self))
|
110 |
+
|
111 |
+
def keys(self):
|
112 |
+
if self._keys is None:
|
113 |
+
self._keys = self._build_keys()
|
114 |
+
return self._keys[:]
|
115 |
+
|
116 |
+
def __iter__(self):
|
117 |
+
if self._keys is None:
|
118 |
+
self._keys = self._build_keys()
|
119 |
+
return iter(self._keys)
|
120 |
+
|
121 |
+
def iterkeys(self):
|
122 |
+
return self
|
123 |
+
|
124 |
+
def __len__(self):
|
125 |
+
if self._keys is None:
|
126 |
+
self._keys = self._build_keys()
|
127 |
+
return len(self._keys)
|
128 |
+
|
129 |
+
def items(self):
|
130 |
+
if self._items is None:
|
131 |
+
self._items = self._build_items()
|
132 |
+
return self._items[:]
|
133 |
+
|
134 |
+
def iteritems(self):
|
135 |
+
if self._items is None:
|
136 |
+
self._items = self._build_items()
|
137 |
+
return iter(self._items)
|
138 |
+
|
139 |
+
def values(self):
|
140 |
+
cdef list values = []
|
141 |
+
if self._items is None:
|
142 |
+
self._items = self._build_items()
|
143 |
+
for item in self._items:
|
144 |
+
value = python.PyTuple_GET_ITEM(item, 1)
|
145 |
+
python.Py_INCREF(value)
|
146 |
+
values.append(value)
|
147 |
+
return values
|
148 |
+
|
149 |
+
def itervalues(self):
|
150 |
+
return iter(self.values())
|
151 |
+
|
152 |
+
cdef object _build_keys(self):
|
153 |
+
keys = []
|
154 |
+
tree.xmlHashScan(<tree.xmlHashTable*>self._doc._c_doc.ids,
|
155 |
+
<tree.xmlHashScanner>_collectIdHashKeys, <python.PyObject*>keys)
|
156 |
+
return keys
|
157 |
+
|
158 |
+
cdef object _build_items(self):
|
159 |
+
items = []
|
160 |
+
context = (items, self._doc)
|
161 |
+
tree.xmlHashScan(<tree.xmlHashTable*>self._doc._c_doc.ids,
|
162 |
+
<tree.xmlHashScanner>_collectIdHashItemList, <python.PyObject*>context)
|
163 |
+
return items
|
164 |
+
|
165 |
+
cdef void _collectIdHashItemList(void* payload, void* context, xmlChar* name) noexcept:
|
166 |
+
# collect elements from ID attribute hash table
|
167 |
+
cdef list lst
|
168 |
+
c_id = <tree.xmlID*>payload
|
169 |
+
if c_id is NULL or c_id.attr is NULL or c_id.attr.parent is NULL:
|
170 |
+
return
|
171 |
+
lst, doc = <tuple>context
|
172 |
+
element = _elementFactory(doc, c_id.attr.parent)
|
173 |
+
lst.append( (funicode(name), element) )
|
174 |
+
|
175 |
+
cdef void _collectIdHashKeys(void* payload, void* collect_list, xmlChar* name) noexcept:
|
176 |
+
c_id = <tree.xmlID*>payload
|
177 |
+
if c_id is NULL or c_id.attr is NULL or c_id.attr.parent is NULL:
|
178 |
+
return
|
179 |
+
(<list>collect_list).append(funicode(name))
|
env-llmeval/lib/python3.10/site-packages/lxml/xmlschema.pxi
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# support for XMLSchema validation
|
2 |
+
from lxml.includes cimport xmlschema
|
3 |
+
|
4 |
+
|
5 |
+
cdef class XMLSchemaError(LxmlError):
|
6 |
+
"""Base class of all XML Schema errors
|
7 |
+
"""
|
8 |
+
|
9 |
+
cdef class XMLSchemaParseError(XMLSchemaError):
|
10 |
+
"""Error while parsing an XML document as XML Schema.
|
11 |
+
"""
|
12 |
+
|
13 |
+
cdef class XMLSchemaValidateError(XMLSchemaError):
|
14 |
+
"""Error while validating an XML document with an XML Schema.
|
15 |
+
"""
|
16 |
+
|
17 |
+
|
18 |
+
################################################################################
|
19 |
+
# XMLSchema
|
20 |
+
|
21 |
+
cdef XPath _check_for_default_attributes = XPath(
|
22 |
+
"boolean(//xs:attribute[@default or @fixed][1])",
|
23 |
+
namespaces={'xs': 'http://www.w3.org/2001/XMLSchema'})
|
24 |
+
|
25 |
+
|
26 |
+
cdef class XMLSchema(_Validator):
|
27 |
+
"""XMLSchema(self, etree=None, file=None)
|
28 |
+
Turn a document into an XML Schema validator.
|
29 |
+
|
30 |
+
Either pass a schema as Element or ElementTree, or pass a file or
|
31 |
+
filename through the ``file`` keyword argument.
|
32 |
+
|
33 |
+
Passing the ``attribute_defaults`` boolean option will make the
|
34 |
+
schema insert default/fixed attributes into validated documents.
|
35 |
+
"""
|
36 |
+
cdef xmlschema.xmlSchema* _c_schema
|
37 |
+
cdef _Document _doc
|
38 |
+
cdef bint _has_default_attributes
|
39 |
+
cdef bint _add_attribute_defaults
|
40 |
+
|
41 |
+
def __cinit__(self):
|
42 |
+
self._has_default_attributes = True # play it safe
|
43 |
+
self._add_attribute_defaults = False
|
44 |
+
|
45 |
+
def __init__(self, etree=None, *, file=None, bint attribute_defaults=False):
|
46 |
+
cdef xmlschema.xmlSchemaParserCtxt* parser_ctxt
|
47 |
+
cdef xmlDoc* c_doc
|
48 |
+
|
49 |
+
self._add_attribute_defaults = attribute_defaults
|
50 |
+
_Validator.__init__(self)
|
51 |
+
c_doc = NULL
|
52 |
+
if etree is not None:
|
53 |
+
doc = _documentOrRaise(etree)
|
54 |
+
root_node = _rootNodeOrRaise(etree)
|
55 |
+
c_doc = _copyDocRoot(doc._c_doc, root_node._c_node)
|
56 |
+
self._doc = _documentFactory(c_doc, doc._parser)
|
57 |
+
parser_ctxt = xmlschema.xmlSchemaNewDocParserCtxt(c_doc)
|
58 |
+
elif file is not None:
|
59 |
+
file = _getFSPathOrObject(file)
|
60 |
+
if _isString(file):
|
61 |
+
filename = _encodeFilename(file)
|
62 |
+
parser_ctxt = xmlschema.xmlSchemaNewParserCtxt(_cstr(filename))
|
63 |
+
else:
|
64 |
+
self._doc = _parseDocument(file, None, None)
|
65 |
+
parser_ctxt = xmlschema.xmlSchemaNewDocParserCtxt(self._doc._c_doc)
|
66 |
+
else:
|
67 |
+
raise XMLSchemaParseError, "No tree or file given"
|
68 |
+
|
69 |
+
if parser_ctxt is NULL:
|
70 |
+
raise MemoryError()
|
71 |
+
|
72 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
73 |
+
xmlschema.xmlSchemaSetParserStructuredErrors(
|
74 |
+
parser_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
|
75 |
+
if self._doc is not None:
|
76 |
+
# calling xmlSchemaParse on a schema with imports or
|
77 |
+
# includes will cause libxml2 to create an internal
|
78 |
+
# context for parsing, so push an implied context to route
|
79 |
+
# resolve requests to the document's parser
|
80 |
+
__GLOBAL_PARSER_CONTEXT.pushImpliedContextFromParser(self._doc._parser)
|
81 |
+
with nogil:
|
82 |
+
orig_loader = _register_document_loader()
|
83 |
+
self._c_schema = xmlschema.xmlSchemaParse(parser_ctxt)
|
84 |
+
_reset_document_loader(orig_loader)
|
85 |
+
if self._doc is not None:
|
86 |
+
__GLOBAL_PARSER_CONTEXT.popImpliedContext()
|
87 |
+
xmlschema.xmlSchemaFreeParserCtxt(parser_ctxt)
|
88 |
+
|
89 |
+
if self._c_schema is NULL:
|
90 |
+
raise XMLSchemaParseError(
|
91 |
+
self._error_log._buildExceptionMessage(
|
92 |
+
"Document is not valid XML Schema"),
|
93 |
+
self._error_log)
|
94 |
+
|
95 |
+
if self._doc is not None:
|
96 |
+
self._has_default_attributes = _check_for_default_attributes(self._doc)
|
97 |
+
self._add_attribute_defaults = attribute_defaults and self._has_default_attributes
|
98 |
+
|
99 |
+
def __dealloc__(self):
|
100 |
+
xmlschema.xmlSchemaFree(self._c_schema)
|
101 |
+
|
102 |
+
def __call__(self, etree):
|
103 |
+
"""__call__(self, etree)
|
104 |
+
|
105 |
+
Validate doc using XML Schema.
|
106 |
+
|
107 |
+
Returns true if document is valid, false if not.
|
108 |
+
"""
|
109 |
+
cdef xmlschema.xmlSchemaValidCtxt* valid_ctxt
|
110 |
+
cdef _Document doc
|
111 |
+
cdef _Element root_node
|
112 |
+
cdef xmlDoc* c_doc
|
113 |
+
cdef int ret
|
114 |
+
|
115 |
+
assert self._c_schema is not NULL, "Schema instance not initialised"
|
116 |
+
doc = _documentOrRaise(etree)
|
117 |
+
root_node = _rootNodeOrRaise(etree)
|
118 |
+
|
119 |
+
valid_ctxt = xmlschema.xmlSchemaNewValidCtxt(self._c_schema)
|
120 |
+
if valid_ctxt is NULL:
|
121 |
+
raise MemoryError()
|
122 |
+
|
123 |
+
try:
|
124 |
+
if self._add_attribute_defaults:
|
125 |
+
xmlschema.xmlSchemaSetValidOptions(
|
126 |
+
valid_ctxt, xmlschema.XML_SCHEMA_VAL_VC_I_CREATE)
|
127 |
+
|
128 |
+
self._error_log.clear()
|
129 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
130 |
+
xmlschema.xmlSchemaSetValidStructuredErrors(
|
131 |
+
valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
|
132 |
+
|
133 |
+
c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
|
134 |
+
with nogil:
|
135 |
+
ret = xmlschema.xmlSchemaValidateDoc(valid_ctxt, c_doc)
|
136 |
+
_destroyFakeDoc(doc._c_doc, c_doc)
|
137 |
+
finally:
|
138 |
+
xmlschema.xmlSchemaFreeValidCtxt(valid_ctxt)
|
139 |
+
|
140 |
+
if ret == -1:
|
141 |
+
raise XMLSchemaValidateError(
|
142 |
+
"Internal error in XML Schema validation.",
|
143 |
+
self._error_log)
|
144 |
+
if ret == 0:
|
145 |
+
return True
|
146 |
+
else:
|
147 |
+
return False
|
148 |
+
|
149 |
+
cdef _ParserSchemaValidationContext _newSaxValidator(
|
150 |
+
self, bint add_default_attributes):
|
151 |
+
cdef _ParserSchemaValidationContext context
|
152 |
+
context = _ParserSchemaValidationContext.__new__(_ParserSchemaValidationContext)
|
153 |
+
context._schema = self
|
154 |
+
context._add_default_attributes = (self._has_default_attributes and (
|
155 |
+
add_default_attributes or self._add_attribute_defaults))
|
156 |
+
return context
|
157 |
+
|
158 |
+
@cython.final
|
159 |
+
@cython.internal
|
160 |
+
cdef class _ParserSchemaValidationContext:
|
161 |
+
cdef XMLSchema _schema
|
162 |
+
cdef xmlschema.xmlSchemaValidCtxt* _valid_ctxt
|
163 |
+
cdef xmlschema.xmlSchemaSAXPlugStruct* _sax_plug
|
164 |
+
cdef bint _add_default_attributes
|
165 |
+
def __cinit__(self):
|
166 |
+
self._valid_ctxt = NULL
|
167 |
+
self._sax_plug = NULL
|
168 |
+
self._add_default_attributes = False
|
169 |
+
|
170 |
+
def __dealloc__(self):
|
171 |
+
self.disconnect()
|
172 |
+
if self._valid_ctxt:
|
173 |
+
xmlschema.xmlSchemaFreeValidCtxt(self._valid_ctxt)
|
174 |
+
|
175 |
+
cdef _ParserSchemaValidationContext copy(self):
|
176 |
+
assert self._schema is not None, "_ParserSchemaValidationContext not initialised"
|
177 |
+
return self._schema._newSaxValidator(
|
178 |
+
self._add_default_attributes)
|
179 |
+
|
180 |
+
cdef void inject_default_attributes(self, xmlDoc* c_doc) noexcept:
|
181 |
+
# we currently need to insert default attributes manually
|
182 |
+
# after parsing, as libxml2 does not support this at parse
|
183 |
+
# time
|
184 |
+
if self._add_default_attributes:
|
185 |
+
with nogil:
|
186 |
+
xmlschema.xmlSchemaValidateDoc(self._valid_ctxt, c_doc)
|
187 |
+
|
188 |
+
cdef int connect(self, xmlparser.xmlParserCtxt* c_ctxt, _BaseErrorLog error_log) except -1:
|
189 |
+
if self._valid_ctxt is NULL:
|
190 |
+
self._valid_ctxt = xmlschema.xmlSchemaNewValidCtxt(
|
191 |
+
self._schema._c_schema)
|
192 |
+
if self._valid_ctxt is NULL:
|
193 |
+
raise MemoryError()
|
194 |
+
if self._add_default_attributes:
|
195 |
+
xmlschema.xmlSchemaSetValidOptions(
|
196 |
+
self._valid_ctxt, xmlschema.XML_SCHEMA_VAL_VC_I_CREATE)
|
197 |
+
if error_log is not None:
|
198 |
+
# Need a cast here because older libxml2 releases do not use 'const' in the functype.
|
199 |
+
xmlschema.xmlSchemaSetValidStructuredErrors(
|
200 |
+
self._valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>error_log)
|
201 |
+
self._sax_plug = xmlschema.xmlSchemaSAXPlug(
|
202 |
+
self._valid_ctxt, &c_ctxt.sax, &c_ctxt.userData)
|
203 |
+
|
204 |
+
cdef void disconnect(self) noexcept:
|
205 |
+
if self._sax_plug is not NULL:
|
206 |
+
xmlschema.xmlSchemaSAXUnplug(self._sax_plug)
|
207 |
+
self._sax_plug = NULL
|
208 |
+
if self._valid_ctxt is not NULL:
|
209 |
+
xmlschema.xmlSchemaSetValidStructuredErrors(
|
210 |
+
self._valid_ctxt, NULL, NULL)
|
211 |
+
|
212 |
+
cdef bint isvalid(self) noexcept:
|
213 |
+
if self._valid_ctxt is NULL:
|
214 |
+
return 1 # valid
|
215 |
+
return xmlschema.xmlSchemaIsValid(self._valid_ctxt)
|
env-llmeval/lib/python3.10/site-packages/lxml/xpath.pxi
ADDED
@@ -0,0 +1,487 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# XPath evaluation
|
2 |
+
|
3 |
+
class XPathSyntaxError(LxmlSyntaxError, XPathError):
|
4 |
+
pass
|
5 |
+
|
6 |
+
################################################################################
|
7 |
+
# XPath
|
8 |
+
|
9 |
+
cdef object _XPATH_SYNTAX_ERRORS = (
|
10 |
+
xmlerror.XML_XPATH_NUMBER_ERROR,
|
11 |
+
xmlerror.XML_XPATH_UNFINISHED_LITERAL_ERROR,
|
12 |
+
xmlerror.XML_XPATH_VARIABLE_REF_ERROR,
|
13 |
+
xmlerror.XML_XPATH_INVALID_PREDICATE_ERROR,
|
14 |
+
xmlerror.XML_XPATH_UNCLOSED_ERROR,
|
15 |
+
xmlerror.XML_XPATH_INVALID_CHAR_ERROR
|
16 |
+
)
|
17 |
+
|
18 |
+
cdef object _XPATH_EVAL_ERRORS = (
|
19 |
+
xmlerror.XML_XPATH_UNDEF_VARIABLE_ERROR,
|
20 |
+
xmlerror.XML_XPATH_UNDEF_PREFIX_ERROR,
|
21 |
+
xmlerror.XML_XPATH_UNKNOWN_FUNC_ERROR,
|
22 |
+
xmlerror.XML_XPATH_INVALID_OPERAND,
|
23 |
+
xmlerror.XML_XPATH_INVALID_TYPE,
|
24 |
+
xmlerror.XML_XPATH_INVALID_ARITY,
|
25 |
+
xmlerror.XML_XPATH_INVALID_CTXT_SIZE,
|
26 |
+
xmlerror.XML_XPATH_INVALID_CTXT_POSITION
|
27 |
+
)
|
28 |
+
|
29 |
+
cdef int _register_xpath_function(void* ctxt, name_utf, ns_utf) noexcept:
|
30 |
+
if ns_utf is None:
|
31 |
+
return xpath.xmlXPathRegisterFunc(
|
32 |
+
<xpath.xmlXPathContext*>ctxt, _xcstr(name_utf),
|
33 |
+
_xpath_function_call)
|
34 |
+
else:
|
35 |
+
return xpath.xmlXPathRegisterFuncNS(
|
36 |
+
<xpath.xmlXPathContext*>ctxt, _xcstr(name_utf), _xcstr(ns_utf),
|
37 |
+
_xpath_function_call)
|
38 |
+
|
39 |
+
cdef int _unregister_xpath_function(void* ctxt, name_utf, ns_utf) noexcept:
|
40 |
+
if ns_utf is None:
|
41 |
+
return xpath.xmlXPathRegisterFunc(
|
42 |
+
<xpath.xmlXPathContext*>ctxt, _xcstr(name_utf), NULL)
|
43 |
+
else:
|
44 |
+
return xpath.xmlXPathRegisterFuncNS(
|
45 |
+
<xpath.xmlXPathContext*>ctxt, _xcstr(name_utf), _xcstr(ns_utf), NULL)
|
46 |
+
|
47 |
+
|
48 |
+
@cython.final
|
49 |
+
@cython.internal
|
50 |
+
cdef class _XPathContext(_BaseContext):
|
51 |
+
cdef object _variables
|
52 |
+
def __init__(self, namespaces, extensions, error_log, enable_regexp, variables,
|
53 |
+
build_smart_strings):
|
54 |
+
self._variables = variables
|
55 |
+
_BaseContext.__init__(self, namespaces, extensions, error_log, enable_regexp,
|
56 |
+
build_smart_strings)
|
57 |
+
|
58 |
+
cdef set_context(self, xpath.xmlXPathContext* xpathCtxt):
|
59 |
+
self._set_xpath_context(xpathCtxt)
|
60 |
+
# This would be a good place to set up the XPath parser dict, but
|
61 |
+
# we cannot use the current thread dict as we do not know which
|
62 |
+
# thread will execute the XPath evaluator - so, no dict for now.
|
63 |
+
self.registerLocalNamespaces()
|
64 |
+
self.registerLocalFunctions(xpathCtxt, _register_xpath_function)
|
65 |
+
|
66 |
+
cdef register_context(self, _Document doc):
|
67 |
+
self._register_context(doc)
|
68 |
+
self.registerGlobalNamespaces()
|
69 |
+
self.registerGlobalFunctions(self._xpathCtxt, _register_xpath_function)
|
70 |
+
self.registerExsltFunctions()
|
71 |
+
if self._variables is not None:
|
72 |
+
self.registerVariables(self._variables)
|
73 |
+
|
74 |
+
cdef unregister_context(self):
|
75 |
+
self.unregisterGlobalFunctions(
|
76 |
+
self._xpathCtxt, _unregister_xpath_function)
|
77 |
+
self.unregisterGlobalNamespaces()
|
78 |
+
xpath.xmlXPathRegisteredVariablesCleanup(self._xpathCtxt)
|
79 |
+
self._cleanup_context()
|
80 |
+
|
81 |
+
cdef void registerExsltFunctions(self) noexcept:
|
82 |
+
if xslt.LIBXSLT_VERSION < 10125:
|
83 |
+
# we'd only execute dummy functions anyway
|
84 |
+
return
|
85 |
+
tree.xmlHashScan(
|
86 |
+
self._xpathCtxt.nsHash, _registerExsltFunctionsForNamespaces,
|
87 |
+
self._xpathCtxt)
|
88 |
+
|
89 |
+
cdef registerVariables(self, variable_dict):
|
90 |
+
for name, value in variable_dict.items():
|
91 |
+
name_utf = self._to_utf(name)
|
92 |
+
xpath.xmlXPathRegisterVariable(
|
93 |
+
self._xpathCtxt, _xcstr(name_utf), _wrapXPathObject(value, None, None))
|
94 |
+
|
95 |
+
cdef registerVariable(self, name, value):
|
96 |
+
name_utf = self._to_utf(name)
|
97 |
+
xpath.xmlXPathRegisterVariable(
|
98 |
+
self._xpathCtxt, _xcstr(name_utf), _wrapXPathObject(value, None, None))
|
99 |
+
|
100 |
+
|
101 |
+
cdef void _registerExsltFunctionsForNamespaces(
|
102 |
+
void* _c_href, void* _ctxt, const_xmlChar* c_prefix) noexcept:
|
103 |
+
c_href = <const_xmlChar*> _c_href
|
104 |
+
ctxt = <xpath.xmlXPathContext*> _ctxt
|
105 |
+
|
106 |
+
if tree.xmlStrcmp(c_href, xslt.EXSLT_DATE_NAMESPACE) == 0:
|
107 |
+
xslt.exsltDateXpathCtxtRegister(ctxt, c_prefix)
|
108 |
+
elif tree.xmlStrcmp(c_href, xslt.EXSLT_SETS_NAMESPACE) == 0:
|
109 |
+
xslt.exsltSetsXpathCtxtRegister(ctxt, c_prefix)
|
110 |
+
elif tree.xmlStrcmp(c_href, xslt.EXSLT_MATH_NAMESPACE) == 0:
|
111 |
+
xslt.exsltMathXpathCtxtRegister(ctxt, c_prefix)
|
112 |
+
elif tree.xmlStrcmp(c_href, xslt.EXSLT_STRINGS_NAMESPACE) == 0:
|
113 |
+
xslt.exsltStrXpathCtxtRegister(ctxt, c_prefix)
|
114 |
+
|
115 |
+
|
116 |
+
cdef class _XPathEvaluatorBase:
|
117 |
+
cdef xpath.xmlXPathContext* _xpathCtxt
|
118 |
+
cdef _XPathContext _context
|
119 |
+
cdef python.PyThread_type_lock _eval_lock
|
120 |
+
cdef _ErrorLog _error_log
|
121 |
+
def __cinit__(self):
|
122 |
+
self._xpathCtxt = NULL
|
123 |
+
if config.ENABLE_THREADING:
|
124 |
+
self._eval_lock = python.PyThread_allocate_lock()
|
125 |
+
if self._eval_lock is NULL:
|
126 |
+
raise MemoryError()
|
127 |
+
self._error_log = _ErrorLog()
|
128 |
+
|
129 |
+
def __init__(self, namespaces, extensions, enable_regexp,
|
130 |
+
smart_strings):
|
131 |
+
self._context = _XPathContext(namespaces, extensions, self._error_log,
|
132 |
+
enable_regexp, None, smart_strings)
|
133 |
+
|
134 |
+
@property
|
135 |
+
def error_log(self):
|
136 |
+
assert self._error_log is not None, "XPath evaluator not initialised"
|
137 |
+
return self._error_log.copy()
|
138 |
+
|
139 |
+
def __dealloc__(self):
|
140 |
+
if self._xpathCtxt is not NULL:
|
141 |
+
xpath.xmlXPathFreeContext(self._xpathCtxt)
|
142 |
+
if config.ENABLE_THREADING:
|
143 |
+
if self._eval_lock is not NULL:
|
144 |
+
python.PyThread_free_lock(self._eval_lock)
|
145 |
+
|
146 |
+
cdef set_context(self, xpath.xmlXPathContext* xpathCtxt):
|
147 |
+
self._xpathCtxt = xpathCtxt
|
148 |
+
self._context.set_context(xpathCtxt)
|
149 |
+
|
150 |
+
cdef bint _checkAbsolutePath(self, char* path) noexcept:
|
151 |
+
cdef char c
|
152 |
+
if path is NULL:
|
153 |
+
return 0
|
154 |
+
c = path[0]
|
155 |
+
while c == c' ' or c == c'\t':
|
156 |
+
path = path + 1
|
157 |
+
c = path[0]
|
158 |
+
return c == c'/'
|
159 |
+
|
160 |
+
@cython.final
|
161 |
+
cdef int _lock(self) except -1:
|
162 |
+
cdef int result
|
163 |
+
if config.ENABLE_THREADING and self._eval_lock != NULL:
|
164 |
+
with nogil:
|
165 |
+
result = python.PyThread_acquire_lock(
|
166 |
+
self._eval_lock, python.WAIT_LOCK)
|
167 |
+
if result == 0:
|
168 |
+
raise XPathError, "XPath evaluator locking failed"
|
169 |
+
return 0
|
170 |
+
|
171 |
+
@cython.final
|
172 |
+
cdef void _unlock(self) noexcept:
|
173 |
+
if config.ENABLE_THREADING and self._eval_lock != NULL:
|
174 |
+
python.PyThread_release_lock(self._eval_lock)
|
175 |
+
|
176 |
+
cdef _build_parse_error(self):
|
177 |
+
cdef _BaseErrorLog entries
|
178 |
+
entries = self._error_log.filter_types(_XPATH_SYNTAX_ERRORS)
|
179 |
+
if entries:
|
180 |
+
message = entries._buildExceptionMessage(None)
|
181 |
+
if message is not None:
|
182 |
+
return XPathSyntaxError(message, self._error_log)
|
183 |
+
return XPathSyntaxError(
|
184 |
+
self._error_log._buildExceptionMessage("Error in xpath expression"),
|
185 |
+
self._error_log)
|
186 |
+
|
187 |
+
cdef _build_eval_error(self):
|
188 |
+
cdef _BaseErrorLog entries
|
189 |
+
entries = self._error_log.filter_types(_XPATH_EVAL_ERRORS)
|
190 |
+
if not entries:
|
191 |
+
entries = self._error_log.filter_types(_XPATH_SYNTAX_ERRORS)
|
192 |
+
if entries:
|
193 |
+
message = entries._buildExceptionMessage(None)
|
194 |
+
if message is not None:
|
195 |
+
return XPathEvalError(message, self._error_log)
|
196 |
+
return XPathEvalError(
|
197 |
+
self._error_log._buildExceptionMessage("Error in xpath expression"),
|
198 |
+
self._error_log)
|
199 |
+
|
200 |
+
cdef object _handle_result(self, xpath.xmlXPathObject* xpathObj, _Document doc):
|
201 |
+
if self._context._exc._has_raised():
|
202 |
+
if xpathObj is not NULL:
|
203 |
+
_freeXPathObject(xpathObj)
|
204 |
+
xpathObj = NULL
|
205 |
+
self._context._release_temp_refs()
|
206 |
+
self._context._exc._raise_if_stored()
|
207 |
+
|
208 |
+
if xpathObj is NULL:
|
209 |
+
self._context._release_temp_refs()
|
210 |
+
raise self._build_eval_error()
|
211 |
+
|
212 |
+
try:
|
213 |
+
result = _unwrapXPathObject(xpathObj, doc, self._context)
|
214 |
+
finally:
|
215 |
+
_freeXPathObject(xpathObj)
|
216 |
+
self._context._release_temp_refs()
|
217 |
+
|
218 |
+
return result
|
219 |
+
|
220 |
+
|
221 |
+
cdef class XPathElementEvaluator(_XPathEvaluatorBase):
|
222 |
+
"""XPathElementEvaluator(self, element, namespaces=None, extensions=None, regexp=True, smart_strings=True)
|
223 |
+
Create an XPath evaluator for an element.
|
224 |
+
|
225 |
+
Absolute XPath expressions (starting with '/') will be evaluated against
|
226 |
+
the ElementTree as returned by getroottree().
|
227 |
+
|
228 |
+
Additional namespace declarations can be passed with the
|
229 |
+
'namespace' keyword argument. EXSLT regular expression support
|
230 |
+
can be disabled with the 'regexp' boolean keyword (defaults to
|
231 |
+
True). Smart strings will be returned for string results unless
|
232 |
+
you pass ``smart_strings=False``.
|
233 |
+
"""
|
234 |
+
cdef _Element _element
|
235 |
+
def __init__(self, _Element element not None, *, namespaces=None,
|
236 |
+
extensions=None, regexp=True, smart_strings=True):
|
237 |
+
cdef xpath.xmlXPathContext* xpathCtxt
|
238 |
+
cdef int ns_register_status
|
239 |
+
cdef _Document doc
|
240 |
+
_assertValidNode(element)
|
241 |
+
_assertValidDoc(element._doc)
|
242 |
+
self._element = element
|
243 |
+
doc = element._doc
|
244 |
+
_XPathEvaluatorBase.__init__(self, namespaces, extensions,
|
245 |
+
regexp, smart_strings)
|
246 |
+
xpathCtxt = xpath.xmlXPathNewContext(doc._c_doc)
|
247 |
+
if xpathCtxt is NULL:
|
248 |
+
raise MemoryError()
|
249 |
+
self.set_context(xpathCtxt)
|
250 |
+
|
251 |
+
def register_namespace(self, prefix, uri):
|
252 |
+
"""Register a namespace with the XPath context.
|
253 |
+
"""
|
254 |
+
assert self._xpathCtxt is not NULL, "XPath context not initialised"
|
255 |
+
self._context.addNamespace(prefix, uri)
|
256 |
+
|
257 |
+
def register_namespaces(self, namespaces):
|
258 |
+
"""Register a prefix -> uri dict.
|
259 |
+
"""
|
260 |
+
assert self._xpathCtxt is not NULL, "XPath context not initialised"
|
261 |
+
for prefix, uri in namespaces.items():
|
262 |
+
self._context.addNamespace(prefix, uri)
|
263 |
+
|
264 |
+
def __call__(self, _path, **_variables):
|
265 |
+
"""__call__(self, _path, **_variables)
|
266 |
+
|
267 |
+
Evaluate an XPath expression on the document.
|
268 |
+
|
269 |
+
Variables may be provided as keyword arguments. Note that namespaces
|
270 |
+
are currently not supported for variables.
|
271 |
+
|
272 |
+
Absolute XPath expressions (starting with '/') will be evaluated
|
273 |
+
against the ElementTree as returned by getroottree().
|
274 |
+
"""
|
275 |
+
cdef xpath.xmlXPathObject* xpathObj
|
276 |
+
cdef _Document doc
|
277 |
+
assert self._xpathCtxt is not NULL, "XPath context not initialised"
|
278 |
+
path = _utf8(_path)
|
279 |
+
doc = self._element._doc
|
280 |
+
|
281 |
+
self._lock()
|
282 |
+
self._xpathCtxt.node = self._element._c_node
|
283 |
+
try:
|
284 |
+
self._context.register_context(doc)
|
285 |
+
self._context.registerVariables(_variables)
|
286 |
+
c_path = _xcstr(path)
|
287 |
+
with nogil:
|
288 |
+
xpathObj = xpath.xmlXPathEvalExpression(
|
289 |
+
c_path, self._xpathCtxt)
|
290 |
+
result = self._handle_result(xpathObj, doc)
|
291 |
+
finally:
|
292 |
+
self._context.unregister_context()
|
293 |
+
self._unlock()
|
294 |
+
|
295 |
+
return result
|
296 |
+
|
297 |
+
|
298 |
+
cdef class XPathDocumentEvaluator(XPathElementEvaluator):
|
299 |
+
"""XPathDocumentEvaluator(self, etree, namespaces=None, extensions=None, regexp=True, smart_strings=True)
|
300 |
+
Create an XPath evaluator for an ElementTree.
|
301 |
+
|
302 |
+
Additional namespace declarations can be passed with the
|
303 |
+
'namespace' keyword argument. EXSLT regular expression support
|
304 |
+
can be disabled with the 'regexp' boolean keyword (defaults to
|
305 |
+
True). Smart strings will be returned for string results unless
|
306 |
+
you pass ``smart_strings=False``.
|
307 |
+
"""
|
308 |
+
def __init__(self, _ElementTree etree not None, *, namespaces=None,
|
309 |
+
extensions=None, regexp=True, smart_strings=True):
|
310 |
+
XPathElementEvaluator.__init__(
|
311 |
+
self, etree._context_node, namespaces=namespaces,
|
312 |
+
extensions=extensions, regexp=regexp,
|
313 |
+
smart_strings=smart_strings)
|
314 |
+
|
315 |
+
def __call__(self, _path, **_variables):
|
316 |
+
"""__call__(self, _path, **_variables)
|
317 |
+
|
318 |
+
Evaluate an XPath expression on the document.
|
319 |
+
|
320 |
+
Variables may be provided as keyword arguments. Note that namespaces
|
321 |
+
are currently not supported for variables.
|
322 |
+
"""
|
323 |
+
cdef xpath.xmlXPathObject* xpathObj
|
324 |
+
cdef xmlDoc* c_doc
|
325 |
+
cdef _Document doc
|
326 |
+
assert self._xpathCtxt is not NULL, "XPath context not initialised"
|
327 |
+
path = _utf8(_path)
|
328 |
+
doc = self._element._doc
|
329 |
+
|
330 |
+
self._lock()
|
331 |
+
try:
|
332 |
+
self._context.register_context(doc)
|
333 |
+
c_doc = _fakeRootDoc(doc._c_doc, self._element._c_node)
|
334 |
+
try:
|
335 |
+
self._context.registerVariables(_variables)
|
336 |
+
c_path = _xcstr(path)
|
337 |
+
with nogil:
|
338 |
+
self._xpathCtxt.doc = c_doc
|
339 |
+
self._xpathCtxt.node = tree.xmlDocGetRootElement(c_doc)
|
340 |
+
xpathObj = xpath.xmlXPathEvalExpression(
|
341 |
+
c_path, self._xpathCtxt)
|
342 |
+
result = self._handle_result(xpathObj, doc)
|
343 |
+
finally:
|
344 |
+
_destroyFakeDoc(doc._c_doc, c_doc)
|
345 |
+
self._context.unregister_context()
|
346 |
+
finally:
|
347 |
+
self._unlock()
|
348 |
+
|
349 |
+
return result
|
350 |
+
|
351 |
+
|
352 |
+
def XPathEvaluator(etree_or_element, *, namespaces=None, extensions=None,
|
353 |
+
regexp=True, smart_strings=True):
|
354 |
+
"""XPathEvaluator(etree_or_element, namespaces=None, extensions=None, regexp=True, smart_strings=True)
|
355 |
+
|
356 |
+
Creates an XPath evaluator for an ElementTree or an Element.
|
357 |
+
|
358 |
+
The resulting object can be called with an XPath expression as argument
|
359 |
+
and XPath variables provided as keyword arguments.
|
360 |
+
|
361 |
+
Additional namespace declarations can be passed with the
|
362 |
+
'namespace' keyword argument. EXSLT regular expression support
|
363 |
+
can be disabled with the 'regexp' boolean keyword (defaults to
|
364 |
+
True). Smart strings will be returned for string results unless
|
365 |
+
you pass ``smart_strings=False``.
|
366 |
+
"""
|
367 |
+
if isinstance(etree_or_element, _ElementTree):
|
368 |
+
return XPathDocumentEvaluator(
|
369 |
+
etree_or_element, namespaces=namespaces,
|
370 |
+
extensions=extensions, regexp=regexp, smart_strings=smart_strings)
|
371 |
+
else:
|
372 |
+
return XPathElementEvaluator(
|
373 |
+
etree_or_element, namespaces=namespaces,
|
374 |
+
extensions=extensions, regexp=regexp, smart_strings=smart_strings)
|
375 |
+
|
376 |
+
|
377 |
+
cdef class XPath(_XPathEvaluatorBase):
|
378 |
+
"""XPath(self, path, namespaces=None, extensions=None, regexp=True, smart_strings=True)
|
379 |
+
A compiled XPath expression that can be called on Elements and ElementTrees.
|
380 |
+
|
381 |
+
Besides the XPath expression, you can pass prefix-namespace
|
382 |
+
mappings and extension functions to the constructor through the
|
383 |
+
keyword arguments ``namespaces`` and ``extensions``. EXSLT
|
384 |
+
regular expression support can be disabled with the 'regexp'
|
385 |
+
boolean keyword (defaults to True). Smart strings will be
|
386 |
+
returned for string results unless you pass
|
387 |
+
``smart_strings=False``.
|
388 |
+
"""
|
389 |
+
cdef xpath.xmlXPathCompExpr* _xpath
|
390 |
+
cdef bytes _path
|
391 |
+
def __cinit__(self):
|
392 |
+
self._xpath = NULL
|
393 |
+
|
394 |
+
def __init__(self, path, *, namespaces=None, extensions=None,
|
395 |
+
regexp=True, smart_strings=True):
|
396 |
+
cdef xpath.xmlXPathContext* xpathCtxt
|
397 |
+
_XPathEvaluatorBase.__init__(self, namespaces, extensions,
|
398 |
+
regexp, smart_strings)
|
399 |
+
self._path = _utf8(path)
|
400 |
+
xpathCtxt = xpath.xmlXPathNewContext(NULL)
|
401 |
+
if xpathCtxt is NULL:
|
402 |
+
raise MemoryError()
|
403 |
+
self.set_context(xpathCtxt)
|
404 |
+
self._xpath = xpath.xmlXPathCtxtCompile(xpathCtxt, _xcstr(self._path))
|
405 |
+
if self._xpath is NULL:
|
406 |
+
raise self._build_parse_error()
|
407 |
+
|
408 |
+
def __call__(self, _etree_or_element, **_variables):
|
409 |
+
"__call__(self, _etree_or_element, **_variables)"
|
410 |
+
cdef xpath.xmlXPathObject* xpathObj
|
411 |
+
cdef _Document document
|
412 |
+
cdef _Element element
|
413 |
+
|
414 |
+
assert self._xpathCtxt is not NULL, "XPath context not initialised"
|
415 |
+
document = _documentOrRaise(_etree_or_element)
|
416 |
+
element = _rootNodeOrRaise(_etree_or_element)
|
417 |
+
|
418 |
+
self._lock()
|
419 |
+
self._xpathCtxt.doc = document._c_doc
|
420 |
+
self._xpathCtxt.node = element._c_node
|
421 |
+
|
422 |
+
try:
|
423 |
+
self._context.register_context(document)
|
424 |
+
self._context.registerVariables(_variables)
|
425 |
+
with nogil:
|
426 |
+
xpathObj = xpath.xmlXPathCompiledEval(
|
427 |
+
self._xpath, self._xpathCtxt)
|
428 |
+
result = self._handle_result(xpathObj, document)
|
429 |
+
finally:
|
430 |
+
self._context.unregister_context()
|
431 |
+
self._unlock()
|
432 |
+
return result
|
433 |
+
|
434 |
+
@property
|
435 |
+
def path(self):
|
436 |
+
"""The literal XPath expression.
|
437 |
+
"""
|
438 |
+
return self._path.decode('UTF-8')
|
439 |
+
|
440 |
+
def __dealloc__(self):
|
441 |
+
if self._xpath is not NULL:
|
442 |
+
xpath.xmlXPathFreeCompExpr(self._xpath)
|
443 |
+
|
444 |
+
def __repr__(self):
|
445 |
+
return self.path
|
446 |
+
|
447 |
+
|
448 |
+
cdef object _replace_strings = re.compile(b'("[^"]*")|(\'[^\']*\')').sub
|
449 |
+
cdef object _find_namespaces = re.compile(b'({[^}]+})').findall
|
450 |
+
|
451 |
+
cdef class ETXPath(XPath):
|
452 |
+
"""ETXPath(self, path, extensions=None, regexp=True, smart_strings=True)
|
453 |
+
Special XPath class that supports the ElementTree {uri} notation for namespaces.
|
454 |
+
|
455 |
+
Note that this class does not accept the ``namespace`` keyword
|
456 |
+
argument. All namespaces must be passed as part of the path
|
457 |
+
string. Smart strings will be returned for string results unless
|
458 |
+
you pass ``smart_strings=False``.
|
459 |
+
"""
|
460 |
+
def __init__(self, path, *, extensions=None, regexp=True,
|
461 |
+
smart_strings=True):
|
462 |
+
path, namespaces = self._nsextract_path(path)
|
463 |
+
XPath.__init__(self, path, namespaces=namespaces,
|
464 |
+
extensions=extensions, regexp=regexp,
|
465 |
+
smart_strings=smart_strings)
|
466 |
+
|
467 |
+
cdef _nsextract_path(self, path):
|
468 |
+
# replace {namespaces} by new prefixes
|
469 |
+
cdef dict namespaces = {}
|
470 |
+
cdef list namespace_defs = []
|
471 |
+
cdef int i
|
472 |
+
path_utf = _utf8(path)
|
473 |
+
stripped_path = _replace_strings(b'', path_utf) # remove string literals
|
474 |
+
i = 1
|
475 |
+
for namespace_def in _find_namespaces(stripped_path):
|
476 |
+
if namespace_def not in namespace_defs:
|
477 |
+
prefix = python.PyBytes_FromFormat("__xpp%02d", i)
|
478 |
+
i += 1
|
479 |
+
namespace_defs.append(namespace_def)
|
480 |
+
namespace = namespace_def[1:-1] # remove '{}'
|
481 |
+
namespace = (<bytes>namespace).decode('utf8')
|
482 |
+
namespaces[prefix.decode('utf8')] = namespace
|
483 |
+
prefix_str = prefix + b':'
|
484 |
+
# FIXME: this also replaces {namespaces} within strings!
|
485 |
+
path_utf = path_utf.replace(namespace_def, prefix_str)
|
486 |
+
path = path_utf.decode('utf8')
|
487 |
+
return path, namespaces
|
env-llmeval/lib/python3.10/site-packages/lxml/xslt.pxi
ADDED
@@ -0,0 +1,950 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# XSLT
|
2 |
+
from lxml.includes cimport xslt
|
3 |
+
|
4 |
+
|
5 |
+
cdef class XSLTError(LxmlError):
|
6 |
+
"""Base class of all XSLT errors.
|
7 |
+
"""
|
8 |
+
|
9 |
+
cdef class XSLTParseError(XSLTError):
|
10 |
+
"""Error parsing a stylesheet document.
|
11 |
+
"""
|
12 |
+
|
13 |
+
cdef class XSLTApplyError(XSLTError):
|
14 |
+
"""Error running an XSL transformation.
|
15 |
+
"""
|
16 |
+
|
17 |
+
class XSLTSaveError(XSLTError, SerialisationError):
|
18 |
+
"""Error serialising an XSLT result.
|
19 |
+
"""
|
20 |
+
|
21 |
+
cdef class XSLTExtensionError(XSLTError):
|
22 |
+
"""Error registering an XSLT extension.
|
23 |
+
"""
|
24 |
+
|
25 |
+
|
26 |
+
# version information
|
27 |
+
LIBXSLT_COMPILED_VERSION = __unpackIntVersion(xslt.LIBXSLT_VERSION)
|
28 |
+
LIBXSLT_VERSION = __unpackIntVersion(xslt.xsltLibxsltVersion)
|
29 |
+
|
30 |
+
|
31 |
+
################################################################################
|
32 |
+
# Where do we store what?
|
33 |
+
#
|
34 |
+
# xsltStylesheet->doc->_private
|
35 |
+
# == _XSLTResolverContext for XSL stylesheet
|
36 |
+
#
|
37 |
+
# xsltTransformContext->_private
|
38 |
+
# == _XSLTResolverContext for transformed document
|
39 |
+
#
|
40 |
+
################################################################################
|
41 |
+
|
42 |
+
|
43 |
+
################################################################################
|
44 |
+
# XSLT document loaders
|
45 |
+
|
46 |
+
@cython.final
|
47 |
+
@cython.internal
|
48 |
+
cdef class _XSLTResolverContext(_ResolverContext):
|
49 |
+
cdef xmlDoc* _c_style_doc
|
50 |
+
cdef _BaseParser _parser
|
51 |
+
|
52 |
+
cdef _XSLTResolverContext _copy(self):
|
53 |
+
cdef _XSLTResolverContext context
|
54 |
+
context = _XSLTResolverContext()
|
55 |
+
_initXSLTResolverContext(context, self._parser)
|
56 |
+
context._c_style_doc = self._c_style_doc
|
57 |
+
return context
|
58 |
+
|
59 |
+
cdef _initXSLTResolverContext(_XSLTResolverContext context,
|
60 |
+
_BaseParser parser):
|
61 |
+
_initResolverContext(context, parser.resolvers)
|
62 |
+
context._parser = parser
|
63 |
+
context._c_style_doc = NULL
|
64 |
+
|
65 |
+
cdef xmlDoc* _xslt_resolve_from_python(const_xmlChar* c_uri, void* c_context,
|
66 |
+
int parse_options, int* error) with gil:
|
67 |
+
# call the Python document loaders
|
68 |
+
cdef _XSLTResolverContext context
|
69 |
+
cdef _ResolverRegistry resolvers
|
70 |
+
cdef _InputDocument doc_ref
|
71 |
+
cdef xmlDoc* c_doc
|
72 |
+
cdef xmlDoc* c_return_doc = NULL
|
73 |
+
|
74 |
+
error[0] = 0
|
75 |
+
context = <_XSLTResolverContext>c_context
|
76 |
+
|
77 |
+
# shortcut if we resolve the stylesheet itself
|
78 |
+
c_doc = context._c_style_doc
|
79 |
+
try:
|
80 |
+
if c_doc is not NULL and c_doc.URL is not NULL:
|
81 |
+
if tree.xmlStrcmp(c_uri, c_doc.URL) == 0:
|
82 |
+
c_return_doc = _copyDoc(c_doc, 1)
|
83 |
+
return c_return_doc # 'goto', see 'finally' below
|
84 |
+
|
85 |
+
# delegate to the Python resolvers
|
86 |
+
resolvers = context._resolvers
|
87 |
+
if tree.xmlStrncmp(<unsigned char*>'string://__STRING__XSLT__/', c_uri, 26) == 0:
|
88 |
+
c_uri += 26
|
89 |
+
uri = _decodeFilename(c_uri)
|
90 |
+
doc_ref = resolvers.resolve(uri, None, context)
|
91 |
+
|
92 |
+
if doc_ref is not None:
|
93 |
+
if doc_ref._type == PARSER_DATA_STRING:
|
94 |
+
c_return_doc = _parseDoc(
|
95 |
+
doc_ref._data_bytes, doc_ref._filename, context._parser)
|
96 |
+
elif doc_ref._type == PARSER_DATA_FILENAME:
|
97 |
+
c_return_doc = _parseDocFromFile(
|
98 |
+
doc_ref._filename, context._parser)
|
99 |
+
elif doc_ref._type == PARSER_DATA_FILE:
|
100 |
+
c_return_doc = _parseDocFromFilelike(
|
101 |
+
doc_ref._file, doc_ref._filename, context._parser)
|
102 |
+
elif doc_ref._type == PARSER_DATA_EMPTY:
|
103 |
+
c_return_doc = _newXMLDoc()
|
104 |
+
if c_return_doc is not NULL and c_return_doc.URL is NULL:
|
105 |
+
c_return_doc.URL = tree.xmlStrdup(c_uri)
|
106 |
+
except:
|
107 |
+
error[0] = 1
|
108 |
+
context._store_raised()
|
109 |
+
finally:
|
110 |
+
return c_return_doc # and swallow any further exceptions
|
111 |
+
|
112 |
+
|
113 |
+
cdef void _xslt_store_resolver_exception(const_xmlChar* c_uri, void* context,
|
114 |
+
xslt.xsltLoadType c_type) noexcept with gil:
|
115 |
+
try:
|
116 |
+
message = f"Cannot resolve URI {_decodeFilename(c_uri)}"
|
117 |
+
if c_type == xslt.XSLT_LOAD_DOCUMENT:
|
118 |
+
exception = XSLTApplyError(message)
|
119 |
+
else:
|
120 |
+
exception = XSLTParseError(message)
|
121 |
+
(<_XSLTResolverContext>context)._store_exception(exception)
|
122 |
+
except BaseException as e:
|
123 |
+
(<_XSLTResolverContext>context)._store_exception(e)
|
124 |
+
finally:
|
125 |
+
return # and swallow any further exceptions
|
126 |
+
|
127 |
+
|
128 |
+
cdef xmlDoc* _xslt_doc_loader(const_xmlChar* c_uri, tree.xmlDict* c_dict,
|
129 |
+
int parse_options, void* c_ctxt,
|
130 |
+
xslt.xsltLoadType c_type) noexcept nogil:
|
131 |
+
# nogil => no Python objects here, may be called without thread context !
|
132 |
+
cdef xmlDoc* c_doc
|
133 |
+
cdef xmlDoc* result
|
134 |
+
cdef void* c_pcontext
|
135 |
+
cdef int error = 0
|
136 |
+
# find resolver contexts of stylesheet and transformed doc
|
137 |
+
if c_type == xslt.XSLT_LOAD_DOCUMENT:
|
138 |
+
# transformation time
|
139 |
+
c_pcontext = (<xslt.xsltTransformContext*>c_ctxt)._private
|
140 |
+
elif c_type == xslt.XSLT_LOAD_STYLESHEET:
|
141 |
+
# include/import resolution while parsing
|
142 |
+
c_pcontext = (<xslt.xsltStylesheet*>c_ctxt).doc._private
|
143 |
+
else:
|
144 |
+
c_pcontext = NULL
|
145 |
+
|
146 |
+
if c_pcontext is NULL:
|
147 |
+
# can't call Python without context, fall back to default loader
|
148 |
+
return XSLT_DOC_DEFAULT_LOADER(
|
149 |
+
c_uri, c_dict, parse_options, c_ctxt, c_type)
|
150 |
+
|
151 |
+
c_doc = _xslt_resolve_from_python(c_uri, c_pcontext, parse_options, &error)
|
152 |
+
if c_doc is NULL and not error:
|
153 |
+
c_doc = XSLT_DOC_DEFAULT_LOADER(
|
154 |
+
c_uri, c_dict, parse_options, c_ctxt, c_type)
|
155 |
+
if c_doc is NULL:
|
156 |
+
_xslt_store_resolver_exception(c_uri, c_pcontext, c_type)
|
157 |
+
|
158 |
+
if c_doc is not NULL and c_type == xslt.XSLT_LOAD_STYLESHEET:
|
159 |
+
c_doc._private = c_pcontext
|
160 |
+
return c_doc
|
161 |
+
|
162 |
+
cdef xslt.xsltDocLoaderFunc XSLT_DOC_DEFAULT_LOADER = xslt.xsltDocDefaultLoader
|
163 |
+
xslt.xsltSetLoaderFunc(<xslt.xsltDocLoaderFunc>_xslt_doc_loader)
|
164 |
+
|
165 |
+
################################################################################
|
166 |
+
# XSLT file/network access control
|
167 |
+
|
168 |
+
cdef class XSLTAccessControl:
|
169 |
+
"""XSLTAccessControl(self, read_file=True, write_file=True, create_dir=True, read_network=True, write_network=True)
|
170 |
+
|
171 |
+
Access control for XSLT: reading/writing files, directories and
|
172 |
+
network I/O. Access to a type of resource is granted or denied by
|
173 |
+
passing any of the following boolean keyword arguments. All of
|
174 |
+
them default to True to allow access.
|
175 |
+
|
176 |
+
- read_file
|
177 |
+
- write_file
|
178 |
+
- create_dir
|
179 |
+
- read_network
|
180 |
+
- write_network
|
181 |
+
|
182 |
+
For convenience, there is also a class member `DENY_ALL` that
|
183 |
+
provides an XSLTAccessControl instance that is readily configured
|
184 |
+
to deny everything, and a `DENY_WRITE` member that denies all
|
185 |
+
write access but allows read access.
|
186 |
+
|
187 |
+
See `XSLT`.
|
188 |
+
"""
|
189 |
+
cdef xslt.xsltSecurityPrefs* _prefs
|
190 |
+
def __cinit__(self):
|
191 |
+
self._prefs = xslt.xsltNewSecurityPrefs()
|
192 |
+
if self._prefs is NULL:
|
193 |
+
raise MemoryError()
|
194 |
+
|
195 |
+
def __init__(self, *, bint read_file=True, bint write_file=True, bint create_dir=True,
|
196 |
+
bint read_network=True, bint write_network=True):
|
197 |
+
self._setAccess(xslt.XSLT_SECPREF_READ_FILE, read_file)
|
198 |
+
self._setAccess(xslt.XSLT_SECPREF_WRITE_FILE, write_file)
|
199 |
+
self._setAccess(xslt.XSLT_SECPREF_CREATE_DIRECTORY, create_dir)
|
200 |
+
self._setAccess(xslt.XSLT_SECPREF_READ_NETWORK, read_network)
|
201 |
+
self._setAccess(xslt.XSLT_SECPREF_WRITE_NETWORK, write_network)
|
202 |
+
|
203 |
+
DENY_ALL = XSLTAccessControl(
|
204 |
+
read_file=False, write_file=False, create_dir=False,
|
205 |
+
read_network=False, write_network=False)
|
206 |
+
|
207 |
+
DENY_WRITE = XSLTAccessControl(
|
208 |
+
read_file=True, write_file=False, create_dir=False,
|
209 |
+
read_network=True, write_network=False)
|
210 |
+
|
211 |
+
def __dealloc__(self):
|
212 |
+
if self._prefs is not NULL:
|
213 |
+
xslt.xsltFreeSecurityPrefs(self._prefs)
|
214 |
+
|
215 |
+
@cython.final
|
216 |
+
cdef _setAccess(self, xslt.xsltSecurityOption option, bint allow):
|
217 |
+
cdef xslt.xsltSecurityCheck function
|
218 |
+
if allow:
|
219 |
+
function = xslt.xsltSecurityAllow
|
220 |
+
else:
|
221 |
+
function = xslt.xsltSecurityForbid
|
222 |
+
xslt.xsltSetSecurityPrefs(self._prefs, option, function)
|
223 |
+
|
224 |
+
@cython.final
|
225 |
+
cdef void _register_in_context(self, xslt.xsltTransformContext* ctxt) noexcept:
|
226 |
+
xslt.xsltSetCtxtSecurityPrefs(self._prefs, ctxt)
|
227 |
+
|
228 |
+
@property
|
229 |
+
def options(self):
|
230 |
+
"""The access control configuration as a map of options."""
|
231 |
+
return {
|
232 |
+
'read_file': self._optval(xslt.XSLT_SECPREF_READ_FILE),
|
233 |
+
'write_file': self._optval(xslt.XSLT_SECPREF_WRITE_FILE),
|
234 |
+
'create_dir': self._optval(xslt.XSLT_SECPREF_CREATE_DIRECTORY),
|
235 |
+
'read_network': self._optval(xslt.XSLT_SECPREF_READ_NETWORK),
|
236 |
+
'write_network': self._optval(xslt.XSLT_SECPREF_WRITE_NETWORK),
|
237 |
+
}
|
238 |
+
|
239 |
+
@cython.final
|
240 |
+
cdef _optval(self, xslt.xsltSecurityOption option):
|
241 |
+
cdef xslt.xsltSecurityCheck function
|
242 |
+
function = xslt.xsltGetSecurityPrefs(self._prefs, option)
|
243 |
+
if function is <xslt.xsltSecurityCheck>xslt.xsltSecurityAllow:
|
244 |
+
return True
|
245 |
+
elif function is <xslt.xsltSecurityCheck>xslt.xsltSecurityForbid:
|
246 |
+
return False
|
247 |
+
else:
|
248 |
+
return None
|
249 |
+
|
250 |
+
def __repr__(self):
|
251 |
+
items = sorted(self.options.items())
|
252 |
+
return "%s(%s)" % (
|
253 |
+
python._fqtypename(self).decode('UTF-8').split('.')[-1],
|
254 |
+
', '.join(["%s=%r" % item for item in items]))
|
255 |
+
|
256 |
+
################################################################################
|
257 |
+
# XSLT
|
258 |
+
|
259 |
+
cdef int _register_xslt_function(void* ctxt, name_utf, ns_utf) noexcept:
|
260 |
+
if ns_utf is None:
|
261 |
+
return 0
|
262 |
+
# libxml2 internalises the strings if ctxt has a dict
|
263 |
+
return xslt.xsltRegisterExtFunction(
|
264 |
+
<xslt.xsltTransformContext*>ctxt, _xcstr(name_utf), _xcstr(ns_utf),
|
265 |
+
<xslt.xmlXPathFunction>_xpath_function_call)
|
266 |
+
|
267 |
+
cdef dict EMPTY_DICT = {}
|
268 |
+
|
269 |
+
@cython.final
|
270 |
+
@cython.internal
|
271 |
+
cdef class _XSLTContext(_BaseContext):
|
272 |
+
cdef xslt.xsltTransformContext* _xsltCtxt
|
273 |
+
cdef _ReadOnlyElementProxy _extension_element_proxy
|
274 |
+
cdef dict _extension_elements
|
275 |
+
def __cinit__(self):
|
276 |
+
self._xsltCtxt = NULL
|
277 |
+
self._extension_elements = EMPTY_DICT
|
278 |
+
|
279 |
+
def __init__(self, namespaces, extensions, error_log, enable_regexp,
|
280 |
+
build_smart_strings):
|
281 |
+
if extensions is not None and extensions:
|
282 |
+
for ns_name_tuple, extension in extensions.items():
|
283 |
+
if ns_name_tuple[0] is None:
|
284 |
+
raise XSLTExtensionError, \
|
285 |
+
"extensions must not have empty namespaces"
|
286 |
+
if isinstance(extension, XSLTExtension):
|
287 |
+
if self._extension_elements is EMPTY_DICT:
|
288 |
+
self._extension_elements = {}
|
289 |
+
extensions = extensions.copy()
|
290 |
+
ns_utf = _utf8(ns_name_tuple[0])
|
291 |
+
name_utf = _utf8(ns_name_tuple[1])
|
292 |
+
self._extension_elements[(ns_utf, name_utf)] = extension
|
293 |
+
del extensions[ns_name_tuple]
|
294 |
+
_BaseContext.__init__(self, namespaces, extensions, error_log, enable_regexp,
|
295 |
+
build_smart_strings)
|
296 |
+
|
297 |
+
cdef _BaseContext _copy(self):
|
298 |
+
cdef _XSLTContext context
|
299 |
+
context = <_XSLTContext>_BaseContext._copy(self)
|
300 |
+
context._extension_elements = self._extension_elements
|
301 |
+
return context
|
302 |
+
|
303 |
+
cdef register_context(self, xslt.xsltTransformContext* xsltCtxt,
|
304 |
+
_Document doc):
|
305 |
+
self._xsltCtxt = xsltCtxt
|
306 |
+
self._set_xpath_context(xsltCtxt.xpathCtxt)
|
307 |
+
self._register_context(doc)
|
308 |
+
self.registerLocalFunctions(xsltCtxt, _register_xslt_function)
|
309 |
+
self.registerGlobalFunctions(xsltCtxt, _register_xslt_function)
|
310 |
+
_registerXSLTExtensions(xsltCtxt, self._extension_elements)
|
311 |
+
|
312 |
+
cdef free_context(self):
|
313 |
+
self._cleanup_context()
|
314 |
+
self._release_context()
|
315 |
+
if self._xsltCtxt is not NULL:
|
316 |
+
xslt.xsltFreeTransformContext(self._xsltCtxt)
|
317 |
+
self._xsltCtxt = NULL
|
318 |
+
self._release_temp_refs()
|
319 |
+
|
320 |
+
|
321 |
+
@cython.final
|
322 |
+
@cython.internal
|
323 |
+
@cython.freelist(8)
|
324 |
+
cdef class _XSLTQuotedStringParam:
|
325 |
+
"""A wrapper class for literal XSLT string parameters that require
|
326 |
+
quote escaping.
|
327 |
+
"""
|
328 |
+
cdef bytes strval
|
329 |
+
def __cinit__(self, strval):
|
330 |
+
self.strval = _utf8(strval)
|
331 |
+
|
332 |
+
|
333 |
+
@cython.no_gc_clear
|
334 |
+
cdef class XSLT:
|
335 |
+
"""XSLT(self, xslt_input, extensions=None, regexp=True, access_control=None)
|
336 |
+
|
337 |
+
Turn an XSL document into an XSLT object.
|
338 |
+
|
339 |
+
Calling this object on a tree or Element will execute the XSLT::
|
340 |
+
|
341 |
+
transform = etree.XSLT(xsl_tree)
|
342 |
+
result = transform(xml_tree)
|
343 |
+
|
344 |
+
Keyword arguments of the constructor:
|
345 |
+
|
346 |
+
- extensions: a dict mapping ``(namespace, name)`` pairs to
|
347 |
+
extension functions or extension elements
|
348 |
+
- regexp: enable exslt regular expression support in XPath
|
349 |
+
(default: True)
|
350 |
+
- access_control: access restrictions for network or file
|
351 |
+
system (see `XSLTAccessControl`)
|
352 |
+
|
353 |
+
Keyword arguments of the XSLT call:
|
354 |
+
|
355 |
+
- profile_run: enable XSLT profiling and make the profile available
|
356 |
+
as XML document in ``result.xslt_profile`` (default: False)
|
357 |
+
|
358 |
+
Other keyword arguments of the call are passed to the stylesheet
|
359 |
+
as parameters.
|
360 |
+
"""
|
361 |
+
cdef _XSLTContext _context
|
362 |
+
cdef xslt.xsltStylesheet* _c_style
|
363 |
+
cdef _XSLTResolverContext _xslt_resolver_context
|
364 |
+
cdef XSLTAccessControl _access_control
|
365 |
+
cdef _ErrorLog _error_log
|
366 |
+
|
367 |
+
def __cinit__(self):
|
368 |
+
self._c_style = NULL
|
369 |
+
|
370 |
+
def __init__(self, xslt_input, *, extensions=None, regexp=True,
|
371 |
+
access_control=None):
|
372 |
+
cdef xslt.xsltStylesheet* c_style = NULL
|
373 |
+
cdef xmlDoc* c_doc
|
374 |
+
cdef _Document doc
|
375 |
+
cdef _Element root_node
|
376 |
+
|
377 |
+
doc = _documentOrRaise(xslt_input)
|
378 |
+
root_node = _rootNodeOrRaise(xslt_input)
|
379 |
+
|
380 |
+
# set access control or raise TypeError
|
381 |
+
self._access_control = access_control
|
382 |
+
|
383 |
+
# make a copy of the document as stylesheet parsing modifies it
|
384 |
+
c_doc = _copyDocRoot(doc._c_doc, root_node._c_node)
|
385 |
+
|
386 |
+
# make sure we always have a stylesheet URL
|
387 |
+
if c_doc.URL is NULL:
|
388 |
+
doc_url_utf = python.PyUnicode_AsASCIIString(
|
389 |
+
f"string://__STRING__XSLT__/{id(self)}.xslt")
|
390 |
+
c_doc.URL = tree.xmlStrdup(_xcstr(doc_url_utf))
|
391 |
+
|
392 |
+
self._error_log = _ErrorLog()
|
393 |
+
self._xslt_resolver_context = _XSLTResolverContext()
|
394 |
+
_initXSLTResolverContext(self._xslt_resolver_context, doc._parser)
|
395 |
+
# keep a copy in case we need to access the stylesheet via 'document()'
|
396 |
+
self._xslt_resolver_context._c_style_doc = _copyDoc(c_doc, 1)
|
397 |
+
c_doc._private = <python.PyObject*>self._xslt_resolver_context
|
398 |
+
|
399 |
+
with self._error_log:
|
400 |
+
orig_loader = _register_document_loader()
|
401 |
+
c_style = xslt.xsltParseStylesheetDoc(c_doc)
|
402 |
+
_reset_document_loader(orig_loader)
|
403 |
+
|
404 |
+
if c_style is NULL or c_style.errors:
|
405 |
+
tree.xmlFreeDoc(c_doc)
|
406 |
+
if c_style is not NULL:
|
407 |
+
xslt.xsltFreeStylesheet(c_style)
|
408 |
+
self._xslt_resolver_context._raise_if_stored()
|
409 |
+
# last error seems to be the most accurate here
|
410 |
+
if self._error_log.last_error is not None and \
|
411 |
+
self._error_log.last_error.message:
|
412 |
+
raise XSLTParseError(self._error_log.last_error.message,
|
413 |
+
self._error_log)
|
414 |
+
else:
|
415 |
+
raise XSLTParseError(
|
416 |
+
self._error_log._buildExceptionMessage(
|
417 |
+
"Cannot parse stylesheet"),
|
418 |
+
self._error_log)
|
419 |
+
|
420 |
+
c_doc._private = NULL # no longer used!
|
421 |
+
self._c_style = c_style
|
422 |
+
self._context = _XSLTContext(None, extensions, self._error_log, regexp, True)
|
423 |
+
|
424 |
+
def __dealloc__(self):
|
425 |
+
if self._xslt_resolver_context is not None and \
|
426 |
+
self._xslt_resolver_context._c_style_doc is not NULL:
|
427 |
+
tree.xmlFreeDoc(self._xslt_resolver_context._c_style_doc)
|
428 |
+
# this cleans up the doc copy as well
|
429 |
+
if self._c_style is not NULL:
|
430 |
+
xslt.xsltFreeStylesheet(self._c_style)
|
431 |
+
|
432 |
+
@property
|
433 |
+
def error_log(self):
|
434 |
+
"""The log of errors and warnings of an XSLT execution."""
|
435 |
+
return self._error_log.copy()
|
436 |
+
|
437 |
+
@staticmethod
|
438 |
+
def strparam(strval):
|
439 |
+
"""strparam(strval)
|
440 |
+
|
441 |
+
Mark an XSLT string parameter that requires quote escaping
|
442 |
+
before passing it into the transformation. Use it like this::
|
443 |
+
|
444 |
+
result = transform(doc, some_strval = XSLT.strparam(
|
445 |
+
'''it's \"Monty Python's\" ...'''))
|
446 |
+
|
447 |
+
Escaped string parameters can be reused without restriction.
|
448 |
+
"""
|
449 |
+
return _XSLTQuotedStringParam(strval)
|
450 |
+
|
451 |
+
@staticmethod
|
452 |
+
def set_global_max_depth(int max_depth):
|
453 |
+
"""set_global_max_depth(max_depth)
|
454 |
+
|
455 |
+
The maximum traversal depth that the stylesheet engine will allow.
|
456 |
+
This does not only count the template recursion depth but also takes
|
457 |
+
the number of variables/parameters into account. The required setting
|
458 |
+
for a run depends on both the stylesheet and the input data.
|
459 |
+
|
460 |
+
Example::
|
461 |
+
|
462 |
+
XSLT.set_global_max_depth(5000)
|
463 |
+
|
464 |
+
Note that this is currently a global, module-wide setting because
|
465 |
+
libxslt does not support it at a per-stylesheet level.
|
466 |
+
"""
|
467 |
+
if max_depth < 0:
|
468 |
+
raise ValueError("cannot set a maximum stylesheet traversal depth < 0")
|
469 |
+
xslt.xsltMaxDepth = max_depth
|
470 |
+
|
471 |
+
def tostring(self, _ElementTree result_tree):
|
472 |
+
"""tostring(self, result_tree)
|
473 |
+
|
474 |
+
Save result doc to string based on stylesheet output method.
|
475 |
+
|
476 |
+
:deprecated: use str(result_tree) instead.
|
477 |
+
"""
|
478 |
+
return str(result_tree)
|
479 |
+
|
480 |
+
def __deepcopy__(self, memo):
|
481 |
+
return self.__copy__()
|
482 |
+
|
483 |
+
def __copy__(self):
|
484 |
+
return _copyXSLT(self)
|
485 |
+
|
486 |
+
def __call__(self, _input, *, profile_run=False, **kw):
|
487 |
+
"""__call__(self, _input, profile_run=False, **kw)
|
488 |
+
|
489 |
+
Execute the XSL transformation on a tree or Element.
|
490 |
+
|
491 |
+
Pass the ``profile_run`` option to get profile information
|
492 |
+
about the XSLT. The result of the XSLT will have a property
|
493 |
+
xslt_profile that holds an XML tree with profiling data.
|
494 |
+
"""
|
495 |
+
cdef _XSLTContext context = None
|
496 |
+
cdef _XSLTResolverContext resolver_context
|
497 |
+
cdef _Document input_doc
|
498 |
+
cdef _Element root_node
|
499 |
+
cdef _Document result_doc
|
500 |
+
cdef _Document profile_doc = None
|
501 |
+
cdef xmlDoc* c_profile_doc
|
502 |
+
cdef xslt.xsltTransformContext* transform_ctxt
|
503 |
+
cdef xmlDoc* c_result = NULL
|
504 |
+
cdef xmlDoc* c_doc
|
505 |
+
cdef tree.xmlDict* c_dict
|
506 |
+
cdef const_char** params = NULL
|
507 |
+
|
508 |
+
assert self._c_style is not NULL, "XSLT stylesheet not initialised"
|
509 |
+
input_doc = _documentOrRaise(_input)
|
510 |
+
root_node = _rootNodeOrRaise(_input)
|
511 |
+
|
512 |
+
c_doc = _fakeRootDoc(input_doc._c_doc, root_node._c_node)
|
513 |
+
|
514 |
+
transform_ctxt = xslt.xsltNewTransformContext(self._c_style, c_doc)
|
515 |
+
if transform_ctxt is NULL:
|
516 |
+
_destroyFakeDoc(input_doc._c_doc, c_doc)
|
517 |
+
raise MemoryError()
|
518 |
+
|
519 |
+
# using the stylesheet dict is safer than using a possibly
|
520 |
+
# unrelated dict from the current thread. Almost all
|
521 |
+
# non-input tag/attr names will come from the stylesheet
|
522 |
+
# anyway.
|
523 |
+
if transform_ctxt.dict is not NULL:
|
524 |
+
xmlparser.xmlDictFree(transform_ctxt.dict)
|
525 |
+
if kw:
|
526 |
+
# parameter values are stored in the dict
|
527 |
+
# => avoid unnecessarily cluttering the global dict
|
528 |
+
transform_ctxt.dict = xmlparser.xmlDictCreateSub(self._c_style.doc.dict)
|
529 |
+
if transform_ctxt.dict is NULL:
|
530 |
+
xslt.xsltFreeTransformContext(transform_ctxt)
|
531 |
+
raise MemoryError()
|
532 |
+
else:
|
533 |
+
transform_ctxt.dict = self._c_style.doc.dict
|
534 |
+
xmlparser.xmlDictReference(transform_ctxt.dict)
|
535 |
+
|
536 |
+
xslt.xsltSetCtxtParseOptions(
|
537 |
+
transform_ctxt, input_doc._parser._parse_options)
|
538 |
+
|
539 |
+
if profile_run:
|
540 |
+
transform_ctxt.profile = 1
|
541 |
+
|
542 |
+
try:
|
543 |
+
context = self._context._copy()
|
544 |
+
context.register_context(transform_ctxt, input_doc)
|
545 |
+
|
546 |
+
resolver_context = self._xslt_resolver_context._copy()
|
547 |
+
transform_ctxt._private = <python.PyObject*>resolver_context
|
548 |
+
|
549 |
+
_convert_xslt_parameters(transform_ctxt, kw, ¶ms)
|
550 |
+
c_result = self._run_transform(
|
551 |
+
c_doc, params, context, transform_ctxt)
|
552 |
+
if params is not NULL:
|
553 |
+
# deallocate space for parameters
|
554 |
+
python.lxml_free(params)
|
555 |
+
|
556 |
+
if transform_ctxt.state != xslt.XSLT_STATE_OK:
|
557 |
+
if c_result is not NULL:
|
558 |
+
tree.xmlFreeDoc(c_result)
|
559 |
+
c_result = NULL
|
560 |
+
|
561 |
+
if transform_ctxt.profile:
|
562 |
+
c_profile_doc = xslt.xsltGetProfileInformation(transform_ctxt)
|
563 |
+
if c_profile_doc is not NULL:
|
564 |
+
profile_doc = _documentFactory(
|
565 |
+
c_profile_doc, input_doc._parser)
|
566 |
+
finally:
|
567 |
+
if context is not None:
|
568 |
+
context.free_context()
|
569 |
+
_destroyFakeDoc(input_doc._c_doc, c_doc)
|
570 |
+
|
571 |
+
try:
|
572 |
+
if resolver_context is not None and resolver_context._has_raised():
|
573 |
+
if c_result is not NULL:
|
574 |
+
tree.xmlFreeDoc(c_result)
|
575 |
+
c_result = NULL
|
576 |
+
resolver_context._raise_if_stored()
|
577 |
+
|
578 |
+
if context._exc._has_raised():
|
579 |
+
if c_result is not NULL:
|
580 |
+
tree.xmlFreeDoc(c_result)
|
581 |
+
c_result = NULL
|
582 |
+
context._exc._raise_if_stored()
|
583 |
+
|
584 |
+
if c_result is NULL:
|
585 |
+
# last error seems to be the most accurate here
|
586 |
+
error = self._error_log.last_error
|
587 |
+
if error is not None and error.message:
|
588 |
+
if error.line > 0:
|
589 |
+
message = f"{error.message}, line {error.line}"
|
590 |
+
else:
|
591 |
+
message = error.message
|
592 |
+
elif error is not None and error.line > 0:
|
593 |
+
message = f"Error applying stylesheet, line {error.line}"
|
594 |
+
else:
|
595 |
+
message = "Error applying stylesheet"
|
596 |
+
raise XSLTApplyError(message, self._error_log)
|
597 |
+
finally:
|
598 |
+
if resolver_context is not None:
|
599 |
+
resolver_context.clear()
|
600 |
+
|
601 |
+
result_doc = _documentFactory(c_result, input_doc._parser)
|
602 |
+
|
603 |
+
c_dict = c_result.dict
|
604 |
+
xmlparser.xmlDictReference(c_dict)
|
605 |
+
__GLOBAL_PARSER_CONTEXT.initThreadDictRef(&c_result.dict)
|
606 |
+
if c_dict is not c_result.dict or \
|
607 |
+
self._c_style.doc.dict is not c_result.dict or \
|
608 |
+
input_doc._c_doc.dict is not c_result.dict:
|
609 |
+
with nogil:
|
610 |
+
if c_dict is not c_result.dict:
|
611 |
+
fixThreadDictNames(<xmlNode*>c_result,
|
612 |
+
c_dict, c_result.dict)
|
613 |
+
if self._c_style.doc.dict is not c_result.dict:
|
614 |
+
fixThreadDictNames(<xmlNode*>c_result,
|
615 |
+
self._c_style.doc.dict, c_result.dict)
|
616 |
+
if input_doc._c_doc.dict is not c_result.dict:
|
617 |
+
fixThreadDictNames(<xmlNode*>c_result,
|
618 |
+
input_doc._c_doc.dict, c_result.dict)
|
619 |
+
xmlparser.xmlDictFree(c_dict)
|
620 |
+
|
621 |
+
return _xsltResultTreeFactory(result_doc, self, profile_doc)
|
622 |
+
|
623 |
+
cdef xmlDoc* _run_transform(self, xmlDoc* c_input_doc,
|
624 |
+
const_char** params, _XSLTContext context,
|
625 |
+
xslt.xsltTransformContext* transform_ctxt):
|
626 |
+
cdef xmlDoc* c_result
|
627 |
+
xslt.xsltSetTransformErrorFunc(transform_ctxt, <void*>self._error_log,
|
628 |
+
<xmlerror.xmlGenericErrorFunc>_receiveXSLTError)
|
629 |
+
if self._access_control is not None:
|
630 |
+
self._access_control._register_in_context(transform_ctxt)
|
631 |
+
with self._error_log, nogil:
|
632 |
+
orig_loader = _register_document_loader()
|
633 |
+
c_result = xslt.xsltApplyStylesheetUser(
|
634 |
+
self._c_style, c_input_doc, params, NULL, NULL, transform_ctxt)
|
635 |
+
_reset_document_loader(orig_loader)
|
636 |
+
return c_result
|
637 |
+
|
638 |
+
|
639 |
+
cdef _convert_xslt_parameters(xslt.xsltTransformContext* transform_ctxt,
|
640 |
+
dict parameters, const_char*** params_ptr):
|
641 |
+
cdef Py_ssize_t i, parameter_count
|
642 |
+
cdef const_char** params
|
643 |
+
cdef tree.xmlDict* c_dict = transform_ctxt.dict
|
644 |
+
params_ptr[0] = NULL
|
645 |
+
parameter_count = len(parameters)
|
646 |
+
if parameter_count == 0:
|
647 |
+
return
|
648 |
+
# allocate space for parameters
|
649 |
+
# * 2 as we want an entry for both key and value,
|
650 |
+
# and + 1 as array is NULL terminated
|
651 |
+
params = <const_char**>python.lxml_malloc(parameter_count * 2 + 1, sizeof(const_char*))
|
652 |
+
if not params:
|
653 |
+
raise MemoryError()
|
654 |
+
try:
|
655 |
+
i = 0
|
656 |
+
for key, value in parameters.iteritems():
|
657 |
+
k = _utf8(key)
|
658 |
+
if isinstance(value, _XSLTQuotedStringParam):
|
659 |
+
v = (<_XSLTQuotedStringParam>value).strval
|
660 |
+
xslt.xsltQuoteOneUserParam(
|
661 |
+
transform_ctxt, _xcstr(k), _xcstr(v))
|
662 |
+
else:
|
663 |
+
if isinstance(value, XPath):
|
664 |
+
v = (<XPath>value)._path
|
665 |
+
else:
|
666 |
+
v = _utf8(value)
|
667 |
+
params[i] = <const_char*>tree.xmlDictLookup(c_dict, _xcstr(k), len(k))
|
668 |
+
i += 1
|
669 |
+
params[i] = <const_char*>tree.xmlDictLookup(c_dict, _xcstr(v), len(v))
|
670 |
+
i += 1
|
671 |
+
except:
|
672 |
+
python.lxml_free(params)
|
673 |
+
raise
|
674 |
+
params[i] = NULL
|
675 |
+
params_ptr[0] = params
|
676 |
+
|
677 |
+
cdef XSLT _copyXSLT(XSLT stylesheet):
|
678 |
+
cdef XSLT new_xslt
|
679 |
+
cdef xmlDoc* c_doc
|
680 |
+
assert stylesheet._c_style is not NULL, "XSLT stylesheet not initialised"
|
681 |
+
new_xslt = XSLT.__new__(XSLT)
|
682 |
+
new_xslt._access_control = stylesheet._access_control
|
683 |
+
new_xslt._error_log = _ErrorLog()
|
684 |
+
new_xslt._context = stylesheet._context._copy()
|
685 |
+
|
686 |
+
new_xslt._xslt_resolver_context = stylesheet._xslt_resolver_context._copy()
|
687 |
+
new_xslt._xslt_resolver_context._c_style_doc = _copyDoc(
|
688 |
+
stylesheet._xslt_resolver_context._c_style_doc, 1)
|
689 |
+
|
690 |
+
c_doc = _copyDoc(stylesheet._c_style.doc, 1)
|
691 |
+
new_xslt._c_style = xslt.xsltParseStylesheetDoc(c_doc)
|
692 |
+
if new_xslt._c_style is NULL:
|
693 |
+
tree.xmlFreeDoc(c_doc)
|
694 |
+
raise MemoryError()
|
695 |
+
|
696 |
+
return new_xslt
|
697 |
+
|
698 |
+
@cython.final
|
699 |
+
cdef class _XSLTResultTree(_ElementTree):
|
700 |
+
"""The result of an XSLT evaluation.
|
701 |
+
|
702 |
+
Use ``str()`` or ``bytes()`` (or ``unicode()`` in Python 2.x) to serialise to a string,
|
703 |
+
and the ``.write_output()`` method to write serialise to a file.
|
704 |
+
"""
|
705 |
+
cdef XSLT _xslt
|
706 |
+
cdef _Document _profile
|
707 |
+
cdef xmlChar* _buffer
|
708 |
+
cdef Py_ssize_t _buffer_len
|
709 |
+
cdef Py_ssize_t _buffer_refcnt
|
710 |
+
|
711 |
+
def write_output(self, file, *, compression=0):
|
712 |
+
"""write_output(self, file, *, compression=0)
|
713 |
+
|
714 |
+
Serialise the XSLT output to a file or file-like object.
|
715 |
+
|
716 |
+
As opposed to the generic ``.write()`` method, ``.write_output()`` serialises
|
717 |
+
the result as defined by the ``<xsl:output>`` tag.
|
718 |
+
"""
|
719 |
+
cdef _FilelikeWriter writer = None
|
720 |
+
cdef _Document doc
|
721 |
+
cdef int r, rclose, c_compression
|
722 |
+
cdef const_xmlChar* c_encoding = NULL
|
723 |
+
cdef tree.xmlOutputBuffer* c_buffer
|
724 |
+
|
725 |
+
if self._context_node is not None:
|
726 |
+
doc = self._context_node._doc
|
727 |
+
else:
|
728 |
+
doc = None
|
729 |
+
if doc is None:
|
730 |
+
doc = self._doc
|
731 |
+
if doc is None:
|
732 |
+
raise XSLTSaveError("No document to serialise")
|
733 |
+
c_compression = compression or 0
|
734 |
+
xslt.LXML_GET_XSLT_ENCODING(c_encoding, self._xslt._c_style)
|
735 |
+
writer = _create_output_buffer(file, <const_char*>c_encoding, compression, &c_buffer, close=False)
|
736 |
+
if writer is None:
|
737 |
+
with nogil:
|
738 |
+
r = xslt.xsltSaveResultTo(c_buffer, doc._c_doc, self._xslt._c_style)
|
739 |
+
rclose = tree.xmlOutputBufferClose(c_buffer)
|
740 |
+
else:
|
741 |
+
r = xslt.xsltSaveResultTo(c_buffer, doc._c_doc, self._xslt._c_style)
|
742 |
+
rclose = tree.xmlOutputBufferClose(c_buffer)
|
743 |
+
if writer is not None:
|
744 |
+
writer._exc_context._raise_if_stored()
|
745 |
+
if r < 0 or rclose == -1:
|
746 |
+
python.PyErr_SetFromErrno(IOError) # raises IOError
|
747 |
+
|
748 |
+
cdef _saveToStringAndSize(self, xmlChar** s, int* l):
|
749 |
+
cdef _Document doc
|
750 |
+
cdef int r
|
751 |
+
if self._context_node is not None:
|
752 |
+
doc = self._context_node._doc
|
753 |
+
else:
|
754 |
+
doc = None
|
755 |
+
if doc is None:
|
756 |
+
doc = self._doc
|
757 |
+
if doc is None:
|
758 |
+
s[0] = NULL
|
759 |
+
return
|
760 |
+
with nogil:
|
761 |
+
r = xslt.xsltSaveResultToString(s, l, doc._c_doc,
|
762 |
+
self._xslt._c_style)
|
763 |
+
if r == -1:
|
764 |
+
raise MemoryError()
|
765 |
+
|
766 |
+
def __str__(self):
|
767 |
+
cdef xmlChar* encoding
|
768 |
+
cdef xmlChar* s = NULL
|
769 |
+
cdef int l = 0
|
770 |
+
self._saveToStringAndSize(&s, &l)
|
771 |
+
if s is NULL:
|
772 |
+
return ''
|
773 |
+
encoding = self._xslt._c_style.encoding
|
774 |
+
try:
|
775 |
+
if encoding is NULL:
|
776 |
+
result = s[:l].decode('UTF-8')
|
777 |
+
else:
|
778 |
+
result = s[:l].decode(encoding)
|
779 |
+
finally:
|
780 |
+
tree.xmlFree(s)
|
781 |
+
return _stripEncodingDeclaration(result)
|
782 |
+
|
783 |
+
def __getbuffer__(self, Py_buffer* buffer, int flags):
|
784 |
+
cdef int l = 0
|
785 |
+
if buffer is NULL:
|
786 |
+
return
|
787 |
+
if self._buffer is NULL or flags & python.PyBUF_WRITABLE:
|
788 |
+
self._saveToStringAndSize(<xmlChar**>&buffer.buf, &l)
|
789 |
+
buffer.len = l
|
790 |
+
if self._buffer is NULL and not flags & python.PyBUF_WRITABLE:
|
791 |
+
self._buffer = <xmlChar*>buffer.buf
|
792 |
+
self._buffer_len = l
|
793 |
+
self._buffer_refcnt = 1
|
794 |
+
else:
|
795 |
+
buffer.buf = self._buffer
|
796 |
+
buffer.len = self._buffer_len
|
797 |
+
self._buffer_refcnt += 1
|
798 |
+
if flags & python.PyBUF_WRITABLE:
|
799 |
+
buffer.readonly = 0
|
800 |
+
else:
|
801 |
+
buffer.readonly = 1
|
802 |
+
if flags & python.PyBUF_FORMAT:
|
803 |
+
buffer.format = "B"
|
804 |
+
else:
|
805 |
+
buffer.format = NULL
|
806 |
+
buffer.ndim = 0
|
807 |
+
buffer.shape = NULL
|
808 |
+
buffer.strides = NULL
|
809 |
+
buffer.suboffsets = NULL
|
810 |
+
buffer.itemsize = 1
|
811 |
+
buffer.internal = NULL
|
812 |
+
if buffer.obj is not self: # set by Cython?
|
813 |
+
buffer.obj = self
|
814 |
+
|
815 |
+
def __releasebuffer__(self, Py_buffer* buffer):
|
816 |
+
if buffer is NULL:
|
817 |
+
return
|
818 |
+
if <xmlChar*>buffer.buf is self._buffer:
|
819 |
+
self._buffer_refcnt -= 1
|
820 |
+
if self._buffer_refcnt == 0:
|
821 |
+
tree.xmlFree(<char*>self._buffer)
|
822 |
+
self._buffer = NULL
|
823 |
+
else:
|
824 |
+
tree.xmlFree(<char*>buffer.buf)
|
825 |
+
buffer.buf = NULL
|
826 |
+
|
827 |
+
property xslt_profile:
|
828 |
+
"""Return an ElementTree with profiling data for the stylesheet run.
|
829 |
+
"""
|
830 |
+
def __get__(self):
|
831 |
+
cdef object root
|
832 |
+
if self._profile is None:
|
833 |
+
return None
|
834 |
+
root = self._profile.getroot()
|
835 |
+
if root is None:
|
836 |
+
return None
|
837 |
+
return ElementTree(root)
|
838 |
+
|
839 |
+
def __del__(self):
|
840 |
+
self._profile = None
|
841 |
+
|
842 |
+
cdef _xsltResultTreeFactory(_Document doc, XSLT xslt, _Document profile):
|
843 |
+
cdef _XSLTResultTree result
|
844 |
+
result = <_XSLTResultTree>_newElementTree(doc, None, _XSLTResultTree)
|
845 |
+
result._xslt = xslt
|
846 |
+
result._profile = profile
|
847 |
+
return result
|
848 |
+
|
849 |
+
# functions like "output" and "write" are a potential security risk, but we
|
850 |
+
# rely on the user to configure XSLTAccessControl as needed
|
851 |
+
xslt.xsltRegisterAllExtras()
|
852 |
+
|
853 |
+
# enable EXSLT support for XSLT
|
854 |
+
xslt.exsltRegisterAll()
|
855 |
+
|
856 |
+
|
857 |
+
################################################################################
|
858 |
+
# XSLT PI support
|
859 |
+
|
860 |
+
cdef object _RE_PI_HREF = re.compile(r'\s+href\s*=\s*(?:\'([^\']*)\'|"([^"]*)")')
|
861 |
+
cdef object _FIND_PI_HREF = _RE_PI_HREF.findall
|
862 |
+
cdef object _REPLACE_PI_HREF = _RE_PI_HREF.sub
|
863 |
+
cdef XPath __findStylesheetByID = None
|
864 |
+
|
865 |
+
cdef _findStylesheetByID(_Document doc, id):
|
866 |
+
global __findStylesheetByID
|
867 |
+
if __findStylesheetByID is None:
|
868 |
+
__findStylesheetByID = XPath(
|
869 |
+
"//xsl:stylesheet[@xml:id = $id]",
|
870 |
+
namespaces={"xsl" : "http://www.w3.org/1999/XSL/Transform"})
|
871 |
+
return __findStylesheetByID(doc, id=id)
|
872 |
+
|
873 |
+
cdef class _XSLTProcessingInstruction(PIBase):
|
874 |
+
def parseXSL(self, parser=None):
|
875 |
+
"""parseXSL(self, parser=None)
|
876 |
+
|
877 |
+
Try to parse the stylesheet referenced by this PI and return
|
878 |
+
an ElementTree for it. If the stylesheet is embedded in the
|
879 |
+
same document (referenced via xml:id), find and return an
|
880 |
+
ElementTree for the stylesheet Element.
|
881 |
+
|
882 |
+
The optional ``parser`` keyword argument can be passed to specify the
|
883 |
+
parser used to read from external stylesheet URLs.
|
884 |
+
"""
|
885 |
+
cdef _Document result_doc
|
886 |
+
cdef _Element result_node
|
887 |
+
cdef bytes href_utf
|
888 |
+
cdef const_xmlChar* c_href
|
889 |
+
cdef xmlAttr* c_attr
|
890 |
+
_assertValidNode(self)
|
891 |
+
if self._c_node.content is NULL:
|
892 |
+
raise ValueError, "PI lacks content"
|
893 |
+
hrefs = _FIND_PI_HREF(' ' + (<unsigned char*>self._c_node.content).decode('UTF-8'))
|
894 |
+
if len(hrefs) != 1:
|
895 |
+
raise ValueError, "malformed PI attributes"
|
896 |
+
hrefs = hrefs[0]
|
897 |
+
href_utf = utf8(hrefs[0] or hrefs[1])
|
898 |
+
c_href = _xcstr(href_utf)
|
899 |
+
|
900 |
+
if c_href[0] != c'#':
|
901 |
+
# normal URL, try to parse from it
|
902 |
+
c_href = tree.xmlBuildURI(
|
903 |
+
c_href,
|
904 |
+
tree.xmlNodeGetBase(self._c_node.doc, self._c_node))
|
905 |
+
if c_href is not NULL:
|
906 |
+
try:
|
907 |
+
href_utf = <unsigned char*>c_href
|
908 |
+
finally:
|
909 |
+
tree.xmlFree(<char*>c_href)
|
910 |
+
result_doc = _parseDocumentFromURL(href_utf, parser)
|
911 |
+
return _elementTreeFactory(result_doc, None)
|
912 |
+
|
913 |
+
# ID reference to embedded stylesheet
|
914 |
+
# try XML:ID lookup
|
915 |
+
_assertValidDoc(self._doc)
|
916 |
+
c_href += 1 # skip leading '#'
|
917 |
+
c_attr = tree.xmlGetID(self._c_node.doc, c_href)
|
918 |
+
if c_attr is not NULL and c_attr.doc is self._c_node.doc:
|
919 |
+
result_node = _elementFactory(self._doc, c_attr.parent)
|
920 |
+
return _elementTreeFactory(result_node._doc, result_node)
|
921 |
+
|
922 |
+
# try XPath search
|
923 |
+
root = _findStylesheetByID(self._doc, funicode(c_href))
|
924 |
+
if not root:
|
925 |
+
raise ValueError, "reference to non-existing embedded stylesheet"
|
926 |
+
elif len(root) > 1:
|
927 |
+
raise ValueError, "ambiguous reference to embedded stylesheet"
|
928 |
+
result_node = root[0]
|
929 |
+
return _elementTreeFactory(result_node._doc, result_node)
|
930 |
+
|
931 |
+
def set(self, key, value):
|
932 |
+
"""set(self, key, value)
|
933 |
+
|
934 |
+
Supports setting the 'href' pseudo-attribute in the text of
|
935 |
+
the processing instruction.
|
936 |
+
"""
|
937 |
+
if key != "href":
|
938 |
+
raise AttributeError, \
|
939 |
+
"only setting the 'href' attribute is supported on XSLT-PIs"
|
940 |
+
if value is None:
|
941 |
+
attrib = ""
|
942 |
+
elif '"' in value or '>' in value:
|
943 |
+
raise ValueError, "Invalid URL, must not contain '\"' or '>'"
|
944 |
+
else:
|
945 |
+
attrib = f' href="{value}"'
|
946 |
+
text = ' ' + self.text
|
947 |
+
if _FIND_PI_HREF(text):
|
948 |
+
self.text = _REPLACE_PI_HREF(attrib, text)
|
949 |
+
else:
|
950 |
+
self.text = text + attrib
|
env-llmeval/lib/python3.10/site-packages/lxml/xsltext.pxi
ADDED
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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, input_node, output_parent):
|
7 |
+
"""execute(self, context, self_node, input_node, output_parent)
|
8 |
+
Execute this extension element.
|
9 |
+
|
10 |
+
Subclasses must override this method. They may append
|
11 |
+
elements to the `output_parent` element here, or set its text
|
12 |
+
content. To this end, the `input_node` provides read-only
|
13 |
+
access to the current node in the input document, and the
|
14 |
+
`self_node` points to the extension element in the stylesheet.
|
15 |
+
|
16 |
+
Note that the `output_parent` parameter may be `None` if there
|
17 |
+
is no parent element in the current context (e.g. no content
|
18 |
+
was added to the output tree yet).
|
19 |
+
"""
|
20 |
+
pass
|
21 |
+
|
22 |
+
def apply_templates(self, _XSLTContext context not None, node, output_parent=None,
|
23 |
+
*, elements_only=False, remove_blank_text=False):
|
24 |
+
"""apply_templates(self, context, node, output_parent=None, elements_only=False, remove_blank_text=False)
|
25 |
+
|
26 |
+
Call this method to retrieve the result of applying templates
|
27 |
+
to an element.
|
28 |
+
|
29 |
+
The return value is a list of elements or text strings that
|
30 |
+
were generated by the XSLT processor. If you pass
|
31 |
+
``elements_only=True``, strings will be discarded from the result
|
32 |
+
list. The option ``remove_blank_text=True`` will only discard
|
33 |
+
strings that consist entirely of whitespace (e.g. formatting).
|
34 |
+
These options do not apply to Elements, only to bare string results.
|
35 |
+
|
36 |
+
If you pass an Element as `output_parent` parameter, the result
|
37 |
+
will instead be appended to the element (including attributes
|
38 |
+
etc.) and the return value will be `None`. This is a safe way
|
39 |
+
to generate content into the output document directly, without
|
40 |
+
having to take care of special values like text or attributes.
|
41 |
+
Note that the string discarding options will be ignored in this
|
42 |
+
case.
|
43 |
+
"""
|
44 |
+
cdef xmlNode* c_parent
|
45 |
+
cdef xmlNode* c_node
|
46 |
+
cdef xmlNode* c_context_node
|
47 |
+
assert context._xsltCtxt is not NULL, "XSLT context not initialised"
|
48 |
+
c_context_node = _roNodeOf(node)
|
49 |
+
#assert c_context_node.doc is context._xsltContext.node.doc, \
|
50 |
+
# "switching input documents during transformation is not currently supported"
|
51 |
+
|
52 |
+
if output_parent is not None:
|
53 |
+
c_parent = _nonRoNodeOf(output_parent)
|
54 |
+
else:
|
55 |
+
c_parent = tree.xmlNewDocNode(
|
56 |
+
context._xsltCtxt.output, NULL, <unsigned char*>"fake-parent", NULL)
|
57 |
+
|
58 |
+
c_node = context._xsltCtxt.insert
|
59 |
+
context._xsltCtxt.insert = c_parent
|
60 |
+
xslt.xsltProcessOneNode(
|
61 |
+
context._xsltCtxt, c_context_node, NULL)
|
62 |
+
context._xsltCtxt.insert = c_node
|
63 |
+
|
64 |
+
if output_parent is not None:
|
65 |
+
return None
|
66 |
+
|
67 |
+
try:
|
68 |
+
return self._collectXSLTResultContent(
|
69 |
+
context, c_parent, elements_only, remove_blank_text)
|
70 |
+
finally:
|
71 |
+
# free all intermediate nodes that will not be freed by proxies
|
72 |
+
tree.xmlFreeNode(c_parent)
|
73 |
+
|
74 |
+
def process_children(self, _XSLTContext context not None, output_parent=None,
|
75 |
+
*, elements_only=False, remove_blank_text=False):
|
76 |
+
"""process_children(self, context, output_parent=None, elements_only=False, remove_blank_text=False)
|
77 |
+
|
78 |
+
Call this method to process the XSLT content of the extension
|
79 |
+
element itself.
|
80 |
+
|
81 |
+
The return value is a list of elements or text strings that
|
82 |
+
were generated by the XSLT processor. If you pass
|
83 |
+
``elements_only=True``, strings will be discarded from the result
|
84 |
+
list. The option ``remove_blank_text=True`` will only discard
|
85 |
+
strings that consist entirely of whitespace (e.g. formatting).
|
86 |
+
These options do not apply to Elements, only to bare string results.
|
87 |
+
|
88 |
+
If you pass an Element as `output_parent` parameter, the result
|
89 |
+
will instead be appended to the element (including attributes
|
90 |
+
etc.) and the return value will be `None`. This is a safe way
|
91 |
+
to generate content into the output document directly, without
|
92 |
+
having to take care of special values like text or attributes.
|
93 |
+
Note that the string discarding options will be ignored in this
|
94 |
+
case.
|
95 |
+
"""
|
96 |
+
cdef xmlNode* c_parent
|
97 |
+
cdef xslt.xsltTransformContext* c_ctxt = context._xsltCtxt
|
98 |
+
cdef xmlNode* c_old_output_parent = c_ctxt.insert
|
99 |
+
assert context._xsltCtxt is not NULL, "XSLT context not initialised"
|
100 |
+
|
101 |
+
# output_parent node is used for adding results instead of
|
102 |
+
# elements list used in apply_templates, that's easier and allows to
|
103 |
+
# use attributes added to extension element with <xsl:attribute>.
|
104 |
+
|
105 |
+
if output_parent is not None:
|
106 |
+
c_parent = _nonRoNodeOf(output_parent)
|
107 |
+
else:
|
108 |
+
c_parent = tree.xmlNewDocNode(
|
109 |
+
context._xsltCtxt.output, NULL, <unsigned char*>"fake-parent", NULL)
|
110 |
+
|
111 |
+
c_ctxt.insert = c_parent
|
112 |
+
xslt.xsltApplyOneTemplate(c_ctxt,
|
113 |
+
c_ctxt.node, c_ctxt.inst.children, NULL, NULL)
|
114 |
+
c_ctxt.insert = c_old_output_parent
|
115 |
+
|
116 |
+
if output_parent is not None:
|
117 |
+
return None
|
118 |
+
|
119 |
+
try:
|
120 |
+
return self._collectXSLTResultContent(
|
121 |
+
context, c_parent, elements_only, remove_blank_text)
|
122 |
+
finally:
|
123 |
+
# free all intermediate nodes that will not be freed by proxies
|
124 |
+
tree.xmlFreeNode(c_parent)
|
125 |
+
|
126 |
+
cdef _collectXSLTResultContent(self, _XSLTContext context, xmlNode* c_parent,
|
127 |
+
bint elements_only, bint remove_blank_text):
|
128 |
+
cdef xmlNode* c_node
|
129 |
+
cdef xmlNode* c_next
|
130 |
+
cdef _ReadOnlyProxy proxy
|
131 |
+
cdef list results = [] # or maybe _collectAttributes(c_parent, 2) ?
|
132 |
+
c_node = c_parent.children
|
133 |
+
while c_node is not NULL:
|
134 |
+
c_next = c_node.next
|
135 |
+
if c_node.type == tree.XML_TEXT_NODE:
|
136 |
+
if not elements_only:
|
137 |
+
s = funicode(c_node.content)
|
138 |
+
if not remove_blank_text or s.strip():
|
139 |
+
results.append(s)
|
140 |
+
s = None
|
141 |
+
elif c_node.type == tree.XML_ELEMENT_NODE:
|
142 |
+
proxy = _newReadOnlyProxy(
|
143 |
+
context._extension_element_proxy, c_node)
|
144 |
+
results.append(proxy)
|
145 |
+
# unlink node and make sure it will be freed later on
|
146 |
+
tree.xmlUnlinkNode(c_node)
|
147 |
+
proxy.free_after_use()
|
148 |
+
else:
|
149 |
+
raise TypeError, \
|
150 |
+
f"unsupported XSLT result type: {c_node.type}"
|
151 |
+
c_node = c_next
|
152 |
+
return results
|
153 |
+
|
154 |
+
|
155 |
+
cdef _registerXSLTExtensions(xslt.xsltTransformContext* c_ctxt,
|
156 |
+
extension_dict):
|
157 |
+
for ns_utf, name_utf in extension_dict:
|
158 |
+
xslt.xsltRegisterExtElement(
|
159 |
+
c_ctxt, _xcstr(name_utf), _xcstr(ns_utf),
|
160 |
+
<xslt.xsltTransformFunction>_callExtensionElement)
|
161 |
+
|
162 |
+
cdef void _callExtensionElement(xslt.xsltTransformContext* c_ctxt,
|
163 |
+
xmlNode* c_context_node,
|
164 |
+
xmlNode* c_inst_node,
|
165 |
+
void* dummy) noexcept with gil:
|
166 |
+
cdef _XSLTContext context
|
167 |
+
cdef XSLTExtension extension
|
168 |
+
cdef python.PyObject* dict_result
|
169 |
+
cdef xmlNode* c_node
|
170 |
+
cdef _ReadOnlyProxy context_node = None, self_node = None
|
171 |
+
cdef object output_parent # not restricted to ro-nodes
|
172 |
+
c_uri = _getNs(c_inst_node)
|
173 |
+
if c_uri is NULL:
|
174 |
+
# not allowed, and should never happen
|
175 |
+
return
|
176 |
+
if c_ctxt.xpathCtxt.userData is NULL:
|
177 |
+
# just for safety, should never happen
|
178 |
+
return
|
179 |
+
context = <_XSLTContext>c_ctxt.xpathCtxt.userData
|
180 |
+
try:
|
181 |
+
try:
|
182 |
+
dict_result = python.PyDict_GetItem(
|
183 |
+
context._extension_elements, (c_uri, c_inst_node.name))
|
184 |
+
if dict_result is NULL:
|
185 |
+
raise KeyError, f"extension element {funicode(c_inst_node.name)} not found"
|
186 |
+
extension = <object>dict_result
|
187 |
+
|
188 |
+
try:
|
189 |
+
# build the context proxy nodes
|
190 |
+
self_node = _newReadOnlyProxy(None, c_inst_node)
|
191 |
+
if _isElement(c_ctxt.insert):
|
192 |
+
output_parent = _newAppendOnlyProxy(self_node, c_ctxt.insert)
|
193 |
+
else:
|
194 |
+
# may be the document node or other stuff
|
195 |
+
output_parent = _newOpaqueAppendOnlyNodeWrapper(c_ctxt.insert)
|
196 |
+
if c_context_node.type in (tree.XML_DOCUMENT_NODE,
|
197 |
+
tree.XML_HTML_DOCUMENT_NODE):
|
198 |
+
c_node = tree.xmlDocGetRootElement(<xmlDoc*>c_context_node)
|
199 |
+
if c_node is not NULL:
|
200 |
+
context_node = _newReadOnlyProxy(self_node, c_node)
|
201 |
+
else:
|
202 |
+
context_node = None
|
203 |
+
elif c_context_node.type in (tree.XML_ATTRIBUTE_NODE,
|
204 |
+
tree.XML_TEXT_NODE,
|
205 |
+
tree.XML_CDATA_SECTION_NODE):
|
206 |
+
# this isn't easy to support using read-only
|
207 |
+
# nodes, as the smart-string factory must
|
208 |
+
# instantiate the parent proxy somehow...
|
209 |
+
raise TypeError(f"Unsupported element type: {c_context_node.type}")
|
210 |
+
else:
|
211 |
+
context_node = _newReadOnlyProxy(self_node, c_context_node)
|
212 |
+
|
213 |
+
# run the XSLT extension
|
214 |
+
context._extension_element_proxy = self_node
|
215 |
+
extension.execute(context, self_node, context_node, output_parent)
|
216 |
+
finally:
|
217 |
+
context._extension_element_proxy = None
|
218 |
+
if self_node is not None:
|
219 |
+
_freeReadOnlyProxies(self_node)
|
220 |
+
except Exception as e:
|
221 |
+
try:
|
222 |
+
e = unicode(e).encode("UTF-8")
|
223 |
+
except:
|
224 |
+
e = repr(e).encode("UTF-8")
|
225 |
+
message = python.PyBytes_FromFormat(
|
226 |
+
"Error executing extension element '%s': %s",
|
227 |
+
c_inst_node.name, _cstr(e))
|
228 |
+
xslt.xsltTransformError(c_ctxt, NULL, c_inst_node, "%s", message)
|
229 |
+
context._exc._store_raised()
|
230 |
+
except:
|
231 |
+
# just in case
|
232 |
+
message = python.PyBytes_FromFormat(
|
233 |
+
"Error executing extension element '%s'", c_inst_node.name)
|
234 |
+
xslt.xsltTransformError(c_ctxt, NULL, c_inst_node, "%s", message)
|
235 |
+
context._exc._store_raised()
|
236 |
+
except:
|
237 |
+
# no Python functions here - everything can fail...
|
238 |
+
xslt.xsltTransformError(c_ctxt, NULL, c_inst_node,
|
239 |
+
"Error during XSLT extension element evaluation")
|
240 |
+
context._exc._store_raised()
|
241 |
+
finally:
|
242 |
+
return # swallow any further exceptions
|
env-llmeval/lib/python3.10/site-packages/triton/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/__pycache__/testing.cpython-310.pyc
ADDED
Binary file (13.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/language/__init__.py
ADDED
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""isort:skip_file"""
|
2 |
+
# Import order is significant here.
|
3 |
+
|
4 |
+
from . import math
|
5 |
+
from . import extra
|
6 |
+
from .standard import (
|
7 |
+
argmax,
|
8 |
+
argmin,
|
9 |
+
cdiv,
|
10 |
+
cumprod,
|
11 |
+
cumsum,
|
12 |
+
max,
|
13 |
+
maximum,
|
14 |
+
min,
|
15 |
+
minimum,
|
16 |
+
sigmoid,
|
17 |
+
softmax,
|
18 |
+
sort,
|
19 |
+
sum,
|
20 |
+
ravel,
|
21 |
+
swizzle2d,
|
22 |
+
xor_sum,
|
23 |
+
zeros,
|
24 |
+
zeros_like,
|
25 |
+
)
|
26 |
+
from .core import (
|
27 |
+
TRITON_MAX_TENSOR_NUMEL,
|
28 |
+
abs,
|
29 |
+
advance,
|
30 |
+
arange,
|
31 |
+
associative_scan,
|
32 |
+
atomic_add,
|
33 |
+
atomic_and,
|
34 |
+
atomic_cas,
|
35 |
+
atomic_max,
|
36 |
+
atomic_min,
|
37 |
+
atomic_or,
|
38 |
+
atomic_xchg,
|
39 |
+
atomic_xor,
|
40 |
+
bfloat16,
|
41 |
+
block_type,
|
42 |
+
broadcast,
|
43 |
+
broadcast_to,
|
44 |
+
cat,
|
45 |
+
constexpr,
|
46 |
+
cos,
|
47 |
+
debug_barrier,
|
48 |
+
device_assert,
|
49 |
+
device_print,
|
50 |
+
dot,
|
51 |
+
dtype,
|
52 |
+
exp,
|
53 |
+
expand_dims,
|
54 |
+
full,
|
55 |
+
fdiv,
|
56 |
+
float16,
|
57 |
+
float32,
|
58 |
+
float64,
|
59 |
+
float8e4b15,
|
60 |
+
float8e4b15x4,
|
61 |
+
float8e4nv,
|
62 |
+
float8e5,
|
63 |
+
function_type,
|
64 |
+
inline_asm_elementwise,
|
65 |
+
int1,
|
66 |
+
int16,
|
67 |
+
int32,
|
68 |
+
int64,
|
69 |
+
int8,
|
70 |
+
load,
|
71 |
+
log,
|
72 |
+
make_block_ptr,
|
73 |
+
max_constancy,
|
74 |
+
max_contiguous,
|
75 |
+
multiple_of,
|
76 |
+
num_programs,
|
77 |
+
pi32_t,
|
78 |
+
pointer_type,
|
79 |
+
program_id,
|
80 |
+
reduce,
|
81 |
+
reshape,
|
82 |
+
sin,
|
83 |
+
sqrt,
|
84 |
+
static_assert,
|
85 |
+
static_print,
|
86 |
+
store,
|
87 |
+
static_range,
|
88 |
+
tensor,
|
89 |
+
trans,
|
90 |
+
# triton,
|
91 |
+
uint16,
|
92 |
+
uint32,
|
93 |
+
uint64,
|
94 |
+
uint8,
|
95 |
+
umulhi,
|
96 |
+
view,
|
97 |
+
void,
|
98 |
+
where,
|
99 |
+
)
|
100 |
+
from .random import (
|
101 |
+
pair_uniform_to_normal,
|
102 |
+
philox,
|
103 |
+
philox_impl,
|
104 |
+
rand,
|
105 |
+
rand4x,
|
106 |
+
randint,
|
107 |
+
randint4x,
|
108 |
+
randn,
|
109 |
+
randn4x,
|
110 |
+
uint_to_uniform_float,
|
111 |
+
)
|
112 |
+
|
113 |
+
__all__ = [
|
114 |
+
"TRITON_MAX_TENSOR_NUMEL",
|
115 |
+
"abs",
|
116 |
+
"advance",
|
117 |
+
"arange",
|
118 |
+
"argmin",
|
119 |
+
"argmax",
|
120 |
+
"associative_scan",
|
121 |
+
"atomic_add",
|
122 |
+
"atomic_and",
|
123 |
+
"atomic_cas",
|
124 |
+
"atomic_max",
|
125 |
+
"atomic_min",
|
126 |
+
"atomic_or",
|
127 |
+
"atomic_xchg",
|
128 |
+
"atomic_xor",
|
129 |
+
"bfloat16",
|
130 |
+
"block_type",
|
131 |
+
"broadcast",
|
132 |
+
"broadcast_to",
|
133 |
+
"builtin",
|
134 |
+
"cat",
|
135 |
+
"cdiv",
|
136 |
+
"constexpr",
|
137 |
+
"cos",
|
138 |
+
"cumprod",
|
139 |
+
"cumsum",
|
140 |
+
"debug_barrier",
|
141 |
+
"device_assert",
|
142 |
+
"device_print",
|
143 |
+
"dot",
|
144 |
+
"dtype",
|
145 |
+
"exp",
|
146 |
+
"expand_dims",
|
147 |
+
"extra",
|
148 |
+
"fdiv",
|
149 |
+
"float16",
|
150 |
+
"float32",
|
151 |
+
"float64",
|
152 |
+
"float8e4b15",
|
153 |
+
"float8e4b15x4",
|
154 |
+
"float8e4nv",
|
155 |
+
"float8e5",
|
156 |
+
"full",
|
157 |
+
"function_type",
|
158 |
+
"inline_asm_elementwise",
|
159 |
+
"int1",
|
160 |
+
"int16",
|
161 |
+
"int32",
|
162 |
+
"int64",
|
163 |
+
"int8",
|
164 |
+
"ir",
|
165 |
+
"math",
|
166 |
+
"load",
|
167 |
+
"log",
|
168 |
+
"make_block_ptr",
|
169 |
+
"max",
|
170 |
+
"max_constancy",
|
171 |
+
"max_contiguous",
|
172 |
+
"maximum",
|
173 |
+
"min",
|
174 |
+
"minimum",
|
175 |
+
"multiple_of",
|
176 |
+
"num_programs",
|
177 |
+
"pair_uniform_to_normal",
|
178 |
+
"philox",
|
179 |
+
"philox_impl",
|
180 |
+
"pi32_t",
|
181 |
+
"pointer_type",
|
182 |
+
"program_id",
|
183 |
+
"rand",
|
184 |
+
"rand4x",
|
185 |
+
"randint",
|
186 |
+
"randint4x",
|
187 |
+
"randn",
|
188 |
+
"randn4x",
|
189 |
+
"ravel",
|
190 |
+
"reduce",
|
191 |
+
"reshape",
|
192 |
+
"sigmoid",
|
193 |
+
"sin",
|
194 |
+
"softmax",
|
195 |
+
"sort",
|
196 |
+
"sqrt",
|
197 |
+
"static_range",
|
198 |
+
"static_assert",
|
199 |
+
"static_print",
|
200 |
+
"store",
|
201 |
+
"sum",
|
202 |
+
"swizzle2d",
|
203 |
+
"tensor",
|
204 |
+
"trans",
|
205 |
+
"triton",
|
206 |
+
"uint16",
|
207 |
+
"uint32",
|
208 |
+
"uint_to_uniform_float",
|
209 |
+
"uint64",
|
210 |
+
"uint8",
|
211 |
+
"umulhi",
|
212 |
+
"view",
|
213 |
+
"void",
|
214 |
+
"where",
|
215 |
+
"xor_sum",
|
216 |
+
"zeros",
|
217 |
+
"zeros_like",
|
218 |
+
]
|
env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.76 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/core.cpython-310.pyc
ADDED
Binary file (58.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/math.cpython-310.pyc
ADDED
Binary file (33.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/random.cpython-310.pyc
ADDED
Binary file (5.35 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/semantic.cpython-310.pyc
ADDED
Binary file (41.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/language/__pycache__/standard.cpython-310.pyc
ADDED
Binary file (9.64 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/triton/language/core.py
ADDED
@@ -0,0 +1,1884 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
from contextlib import contextmanager
|
4 |
+
from enum import Enum
|
5 |
+
from functools import partial, wraps
|
6 |
+
from typing import Callable, List, Sequence, TypeVar
|
7 |
+
|
8 |
+
from .._C.libtriton.triton import ir
|
9 |
+
from . import semantic
|
10 |
+
|
11 |
+
T = TypeVar('T')
|
12 |
+
|
13 |
+
TRITON_MAX_TENSOR_NUMEL = 1048576
|
14 |
+
|
15 |
+
TRITON_BUILTIN = "__triton_builtin__"
|
16 |
+
|
17 |
+
|
18 |
+
def builtin(fn: T) -> T:
|
19 |
+
"""Mark a function as a builtin."""
|
20 |
+
assert callable(fn)
|
21 |
+
|
22 |
+
@wraps(fn)
|
23 |
+
def wrapper(*args, **kwargs):
|
24 |
+
if "_builder" not in kwargs or kwargs["_builder"] is None:
|
25 |
+
raise ValueError("Did you forget to add @triton.jit ? "
|
26 |
+
"(`_builder` argument must be provided outside of JIT functions.)")
|
27 |
+
return fn(*args, **kwargs)
|
28 |
+
|
29 |
+
setattr(wrapper, TRITON_BUILTIN, True)
|
30 |
+
|
31 |
+
return wrapper
|
32 |
+
|
33 |
+
|
34 |
+
def is_builtin(fn) -> bool:
|
35 |
+
"""Is this a registered triton builtin function?"""
|
36 |
+
return getattr(fn, TRITON_BUILTIN, False)
|
37 |
+
|
38 |
+
|
39 |
+
def _to_tensor(x, builder):
|
40 |
+
if isinstance(x, bool):
|
41 |
+
return tensor(builder.get_int1(x), int1)
|
42 |
+
# Note: compile-time const integers are represented by unsigned values
|
43 |
+
elif isinstance(x, int):
|
44 |
+
if -2**31 <= x < 2**31:
|
45 |
+
return tensor(builder.get_int32(x), int32)
|
46 |
+
elif 2**31 <= x < 2**32:
|
47 |
+
return tensor(builder.get_uint32(x), uint32)
|
48 |
+
elif -2**63 <= x < 2**63:
|
49 |
+
return tensor(builder.get_int64(x), int64)
|
50 |
+
elif 2**63 <= x < 2**64:
|
51 |
+
return tensor(builder.get_uint64(x), uint64)
|
52 |
+
else:
|
53 |
+
raise RuntimeError(f'Nonrepresentable integer {x}.')
|
54 |
+
elif isinstance(x, float):
|
55 |
+
min_float32 = 2**-126
|
56 |
+
max_float32 = (2 - 2**-23) * 2**127
|
57 |
+
abs_x = __builtins__['abs'](x)
|
58 |
+
if abs_x == float("inf") or\
|
59 |
+
abs_x == 0.0 or \
|
60 |
+
x != x or \
|
61 |
+
min_float32 <= abs_x <= max_float32:
|
62 |
+
return tensor(builder.get_fp32(x), float32)
|
63 |
+
else:
|
64 |
+
return tensor(builder.get_fp64(x), float64)
|
65 |
+
|
66 |
+
elif isinstance(x, constexpr):
|
67 |
+
return _to_tensor(x.value, builder)
|
68 |
+
elif isinstance(x, tensor):
|
69 |
+
return x
|
70 |
+
assert False, f"cannot convert {x} of type {type(x)} to tensor"
|
71 |
+
|
72 |
+
|
73 |
+
class dtype:
|
74 |
+
SINT_TYPES = ['int8', 'int16', 'int32', 'int64']
|
75 |
+
UINT_TYPES = ['int1', 'uint8', 'uint16', 'uint32', 'uint64']
|
76 |
+
FP_TYPES = ['fp8e4b15', 'fp8e4b15x4', 'fp8e4nv', 'fp8e5', 'fp16', 'bf16', 'fp32', 'fp64']
|
77 |
+
STANDARD_FP_TYPES = ['fp16', 'bf16', 'fp32', 'fp64']
|
78 |
+
OTHER_TYPES = ['void']
|
79 |
+
|
80 |
+
class SIGNEDNESS(Enum):
|
81 |
+
SIGNED = 0
|
82 |
+
UNSIGNED = 1
|
83 |
+
|
84 |
+
def __init__(self, name):
|
85 |
+
self.name = name
|
86 |
+
assert name in dtype.SINT_TYPES + dtype.UINT_TYPES + dtype.FP_TYPES + dtype.OTHER_TYPES, name
|
87 |
+
if name in dtype.SINT_TYPES:
|
88 |
+
self.int_signedness = dtype.SIGNEDNESS.SIGNED
|
89 |
+
self.int_bitwidth = int(name.split('int')[-1])
|
90 |
+
self.primitive_bitwidth = self.int_bitwidth
|
91 |
+
elif name in dtype.UINT_TYPES:
|
92 |
+
self.int_signedness = dtype.SIGNEDNESS.UNSIGNED
|
93 |
+
self.int_bitwidth = int(name.split('int')[-1])
|
94 |
+
self.primitive_bitwidth = self.int_bitwidth
|
95 |
+
elif name in dtype.FP_TYPES:
|
96 |
+
if name == 'fp8e4b15':
|
97 |
+
self.fp_mantissa_width = 3
|
98 |
+
self.primitive_bitwidth = 8
|
99 |
+
self.exponent_bias = 15
|
100 |
+
elif name == 'fp8e4b15x4':
|
101 |
+
self.fp_mantissa_width = 3
|
102 |
+
self.primitive_bitwidth = 8
|
103 |
+
self.exponent_bias = 15
|
104 |
+
elif name == 'fp8e4nv':
|
105 |
+
self.fp_mantissa_width = 3
|
106 |
+
self.primitive_bitwidth = 8
|
107 |
+
self.exponent_bias = 7
|
108 |
+
elif name == 'fp8e5':
|
109 |
+
self.fp_mantissa_width = 2
|
110 |
+
self.primitive_bitwidth = 8
|
111 |
+
self.exponent_bias = 15
|
112 |
+
elif name == 'fp16':
|
113 |
+
self.fp_mantissa_width = 10
|
114 |
+
self.primitive_bitwidth = 16
|
115 |
+
self.exponent_bias = 15
|
116 |
+
elif name == 'bf16':
|
117 |
+
self.fp_mantissa_width = 7
|
118 |
+
self.primitive_bitwidth = 16
|
119 |
+
self.exponent_bias = 127
|
120 |
+
elif name == 'fp32':
|
121 |
+
self.fp_mantissa_width = 23
|
122 |
+
self.primitive_bitwidth = 32
|
123 |
+
self.exponent_bias = 127
|
124 |
+
elif name == 'fp64':
|
125 |
+
self.fp_mantissa_width = 53
|
126 |
+
self.primitive_bitwidth = 64
|
127 |
+
self.exponent_bias = 1023
|
128 |
+
else:
|
129 |
+
raise RuntimeError(f'Unsupported floating-point type {name}')
|
130 |
+
elif name == 'void':
|
131 |
+
self.primitive_bitwidth = 0
|
132 |
+
|
133 |
+
def is_fp8(self):
|
134 |
+
return 'fp8' in self.name
|
135 |
+
|
136 |
+
def is_fp8e4nv(self):
|
137 |
+
return self.name == 'fp8e4nv'
|
138 |
+
|
139 |
+
def is_fp8e4b15(self):
|
140 |
+
return self.name == 'fp8e4b15'
|
141 |
+
|
142 |
+
def is_fp8e4b15x4(self):
|
143 |
+
return self.name == 'fp8e4b15x4'
|
144 |
+
|
145 |
+
def is_fp8e5(self):
|
146 |
+
return self.name == 'fp8e5'
|
147 |
+
|
148 |
+
def is_fp16(self):
|
149 |
+
return self.name == 'fp16'
|
150 |
+
|
151 |
+
def is_bf16(self):
|
152 |
+
return self.name == 'bf16'
|
153 |
+
|
154 |
+
def is_fp32(self):
|
155 |
+
return self.name == 'fp32'
|
156 |
+
|
157 |
+
def is_fp64(self):
|
158 |
+
return self.name == 'fp64'
|
159 |
+
|
160 |
+
def is_int1(self):
|
161 |
+
return self.name == 'int1'
|
162 |
+
|
163 |
+
def is_int8(self):
|
164 |
+
return self.name == 'int8'
|
165 |
+
|
166 |
+
def is_int16(self):
|
167 |
+
return self.name == 'int16'
|
168 |
+
|
169 |
+
def is_int32(self):
|
170 |
+
return self.name == 'int32'
|
171 |
+
|
172 |
+
def is_int64(self):
|
173 |
+
return self.name == 'int64'
|
174 |
+
|
175 |
+
def is_uint8(self):
|
176 |
+
return self.name == 'uint8'
|
177 |
+
|
178 |
+
def is_uint16(self):
|
179 |
+
return self.name == 'uint16'
|
180 |
+
|
181 |
+
def is_uint32(self):
|
182 |
+
return self.name == 'uint32'
|
183 |
+
|
184 |
+
def is_uint64(self):
|
185 |
+
return self.name == 'uint64'
|
186 |
+
|
187 |
+
def is_floating(self):
|
188 |
+
return self.name in dtype.FP_TYPES
|
189 |
+
|
190 |
+
def is_standard_floating(self):
|
191 |
+
return self.name in dtype.STANDARD_FP_TYPES
|
192 |
+
|
193 |
+
def is_int_signed(self):
|
194 |
+
return self.name in dtype.SINT_TYPES
|
195 |
+
|
196 |
+
def is_int_unsigned(self):
|
197 |
+
return self.name in dtype.UINT_TYPES
|
198 |
+
|
199 |
+
def is_int(self):
|
200 |
+
return self.name in dtype.SINT_TYPES + dtype.UINT_TYPES
|
201 |
+
|
202 |
+
def is_bool(self):
|
203 |
+
return self.is_int1()
|
204 |
+
|
205 |
+
@staticmethod
|
206 |
+
def is_dtype(type_str):
|
207 |
+
return type_str in dtype.SINT_TYPES + dtype.UINT_TYPES + dtype.FP_TYPES + dtype.OTHER_TYPES
|
208 |
+
|
209 |
+
@staticmethod
|
210 |
+
def is_void():
|
211 |
+
raise RuntimeError("Not implemented")
|
212 |
+
|
213 |
+
@staticmethod
|
214 |
+
def is_block():
|
215 |
+
return False
|
216 |
+
|
217 |
+
@staticmethod
|
218 |
+
def is_ptr():
|
219 |
+
return False
|
220 |
+
|
221 |
+
def __eq__(self, other: dtype):
|
222 |
+
if not isinstance(other, dtype):
|
223 |
+
return False
|
224 |
+
return self.name == other.name
|
225 |
+
|
226 |
+
def __ne__(self, other: dtype):
|
227 |
+
return not self.__eq__(other)
|
228 |
+
|
229 |
+
def __hash__(self):
|
230 |
+
return hash((self.name, ))
|
231 |
+
|
232 |
+
@property
|
233 |
+
def scalar(self):
|
234 |
+
return self
|
235 |
+
|
236 |
+
def to_ir(self, builder: ir.builder) -> ir.type:
|
237 |
+
if self.name == 'void':
|
238 |
+
return builder.get_void_ty()
|
239 |
+
elif self.name == 'int1':
|
240 |
+
return builder.get_int1_ty()
|
241 |
+
elif self.name in ('int8', 'uint8'):
|
242 |
+
return builder.get_int8_ty()
|
243 |
+
elif self.name in ('int16', 'uint16'):
|
244 |
+
return builder.get_int16_ty()
|
245 |
+
elif self.name in ('int32', 'uint32'):
|
246 |
+
return builder.get_int32_ty()
|
247 |
+
elif self.name in ('int64', 'uint64'):
|
248 |
+
return builder.get_int64_ty()
|
249 |
+
elif self.name == 'fp8e5':
|
250 |
+
return builder.get_fp8e5_ty()
|
251 |
+
elif self.name == 'fp8e4nv':
|
252 |
+
return builder.get_fp8e4nv_ty()
|
253 |
+
elif self.name == 'fp8e4b15':
|
254 |
+
return builder.get_fp8e4b15_ty()
|
255 |
+
elif self.name == 'fp8e4b15x4':
|
256 |
+
return builder.get_fp8e4b15x4_ty()
|
257 |
+
elif self.name == 'fp16':
|
258 |
+
return builder.get_half_ty()
|
259 |
+
elif self.name == 'bf16':
|
260 |
+
return builder.get_bf16_ty()
|
261 |
+
elif self.name == 'fp32':
|
262 |
+
return builder.get_float_ty()
|
263 |
+
elif self.name == 'fp64':
|
264 |
+
return builder.get_double_ty()
|
265 |
+
raise ValueError(f'fail to convert {self} to ir type')
|
266 |
+
|
267 |
+
def __str__(self):
|
268 |
+
return self.name
|
269 |
+
|
270 |
+
@property
|
271 |
+
def cache_key_part(self) -> str:
|
272 |
+
"""See cache_key_part() in triton.cc."""
|
273 |
+
return self.name
|
274 |
+
|
275 |
+
def __repr__(self):
|
276 |
+
return f'triton.language.{str(self)}'
|
277 |
+
|
278 |
+
|
279 |
+
class pointer_type(dtype):
|
280 |
+
|
281 |
+
def __init__(self, element_ty: dtype, address_space: int = 1):
|
282 |
+
if not isinstance(element_ty, dtype):
|
283 |
+
raise TypeError('element_ty is a {type(element_ty).__name__}.')
|
284 |
+
self.element_ty = element_ty
|
285 |
+
self.address_space = address_space
|
286 |
+
|
287 |
+
self.name = self.__str__()
|
288 |
+
|
289 |
+
def to_ir(self, builder: ir.builder) -> ir.pointer_type:
|
290 |
+
return builder.get_ptr_ty(self.element_ty.to_ir(builder), 1)
|
291 |
+
|
292 |
+
def __str__(self):
|
293 |
+
return f'pointer<{self.element_ty}>'
|
294 |
+
|
295 |
+
def __repr__(self):
|
296 |
+
return self.__str__()
|
297 |
+
|
298 |
+
def is_ptr(self):
|
299 |
+
return True
|
300 |
+
|
301 |
+
def __eq__(self, other: pointer_type) -> bool:
|
302 |
+
if not isinstance(other, pointer_type):
|
303 |
+
return False
|
304 |
+
return self.element_ty == other.element_ty and self.address_space == other.address_space
|
305 |
+
|
306 |
+
def __ne__(self, other: pointer_type) -> bool:
|
307 |
+
return not self.__eq__(other)
|
308 |
+
|
309 |
+
@property
|
310 |
+
def scalar(self):
|
311 |
+
return self
|
312 |
+
|
313 |
+
|
314 |
+
class block_type(dtype):
|
315 |
+
|
316 |
+
def __init__(self, element_ty: dtype, shape: List):
|
317 |
+
self.element_ty = element_ty
|
318 |
+
|
319 |
+
# Note that block_type's shape is a list of int
|
320 |
+
# while tensor's shape is a list of constexpr.
|
321 |
+
|
322 |
+
# shape can be empty ([]) when an input is a 0D tensor.
|
323 |
+
if not shape:
|
324 |
+
raise TypeError('0d block_type is forbidden')
|
325 |
+
if isinstance(shape[0], constexpr):
|
326 |
+
shape = [s.value for s in shape]
|
327 |
+
|
328 |
+
self.shape = shape
|
329 |
+
self.numel = 1
|
330 |
+
for s in self.shape:
|
331 |
+
self.numel *= s
|
332 |
+
if self.numel > TRITON_MAX_TENSOR_NUMEL:
|
333 |
+
raise ValueError(f"numel ({self.numel}) exceeds triton maximum tensor numel ({TRITON_MAX_TENSOR_NUMEL})")
|
334 |
+
|
335 |
+
self.name = self.__str__()
|
336 |
+
|
337 |
+
def to_ir(self, builder: ir.builder) -> ir.block_type:
|
338 |
+
return builder.get_block_ty(self.element_ty.to_ir(builder), self.shape)
|
339 |
+
|
340 |
+
def __str__(self):
|
341 |
+
return f'<{self.shape}, {self.element_ty}>'
|
342 |
+
|
343 |
+
def __repr__(self):
|
344 |
+
return self.__str__()
|
345 |
+
|
346 |
+
def is_block(self):
|
347 |
+
return True
|
348 |
+
|
349 |
+
def get_block_shapes(self) -> List[int]:
|
350 |
+
return self.shape
|
351 |
+
|
352 |
+
def __eq__(self, other: block_type) -> bool:
|
353 |
+
if not isinstance(other, block_type):
|
354 |
+
return False
|
355 |
+
return self.element_ty == other.element_ty and self.shape == other.shape
|
356 |
+
|
357 |
+
def __ne__(self, other: block_type) -> bool:
|
358 |
+
return not self.__eq__(other)
|
359 |
+
|
360 |
+
@property
|
361 |
+
def scalar(self):
|
362 |
+
return self.element_ty
|
363 |
+
|
364 |
+
|
365 |
+
class function_type(dtype):
|
366 |
+
|
367 |
+
def __init__(self, ret_types: List[dtype], param_types: List[dtype]) -> None:
|
368 |
+
self.ret_types = ret_types
|
369 |
+
self.param_types = param_types
|
370 |
+
|
371 |
+
def __str__(self):
|
372 |
+
return f'fn ({self.param_types}) -> {self.ret_types}'
|
373 |
+
|
374 |
+
def to_ir(self, builder: ir.builder):
|
375 |
+
ir_param_types = [ty.to_ir(builder) for ty in self.param_types]
|
376 |
+
ret_types = [ret_type.to_ir(builder) for ret_type in self.ret_types]
|
377 |
+
return builder.get_function_ty(ir_param_types, ret_types)
|
378 |
+
|
379 |
+
|
380 |
+
# scalar types
|
381 |
+
void = dtype('void')
|
382 |
+
int1 = dtype('int1')
|
383 |
+
int8 = dtype('int8')
|
384 |
+
int16 = dtype('int16')
|
385 |
+
int32 = dtype('int32')
|
386 |
+
int64 = dtype('int64')
|
387 |
+
uint8 = dtype('uint8')
|
388 |
+
uint16 = dtype('uint16')
|
389 |
+
uint32 = dtype('uint32')
|
390 |
+
uint64 = dtype('uint64')
|
391 |
+
float8e5 = dtype('fp8e5')
|
392 |
+
float8e4nv = dtype('fp8e4nv')
|
393 |
+
float8e4b15 = dtype('fp8e4b15')
|
394 |
+
float8e4b15x4 = dtype('fp8e4b15x4')
|
395 |
+
float16 = dtype('fp16')
|
396 |
+
bfloat16 = dtype('bf16')
|
397 |
+
float32 = dtype('fp32')
|
398 |
+
float64 = dtype('fp64')
|
399 |
+
# pointer types
|
400 |
+
pi32_t = pointer_type(int32)
|
401 |
+
|
402 |
+
# -----------------------
|
403 |
+
# constexpr
|
404 |
+
# -----------------------
|
405 |
+
|
406 |
+
|
407 |
+
class constexpr:
|
408 |
+
"""
|
409 |
+
This class is used to store a value that is known at compile-time.
|
410 |
+
"""
|
411 |
+
|
412 |
+
def __init__(self, value):
|
413 |
+
if isinstance(value, constexpr):
|
414 |
+
self.value = value.value
|
415 |
+
else:
|
416 |
+
self.value = value
|
417 |
+
|
418 |
+
def __repr__(self) -> str:
|
419 |
+
return f"constexpr[{self.value}]"
|
420 |
+
|
421 |
+
def __index__(self):
|
422 |
+
return self.value
|
423 |
+
|
424 |
+
def __add__(self, other):
|
425 |
+
return constexpr(self.value + other.value)
|
426 |
+
|
427 |
+
def __radd__(self, other):
|
428 |
+
return constexpr(other.value + self.value)
|
429 |
+
|
430 |
+
def __sub__(self, other):
|
431 |
+
return constexpr(self.value - other.value)
|
432 |
+
|
433 |
+
def __rsub__(self, other):
|
434 |
+
return constexpr(other.value - self.value)
|
435 |
+
|
436 |
+
def __mul__(self, other):
|
437 |
+
return constexpr(self.value * other.value)
|
438 |
+
|
439 |
+
def __mod__(self, other):
|
440 |
+
return constexpr(self.value % other.value)
|
441 |
+
|
442 |
+
def __rmul__(self, other):
|
443 |
+
return constexpr(other.value * self.value)
|
444 |
+
|
445 |
+
def __truediv__(self, other):
|
446 |
+
return constexpr(self.value / other.value)
|
447 |
+
|
448 |
+
def __rtruediv__(self, other):
|
449 |
+
return constexpr(other.value / self.value)
|
450 |
+
|
451 |
+
def __floordiv__(self, other):
|
452 |
+
return constexpr(self.value // other.value)
|
453 |
+
|
454 |
+
def __rfloordiv__(self, other):
|
455 |
+
return constexpr(other.value // self.value)
|
456 |
+
|
457 |
+
def __gt__(self, other):
|
458 |
+
return constexpr(self.value > other.value)
|
459 |
+
|
460 |
+
def __rgt__(self, other):
|
461 |
+
return constexpr(other.value > self.value)
|
462 |
+
|
463 |
+
def __ge__(self, other):
|
464 |
+
return constexpr(self.value >= other.value)
|
465 |
+
|
466 |
+
def __rge__(self, other):
|
467 |
+
return constexpr(other.value >= self.value)
|
468 |
+
|
469 |
+
def __lt__(self, other):
|
470 |
+
return constexpr(self.value < other.value)
|
471 |
+
|
472 |
+
def __rlt__(self, other):
|
473 |
+
return constexpr(other.value < self.value)
|
474 |
+
|
475 |
+
def __le__(self, other):
|
476 |
+
return constexpr(self.value <= other.value)
|
477 |
+
|
478 |
+
def __rle__(self, other):
|
479 |
+
return constexpr(other.value <= self.value)
|
480 |
+
|
481 |
+
def __eq__(self, other):
|
482 |
+
return constexpr(self.value == other.value)
|
483 |
+
|
484 |
+
def __ne__(self, other):
|
485 |
+
return constexpr(self.value != other.value)
|
486 |
+
|
487 |
+
def __bool__(self):
|
488 |
+
return bool(self.value)
|
489 |
+
|
490 |
+
def __neg__(self):
|
491 |
+
return constexpr(-self.value)
|
492 |
+
|
493 |
+
def __and__(self, other):
|
494 |
+
return constexpr(self.value & other.value)
|
495 |
+
|
496 |
+
def logical_and(self, other):
|
497 |
+
return constexpr(self.value and other.value)
|
498 |
+
|
499 |
+
def __or__(self, other):
|
500 |
+
return constexpr(self.value | other.value)
|
501 |
+
|
502 |
+
def __xor__(self, other):
|
503 |
+
return constexpr(self.value ^ other.value)
|
504 |
+
|
505 |
+
def logical_or(self, other):
|
506 |
+
return constexpr(self.value or other.value)
|
507 |
+
|
508 |
+
def __pos__(self):
|
509 |
+
return constexpr(+self.value)
|
510 |
+
|
511 |
+
def __invert__(self):
|
512 |
+
return constexpr(~self.value)
|
513 |
+
|
514 |
+
def __pow__(self, other):
|
515 |
+
return constexpr(self.value**other.value)
|
516 |
+
|
517 |
+
def __rshift__(self, other):
|
518 |
+
return constexpr(self.value >> other.value)
|
519 |
+
|
520 |
+
def __lshift__(self, other):
|
521 |
+
return constexpr(self.value << other.value)
|
522 |
+
|
523 |
+
def __not__(self):
|
524 |
+
return constexpr(not self.value)
|
525 |
+
|
526 |
+
def __call__(self, *args, **kwds):
|
527 |
+
return self.value(*args, **kwds)
|
528 |
+
|
529 |
+
|
530 |
+
class tensor:
|
531 |
+
|
532 |
+
def __init__(self, handle, type: dtype):
|
533 |
+
# IR handle
|
534 |
+
self.handle = handle
|
535 |
+
# Block shape
|
536 |
+
self.shape = type.shape if type.is_block() else ()
|
537 |
+
self.numel = 1
|
538 |
+
for s in self.shape:
|
539 |
+
self.numel *= s
|
540 |
+
self.numel = constexpr(self.numel)
|
541 |
+
self.type = type # Tensor type (can be block_type)
|
542 |
+
# Following the practice in pytorch, dtype is scalar type
|
543 |
+
self.dtype = type.scalar
|
544 |
+
self.shape = [constexpr(s) for s in self.shape]
|
545 |
+
|
546 |
+
def __str__(self) -> str:
|
547 |
+
# ex. "float32[16, 32]"
|
548 |
+
return str(self.dtype) + '[' + ', '.join(str(s) for s in self.shape) + ']'
|
549 |
+
|
550 |
+
@builtin
|
551 |
+
def __add__(self, other, _builder=None):
|
552 |
+
other = _to_tensor(other, _builder)
|
553 |
+
return semantic.add(self, other, _builder)
|
554 |
+
|
555 |
+
@builtin
|
556 |
+
def __radd__(self, other, _builder=None):
|
557 |
+
return self.__add__(other, _builder=_builder)
|
558 |
+
|
559 |
+
@builtin
|
560 |
+
def __sub__(self, other, _builder=None):
|
561 |
+
other = _to_tensor(other, _builder)
|
562 |
+
return semantic.sub(self, other, _builder)
|
563 |
+
|
564 |
+
@builtin
|
565 |
+
def __rsub__(self, other, _builder=None):
|
566 |
+
other = _to_tensor(other, _builder)
|
567 |
+
return semantic.sub(other, self, _builder)
|
568 |
+
|
569 |
+
@builtin
|
570 |
+
def __mul__(self, other, _builder=None):
|
571 |
+
other = _to_tensor(other, _builder)
|
572 |
+
return semantic.mul(self, other, _builder)
|
573 |
+
|
574 |
+
@builtin
|
575 |
+
def __rmul__(self, other, _builder=None):
|
576 |
+
return self.__mul__(other, _builder=_builder)
|
577 |
+
|
578 |
+
@builtin
|
579 |
+
def __truediv__(self, other, _builder=None):
|
580 |
+
other = _to_tensor(other, _builder)
|
581 |
+
return semantic.truediv(self, other, _builder)
|
582 |
+
|
583 |
+
@builtin
|
584 |
+
def __rtruediv__(self, other, _builder=None):
|
585 |
+
other = _to_tensor(other, _builder)
|
586 |
+
return semantic.truediv(other, self, _builder)
|
587 |
+
|
588 |
+
@builtin
|
589 |
+
def __floordiv__(self, other, _builder=None):
|
590 |
+
other = _to_tensor(other, _builder)
|
591 |
+
return semantic.floordiv(self, other, _builder)
|
592 |
+
|
593 |
+
@builtin
|
594 |
+
def __rfloordiv__(self, other, _builder=None):
|
595 |
+
other = _to_tensor(other, _builder)
|
596 |
+
return semantic.floordiv(other, self, _builder)
|
597 |
+
|
598 |
+
@builtin
|
599 |
+
def __mod__(self, other, _builder=None):
|
600 |
+
other = _to_tensor(other, _builder)
|
601 |
+
return semantic.mod(self, other, _builder)
|
602 |
+
|
603 |
+
@builtin
|
604 |
+
def __rmod__(self, other, _builder=None):
|
605 |
+
other = _to_tensor(other, _builder)
|
606 |
+
return semantic.mod(other, self, _builder)
|
607 |
+
|
608 |
+
# unary operators
|
609 |
+
@builtin
|
610 |
+
def __neg__(self, _builder=None):
|
611 |
+
return semantic.minus(self, _builder)
|
612 |
+
|
613 |
+
@builtin
|
614 |
+
def __invert__(self, _builder=None):
|
615 |
+
return semantic.invert(self, _builder)
|
616 |
+
|
617 |
+
# bitwise operators
|
618 |
+
|
619 |
+
@builtin
|
620 |
+
def __and__(self, other, _builder=None):
|
621 |
+
other = _to_tensor(other, _builder)
|
622 |
+
return semantic.and_(self, other, _builder)
|
623 |
+
|
624 |
+
@builtin
|
625 |
+
def __rand__(self, other, _builder=None):
|
626 |
+
other = _to_tensor(other, _builder)
|
627 |
+
return semantic.and_(other, self, _builder)
|
628 |
+
|
629 |
+
@builtin
|
630 |
+
def __or__(self, other, _builder=None):
|
631 |
+
other = _to_tensor(other, _builder)
|
632 |
+
return semantic.or_(self, other, _builder)
|
633 |
+
|
634 |
+
@builtin
|
635 |
+
def __ror__(self, other, _builder=None):
|
636 |
+
other = _to_tensor(other, _builder)
|
637 |
+
return semantic.or_(other, self, _builder)
|
638 |
+
|
639 |
+
@builtin
|
640 |
+
def __xor__(self, other, _builder=None):
|
641 |
+
other = _to_tensor(other, _builder)
|
642 |
+
return semantic.xor_(self, other, _builder)
|
643 |
+
|
644 |
+
@builtin
|
645 |
+
def __rxor__(self, other, _builder=None):
|
646 |
+
other = _to_tensor(other, _builder)
|
647 |
+
return semantic.xor_(other, self, _builder)
|
648 |
+
|
649 |
+
@builtin
|
650 |
+
def __lshift__(self, other, _builder=None):
|
651 |
+
other = _to_tensor(other, _builder)
|
652 |
+
return semantic.shl(self, other, _builder)
|
653 |
+
|
654 |
+
@builtin
|
655 |
+
def __rlshift__(self, other, _builder=None):
|
656 |
+
other = _to_tensor(other, _builder)
|
657 |
+
return semantic.shl(other, self, _builder)
|
658 |
+
|
659 |
+
@builtin
|
660 |
+
def __rshift__(self, other, _builder=None):
|
661 |
+
other = _to_tensor(other, _builder)
|
662 |
+
if self.dtype.is_int_signed():
|
663 |
+
return semantic.ashr(self, other, _builder)
|
664 |
+
else:
|
665 |
+
return semantic.lshr(self, other, _builder)
|
666 |
+
|
667 |
+
@builtin
|
668 |
+
def __rrshift__(self, other, _builder=None):
|
669 |
+
other = _to_tensor(other, _builder)
|
670 |
+
if self.dtype.is_int_signed():
|
671 |
+
return semantic.ashr(other, self, _builder)
|
672 |
+
else:
|
673 |
+
return semantic.lshr(other, self, _builder)
|
674 |
+
|
675 |
+
# >
|
676 |
+
@builtin
|
677 |
+
def __gt__(self, other, _builder=None):
|
678 |
+
other = _to_tensor(other, _builder)
|
679 |
+
return semantic.greater_than(self, other, _builder)
|
680 |
+
|
681 |
+
@builtin
|
682 |
+
def __rgt__(self, other, _builder=None):
|
683 |
+
other = _to_tensor(other, _builder)
|
684 |
+
return semantic.greater_than(other, self, _builder)
|
685 |
+
|
686 |
+
# >=
|
687 |
+
@builtin
|
688 |
+
def __ge__(self, other, _builder=None):
|
689 |
+
other = _to_tensor(other, _builder)
|
690 |
+
return semantic.greater_equal(self, other, _builder)
|
691 |
+
|
692 |
+
@builtin
|
693 |
+
def __rge__(self, other, _builder=None):
|
694 |
+
other = _to_tensor(other, _builder)
|
695 |
+
return semantic.greater_equal(other, self, _builder)
|
696 |
+
|
697 |
+
# <
|
698 |
+
@builtin
|
699 |
+
def __lt__(self, other, _builder=None):
|
700 |
+
other = _to_tensor(other, _builder)
|
701 |
+
return semantic.less_than(self, other, _builder)
|
702 |
+
|
703 |
+
@builtin
|
704 |
+
def __rlt__(self, other, _builder=None):
|
705 |
+
other = _to_tensor(other, _builder)
|
706 |
+
return semantic.less_than(other, self, _builder)
|
707 |
+
|
708 |
+
# <=
|
709 |
+
@builtin
|
710 |
+
def __le__(self, other, _builder=None):
|
711 |
+
other = _to_tensor(other, _builder)
|
712 |
+
return semantic.less_equal(self, other, _builder)
|
713 |
+
|
714 |
+
@builtin
|
715 |
+
def __rle__(self, other, _builder=None):
|
716 |
+
other = _to_tensor(other, _builder)
|
717 |
+
return semantic.less_equal(other, self, _builder)
|
718 |
+
|
719 |
+
# ==
|
720 |
+
@builtin
|
721 |
+
def __eq__(self, other, _builder=None):
|
722 |
+
other = _to_tensor(other, _builder)
|
723 |
+
return semantic.equal(self, other, _builder)
|
724 |
+
|
725 |
+
@builtin
|
726 |
+
def __req__(self, other, _builder=None):
|
727 |
+
other = _to_tensor(other, _builder)
|
728 |
+
return semantic.equal(other, self, _builder)
|
729 |
+
|
730 |
+
@builtin
|
731 |
+
def __ne__(self, other, _builder=None):
|
732 |
+
other = _to_tensor(other, _builder)
|
733 |
+
return semantic.not_equal(self, other, _builder)
|
734 |
+
|
735 |
+
@builtin
|
736 |
+
def __rne__(self, other, _builder=None):
|
737 |
+
other = _to_tensor(other, _builder)
|
738 |
+
return semantic.not_equal(other, self, _builder)
|
739 |
+
|
740 |
+
@builtin
|
741 |
+
def logical_and(self, other, _builder=None):
|
742 |
+
other = _to_tensor(other, _builder)
|
743 |
+
return semantic.logical_and(self, other, _builder)
|
744 |
+
|
745 |
+
@builtin
|
746 |
+
def logical_or(self, other, _builder=None):
|
747 |
+
other = _to_tensor(other, _builder)
|
748 |
+
return semantic.logical_or(self, other, _builder)
|
749 |
+
|
750 |
+
# note: __not__ isn't actually a magic method in python
|
751 |
+
# but it's ok because our ASTVisitor handles it
|
752 |
+
@builtin
|
753 |
+
def __not__(self, _builder=None):
|
754 |
+
return semantic.not_(self, _builder)
|
755 |
+
|
756 |
+
@builtin
|
757 |
+
def __getitem__(self, slices, _builder=None):
|
758 |
+
if isinstance(slices, (slice, constexpr)):
|
759 |
+
slices = [slices]
|
760 |
+
ret = self
|
761 |
+
for dim, sl in enumerate(slices):
|
762 |
+
if sl is None or isinstance(sl, constexpr) and sl.value is None:
|
763 |
+
ret = semantic.expand_dims(ret, dim, _builder)
|
764 |
+
elif isinstance(sl, slice) and sl.start is None and sl.stop is None and sl.step is None:
|
765 |
+
pass
|
766 |
+
else:
|
767 |
+
assert False, f"unsupported tensor index: {sl}"
|
768 |
+
return ret
|
769 |
+
|
770 |
+
@property
|
771 |
+
def T(self):
|
772 |
+
assert False, "Transposition must be created by the AST Visitor"
|
773 |
+
|
774 |
+
@builtin
|
775 |
+
def to(self, dtype, bitcast=False, _builder=None):
|
776 |
+
if isinstance(bitcast, constexpr):
|
777 |
+
bitcast = bitcast.value
|
778 |
+
if bitcast:
|
779 |
+
return semantic.bitcast(self, dtype, _builder)
|
780 |
+
return semantic.cast(self, dtype, _builder)
|
781 |
+
|
782 |
+
|
783 |
+
# -----------------------
|
784 |
+
# SPMD Programming Model
|
785 |
+
# -----------------------
|
786 |
+
def _constexpr_to_value(v):
|
787 |
+
if isinstance(v, constexpr):
|
788 |
+
return v.value
|
789 |
+
return v
|
790 |
+
|
791 |
+
|
792 |
+
@builtin
|
793 |
+
def program_id(axis, _builder=None):
|
794 |
+
"""
|
795 |
+
Returns the id of the current program instance along the given :code:`axis`.
|
796 |
+
|
797 |
+
:param axis: The axis of the 3D launch grid. Has to be either 0, 1 or 2.
|
798 |
+
:type axis: int
|
799 |
+
"""
|
800 |
+
# if axis == -1:
|
801 |
+
# pid0 = program_id(0, _builder)
|
802 |
+
# pid1 = program_id(1, _builder)
|
803 |
+
# pid2 = program_id(2, _builder)
|
804 |
+
# npg0 = num_programs(0, _builder)
|
805 |
+
# npg1 = num_programs(0, _builder)
|
806 |
+
# return pid0 + pid1*npg0 + pid2*npg0*npg1
|
807 |
+
axis = _constexpr_to_value(axis)
|
808 |
+
return semantic.program_id(axis, _builder)
|
809 |
+
|
810 |
+
|
811 |
+
@builtin
|
812 |
+
def num_programs(axis, _builder=None):
|
813 |
+
"""
|
814 |
+
Returns the number of program instances launched along the given :code:`axis`.
|
815 |
+
|
816 |
+
:param axis: The axis of the 3D launch grid. Has to be either 0, 1 or 2.
|
817 |
+
:type axis: int
|
818 |
+
"""
|
819 |
+
axis = _constexpr_to_value(axis)
|
820 |
+
return semantic.num_programs(axis, _builder)
|
821 |
+
|
822 |
+
|
823 |
+
# -----------------------
|
824 |
+
# Block Initialization
|
825 |
+
# -----------------------
|
826 |
+
|
827 |
+
|
828 |
+
@builtin
|
829 |
+
def arange(start, end, _builder=None):
|
830 |
+
"""
|
831 |
+
Returns contiguous values within the left-closed and right-open interval [:code:`start`, :code:`end`). \
|
832 |
+
End - Start must be less than or equal to TRITON_MAX_TENSOR_NUMEL = 131072
|
833 |
+
|
834 |
+
:param start: Start of the interval. Must be a power of two.
|
835 |
+
:type start: int32
|
836 |
+
:param end: End of the interval. Must be a power of two > start.
|
837 |
+
:type end: int32
|
838 |
+
"""
|
839 |
+
start = _constexpr_to_value(start)
|
840 |
+
end = _constexpr_to_value(end)
|
841 |
+
return semantic.arange(start, end, _builder)
|
842 |
+
|
843 |
+
|
844 |
+
def _shape_check_impl(shape):
|
845 |
+
shape = _constexpr_to_value(shape)
|
846 |
+
for i, d in enumerate(shape):
|
847 |
+
if isinstance(d, int):
|
848 |
+
d = constexpr(d)
|
849 |
+
if not isinstance(d, constexpr):
|
850 |
+
raise TypeError(f"Shape element {i} must have type `constexpr`")
|
851 |
+
if not isinstance(d.value, int):
|
852 |
+
raise TypeError(f"Shape element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]")
|
853 |
+
return [_constexpr_to_value(x) for x in shape]
|
854 |
+
|
855 |
+
|
856 |
+
@builtin
|
857 |
+
def full(shape, value, dtype, _builder=None):
|
858 |
+
"""
|
859 |
+
Returns a tensor filled with the scalar value for the given :code:`shape` and :code:`dtype`.
|
860 |
+
|
861 |
+
:param shape: Shape of the new array, e.g., (8, 16) or (8, )
|
862 |
+
:value value: A scalar value to fill the array with
|
863 |
+
:type shape: tuple of ints
|
864 |
+
:param dtype: Data-type of the new array, e.g., :code:`tl.float16`
|
865 |
+
:type dtype: DType
|
866 |
+
"""
|
867 |
+
shape = _shape_check_impl(shape)
|
868 |
+
value = _constexpr_to_value(value)
|
869 |
+
dtype = _constexpr_to_value(dtype)
|
870 |
+
return semantic.full(shape, value, dtype, _builder)
|
871 |
+
|
872 |
+
|
873 |
+
# -----------------------
|
874 |
+
# Shape Manipulation
|
875 |
+
# -----------------------
|
876 |
+
|
877 |
+
|
878 |
+
@builtin
|
879 |
+
def broadcast(input, other, _builder=None):
|
880 |
+
"""
|
881 |
+
Tries to broadcast the two given blocks to a common compatible shape.
|
882 |
+
|
883 |
+
:param input: The first input tensor.
|
884 |
+
:type input: Block
|
885 |
+
:param other: The second input tensor.
|
886 |
+
:type other: Block
|
887 |
+
"""
|
888 |
+
return semantic.broadcast_impl_value(input, other, _builder)
|
889 |
+
|
890 |
+
|
891 |
+
@builtin
|
892 |
+
def broadcast_to(input, shape, _builder=None):
|
893 |
+
"""
|
894 |
+
Tries to broadcast the given tensor to a new :code:`shape`.
|
895 |
+
|
896 |
+
:param input: The input tensor.
|
897 |
+
:type input: Block
|
898 |
+
:param shape: The desired shape.
|
899 |
+
:type shape: Tuple[int]
|
900 |
+
"""
|
901 |
+
shape = _shape_check_impl(shape)
|
902 |
+
return semantic.broadcast_impl_shape(input, shape, _builder)
|
903 |
+
|
904 |
+
|
905 |
+
@builtin
|
906 |
+
def trans(input, _builder=None):
|
907 |
+
"""
|
908 |
+
Returns a transposed tensor.
|
909 |
+
|
910 |
+
:param input: The input tensor.
|
911 |
+
:type input:
|
912 |
+
"""
|
913 |
+
return semantic.trans(input, _builder)
|
914 |
+
|
915 |
+
|
916 |
+
@builtin
|
917 |
+
def cat(input, other, can_reorder=False, _builder=None):
|
918 |
+
"""
|
919 |
+
Concatenate the given blocks
|
920 |
+
|
921 |
+
:param input: The first input tensor.
|
922 |
+
:type input:
|
923 |
+
:param other: The second input tensor.
|
924 |
+
:type other:
|
925 |
+
:param reorder: Compiler hint. If true, the compiler is
|
926 |
+
allowed to reorder elements while concatenating inputs. Only use if the
|
927 |
+
order does not matter (e.g., result is only used in reduction ops)
|
928 |
+
"""
|
929 |
+
return semantic.cat(input, other, can_reorder, _builder)
|
930 |
+
|
931 |
+
|
932 |
+
@builtin
|
933 |
+
def view(input, shape, _builder=None):
|
934 |
+
"""
|
935 |
+
Returns a tensor with the same elements as `input` but a different shape.
|
936 |
+
The order of the elements may not be preserved.
|
937 |
+
|
938 |
+
:param input: The input tensor.
|
939 |
+
:type input:
|
940 |
+
:param shape: The desired shape.
|
941 |
+
:type shape: Tuple[int]
|
942 |
+
|
943 |
+
"""
|
944 |
+
shape = _shape_check_impl(shape)
|
945 |
+
return semantic.view(input, shape, _builder)
|
946 |
+
|
947 |
+
|
948 |
+
@builtin
|
949 |
+
def reshape(input, shape, _builder=None):
|
950 |
+
"""
|
951 |
+
Returns a tensor with the same number of elements as input but with the
|
952 |
+
provided shape.
|
953 |
+
|
954 |
+
:param input: The input tensor.
|
955 |
+
:type input:
|
956 |
+
:param shape: The new shape.
|
957 |
+
:type shape: Tuple[int]
|
958 |
+
"""
|
959 |
+
shape = _shape_check_impl(shape)
|
960 |
+
return semantic.reshape(input, shape, _builder)
|
961 |
+
|
962 |
+
|
963 |
+
def _wrap_axis(axis, ndim):
|
964 |
+
if not (-ndim <= axis < ndim):
|
965 |
+
raise ValueError(f"invalid axis {axis}. Expected {-ndim} <= axis < {ndim}")
|
966 |
+
|
967 |
+
return axis if axis >= 0 else axis + ndim
|
968 |
+
|
969 |
+
|
970 |
+
@builtin
|
971 |
+
def expand_dims(input, axis, _builder=None):
|
972 |
+
"""
|
973 |
+
Expand the shape of a tensor, by inserting new length-1 dimensions.
|
974 |
+
|
975 |
+
Axis indices are with respect to the resulting tensor, so
|
976 |
+
``result.shape[axis]`` will be 1 for each axis.
|
977 |
+
|
978 |
+
:param input: The input tensor.
|
979 |
+
:type input: tl.tensor
|
980 |
+
:param axis: The indices to add new axes
|
981 |
+
:type axis: int | Sequence[int]
|
982 |
+
|
983 |
+
"""
|
984 |
+
axis = _constexpr_to_value(axis)
|
985 |
+
axes = list(axis) if isinstance(axis, Sequence) else [axis]
|
986 |
+
new_ndim = len(input.shape) + len(axes)
|
987 |
+
axes = [_wrap_axis(_constexpr_to_value(d), new_ndim) for d in axes]
|
988 |
+
|
989 |
+
if len(set(axes)) != len(axes):
|
990 |
+
raise ValueError(f"expand_dims recieved duplicate axes, normalized axes = {axes}")
|
991 |
+
|
992 |
+
ret = input
|
993 |
+
for a in sorted(axes):
|
994 |
+
ret = semantic.expand_dims(ret, a, _builder)
|
995 |
+
return ret
|
996 |
+
|
997 |
+
|
998 |
+
# -----------------------
|
999 |
+
# Linear Algebra
|
1000 |
+
# -----------------------
|
1001 |
+
|
1002 |
+
|
1003 |
+
@builtin
|
1004 |
+
def dot(input, other, acc=None, allow_tf32=True, max_num_imprecise_acc=None, out_dtype=float32, _builder=None):
|
1005 |
+
"""
|
1006 |
+
Returns the matrix product of two blocks.
|
1007 |
+
|
1008 |
+
The two blocks must be two-dimensional and have compatible inner dimensions.
|
1009 |
+
|
1010 |
+
:param input: The first tensor to be multiplied.
|
1011 |
+
:type input: 2D tensor of scalar-type in {:code:`float16`, :code:`bfloat16`, :code:`float32`}
|
1012 |
+
:param other: The second tensor to be multiplied.
|
1013 |
+
:type other: 2D tensor of scalar-type in {:code:`float16`, :code:`bfloat16`, :code:`float32`}
|
1014 |
+
"""
|
1015 |
+
allow_tf32 = _constexpr_to_value(allow_tf32)
|
1016 |
+
out_dtype = _constexpr_to_value(out_dtype)
|
1017 |
+
max_num_imprecise_acc = _constexpr_to_value(max_num_imprecise_acc)
|
1018 |
+
return semantic.dot(input, other, acc, allow_tf32, max_num_imprecise_acc, out_dtype, _builder)
|
1019 |
+
|
1020 |
+
|
1021 |
+
# -----------------------
|
1022 |
+
# Non-Atomic Memory Operations
|
1023 |
+
# -----------------------
|
1024 |
+
|
1025 |
+
|
1026 |
+
@builtin
|
1027 |
+
def load(pointer, mask=None, other=None, boundary_check=tuple(), padding_option="", cache_modifier="",
|
1028 |
+
eviction_policy="", volatile=False, _builder=None):
|
1029 |
+
"""
|
1030 |
+
Return a tensor of data whose values are loaded from memory at location defined by `pointer`:
|
1031 |
+
(1) `pointer` could be a single element pointer, then a scalar will be loaded
|
1032 |
+
|
1033 |
+
- `mask` and `other` must be scalar too
|
1034 |
+
- `other` is implicitly typecast to `pointer.dtype.element_ty`
|
1035 |
+
- `boundary_check` and `padding_option` must be empty
|
1036 |
+
|
1037 |
+
(2) `pointer` could be element-wise tensor of pointers, in which case:
|
1038 |
+
|
1039 |
+
- `mask` and `other` are implicitly broadcast to `pointer.shape`
|
1040 |
+
- `other` is implicitly typecast to `pointer.dtype.element_ty`
|
1041 |
+
- `boundary_check` and `padding_option` must be empty
|
1042 |
+
|
1043 |
+
(3) `pointer` could be a block pointer defined by `make_block_ptr`, in which case:
|
1044 |
+
|
1045 |
+
- `mask` and `other` must be None
|
1046 |
+
- `boundary_check` and `padding_option` can be specified to control the behavior of out-of-bound access
|
1047 |
+
|
1048 |
+
:param pointer: Pointer to the data to be loaded
|
1049 |
+
:type pointer: `triton.PointerType`, or block of `dtype=triton.PointerType`
|
1050 |
+
:param mask: if `mask[idx]` is false, do not load the data at address `pointer[idx]`
|
1051 |
+
(must be `None` with block pointers)
|
1052 |
+
:type mask: Block of `triton.int1`, optional
|
1053 |
+
:param other: if `mask[idx]` is false, return `other[idx]`
|
1054 |
+
:type other: Block, optional
|
1055 |
+
:param boundary_check: tuple of integers, indicating the dimensions which should do the boundary check
|
1056 |
+
:type boundary_check: tuple of ints, optional
|
1057 |
+
:param padding_option: should be one of {"", "zero", "nan"}, do padding while out of bound
|
1058 |
+
:param cache_modifier: changes cache option in NVIDIA PTX
|
1059 |
+
:type cache_modifier: str, optional
|
1060 |
+
:param eviction_policy: changes eviction policy in NVIDIA PTX
|
1061 |
+
:type eviction_policy: str, optional
|
1062 |
+
:param volatile: changes volatile option in NVIDIA PTX
|
1063 |
+
:type volatile: bool, optional
|
1064 |
+
"""
|
1065 |
+
# `mask` and `other` can be constexpr
|
1066 |
+
if _constexpr_to_value(mask) is not None:
|
1067 |
+
mask = _to_tensor(mask, _builder)
|
1068 |
+
if _constexpr_to_value(other) is not None:
|
1069 |
+
other = _to_tensor(other, _builder)
|
1070 |
+
padding_option = _constexpr_to_value(padding_option)
|
1071 |
+
cache_modifier = _constexpr_to_value(cache_modifier)
|
1072 |
+
eviction_policy = _constexpr_to_value(eviction_policy)
|
1073 |
+
volatile = _constexpr_to_value(volatile)
|
1074 |
+
return semantic.load(pointer, mask, other, boundary_check, padding_option, cache_modifier, eviction_policy,
|
1075 |
+
volatile, _builder)
|
1076 |
+
|
1077 |
+
|
1078 |
+
@builtin
|
1079 |
+
def store(pointer, value, mask=None, boundary_check=(), cache_modifier="", eviction_policy="", _builder=None):
|
1080 |
+
"""
|
1081 |
+
Store a tensor of data into memory locations defined by `pointer`:
|
1082 |
+
(1) `pointer` could be a single element pointer, then a scalar will be stored
|
1083 |
+
|
1084 |
+
- `mask` must be scalar too
|
1085 |
+
- `boundary_check` and `padding_option` must be empty
|
1086 |
+
|
1087 |
+
(2) `pointer` could be element-wise tensor of pointers, in which case:
|
1088 |
+
|
1089 |
+
- `mask` is implicitly broadcast to `pointer.shape`
|
1090 |
+
- `boundary_check` must be empty
|
1091 |
+
|
1092 |
+
(3) or `pointer` could be a block pointer defined by `make_block_ptr`, in which case:
|
1093 |
+
|
1094 |
+
- `mask` must be None
|
1095 |
+
- `boundary_check` can be specified to control the behavior of out-of-bound access
|
1096 |
+
|
1097 |
+
`value` is implicitly broadcast to `pointer.shape` and typecast to `pointer.dtype.element_ty`.
|
1098 |
+
|
1099 |
+
:param pointer: The memory location where the elements of `value` are stored
|
1100 |
+
:type pointer: `triton.PointerType`, or block of `dtype=triton.PointerType`
|
1101 |
+
:param value: The tensor of elements to be stored
|
1102 |
+
:type value: Block
|
1103 |
+
:param mask: If `mask[idx]` is false, do not store `value[idx]` at `pointer[idx]`
|
1104 |
+
:type mask: Block of triton.int1, optional
|
1105 |
+
:param boundary_check: tuple of integers, indicating the dimensions which should do the boundary check
|
1106 |
+
:type boundary_check: tuple of ints, optional
|
1107 |
+
:param cache_modifier: changes cache option in NVIDIA PTX
|
1108 |
+
:type cache_modifier: str, optional
|
1109 |
+
:param eviction_policy: changes eviction policy in NVIDIA PTX
|
1110 |
+
:type eviction_policy: str, optional
|
1111 |
+
"""
|
1112 |
+
# `value` can be constexpr
|
1113 |
+
value = _to_tensor(value, _builder)
|
1114 |
+
if _constexpr_to_value(mask) is not None:
|
1115 |
+
mask = _to_tensor(mask, _builder)
|
1116 |
+
cache_modifier = _constexpr_to_value(cache_modifier)
|
1117 |
+
eviction_policy = _constexpr_to_value(eviction_policy)
|
1118 |
+
return semantic.store(pointer, value, mask, boundary_check, cache_modifier, eviction_policy, _builder)
|
1119 |
+
|
1120 |
+
|
1121 |
+
@builtin
|
1122 |
+
def make_block_ptr(base: tensor, shape, strides, offsets, block_shape, order, _builder=None):
|
1123 |
+
"""
|
1124 |
+
Returns a pointer to a block in a parent tensor
|
1125 |
+
|
1126 |
+
:param base: The base pointer to the parent tensor
|
1127 |
+
:param shape: The shape of the parent tensor
|
1128 |
+
:param strides: The strides of the parent tensor
|
1129 |
+
:param offsets: The offsets to the block
|
1130 |
+
:param block_shape: The shape of the block
|
1131 |
+
:param order: The order of the original data format
|
1132 |
+
"""
|
1133 |
+
return semantic.make_block_ptr(base, shape, strides, offsets, block_shape, order, _builder)
|
1134 |
+
|
1135 |
+
|
1136 |
+
@builtin
|
1137 |
+
def advance(base: tensor, offsets, _builder=None):
|
1138 |
+
"""
|
1139 |
+
Advance a block pointer
|
1140 |
+
|
1141 |
+
:param base: the block pointer to advance
|
1142 |
+
:param offsets: the offsets to advance, a tuple by dimension
|
1143 |
+
"""
|
1144 |
+
return semantic.advance(base, offsets, _builder)
|
1145 |
+
|
1146 |
+
|
1147 |
+
# -----------------------
|
1148 |
+
# Atomic Memory Operations
|
1149 |
+
# -----------------------
|
1150 |
+
|
1151 |
+
|
1152 |
+
def _add_atomic_docstr(name: str, has_cmp: bool = False) -> Callable[[T], T]:
|
1153 |
+
|
1154 |
+
def _decorator(func: T) -> T:
|
1155 |
+
docstr = f"""
|
1156 |
+
Performs an atomic {name} at the memory location specified by :code:`pointer`.
|
1157 |
+
|
1158 |
+
Return the data stored at :code:`pointer` before the atomic operation.
|
1159 |
+
|
1160 |
+
:param pointer: The memory locations to operate on
|
1161 |
+
:type pointer: Block of dtype=triton.PointerDType"""
|
1162 |
+
if has_cmp:
|
1163 |
+
docstr += """
|
1164 |
+
:param cmp: The values expected to be found in the atomic object
|
1165 |
+
:type cmp: Block of dtype=pointer.dtype.element_ty"""
|
1166 |
+
docstr += """
|
1167 |
+
:param val: The values with which to perform the atomic operation
|
1168 |
+
:type val: Block of dtype=pointer.dtype.element_ty
|
1169 |
+
:param sem: Memory semantics to use ("ACQUIRE_RELEASE" (default),
|
1170 |
+
"ACQUIRE", "RELEASE", or "RELAXED")
|
1171 |
+
:type sem: str
|
1172 |
+
:param scope: Scope of threads that observe synchronizing effect of the
|
1173 |
+
atomic operation ("GPU" (default), "CTA", or "SYSTEM")
|
1174 |
+
:type scope: str
|
1175 |
+
"""
|
1176 |
+
func.__doc__ = docstr
|
1177 |
+
return func
|
1178 |
+
|
1179 |
+
return _decorator
|
1180 |
+
|
1181 |
+
|
1182 |
+
@builtin
|
1183 |
+
@_add_atomic_docstr("compare-and-swap", has_cmp=True)
|
1184 |
+
def atomic_cas(pointer, cmp, val, sem=None, scope=None, _builder=None):
|
1185 |
+
cmp = _to_tensor(cmp, _builder)
|
1186 |
+
val = _to_tensor(val, _builder)
|
1187 |
+
sem = _constexpr_to_value(sem)
|
1188 |
+
scope = _constexpr_to_value(scope)
|
1189 |
+
return semantic.atomic_cas(pointer, cmp, val, sem, scope, _builder)
|
1190 |
+
|
1191 |
+
|
1192 |
+
@builtin
|
1193 |
+
@_add_atomic_docstr("exchange")
|
1194 |
+
def atomic_xchg(pointer, val, mask=None, sem=None, scope=None, _builder=None):
|
1195 |
+
val = _to_tensor(val, _builder)
|
1196 |
+
sem = _constexpr_to_value(sem)
|
1197 |
+
scope = _constexpr_to_value(scope)
|
1198 |
+
return semantic.atomic_xchg(pointer, val, mask, sem, scope, _builder)
|
1199 |
+
|
1200 |
+
|
1201 |
+
@builtin
|
1202 |
+
@_add_atomic_docstr("add")
|
1203 |
+
def atomic_add(pointer, val, mask=None, sem=None, scope=None, _builder=None):
|
1204 |
+
val = _to_tensor(val, _builder)
|
1205 |
+
sem = _constexpr_to_value(sem)
|
1206 |
+
scope = _constexpr_to_value(scope)
|
1207 |
+
return semantic.atomic_add(pointer, val, mask, sem, scope, _builder)
|
1208 |
+
|
1209 |
+
|
1210 |
+
@builtin
|
1211 |
+
@_add_atomic_docstr("max")
|
1212 |
+
def atomic_max(pointer, val, mask=None, sem=None, scope=None, _builder=None):
|
1213 |
+
val = _to_tensor(val, _builder)
|
1214 |
+
sem = _constexpr_to_value(sem)
|
1215 |
+
scope = _constexpr_to_value(scope)
|
1216 |
+
return semantic.atomic_max(pointer, val, mask, sem, scope, _builder)
|
1217 |
+
|
1218 |
+
|
1219 |
+
@builtin
|
1220 |
+
@_add_atomic_docstr("min")
|
1221 |
+
def atomic_min(pointer, val, mask=None, sem=None, scope=None, _builder=None):
|
1222 |
+
val = _to_tensor(val, _builder)
|
1223 |
+
sem = _constexpr_to_value(sem)
|
1224 |
+
scope = _constexpr_to_value(scope)
|
1225 |
+
return semantic.atomic_min(pointer, val, mask, sem, scope, _builder)
|
1226 |
+
|
1227 |
+
|
1228 |
+
@builtin
|
1229 |
+
@_add_atomic_docstr("logical and")
|
1230 |
+
def atomic_and(pointer, val, mask=None, sem=None, scope=None, _builder=None):
|
1231 |
+
val = _to_tensor(val, _builder)
|
1232 |
+
sem = _constexpr_to_value(sem)
|
1233 |
+
scope = _constexpr_to_value(scope)
|
1234 |
+
return semantic.atomic_and(pointer, val, mask, sem, scope, _builder)
|
1235 |
+
|
1236 |
+
|
1237 |
+
@builtin
|
1238 |
+
@_add_atomic_docstr("logical or")
|
1239 |
+
def atomic_or(pointer, val, mask=None, sem=None, scope=None, _builder=None):
|
1240 |
+
val = _to_tensor(val, _builder)
|
1241 |
+
sem = _constexpr_to_value(sem)
|
1242 |
+
scope = _constexpr_to_value(scope)
|
1243 |
+
return semantic.atomic_or(pointer, val, mask, sem, scope, _builder)
|
1244 |
+
|
1245 |
+
|
1246 |
+
@builtin
|
1247 |
+
@_add_atomic_docstr("logical xor")
|
1248 |
+
def atomic_xor(pointer, val, mask=None, sem=None, scope=None, _builder=None):
|
1249 |
+
val = _to_tensor(val, _builder)
|
1250 |
+
sem = _constexpr_to_value(sem)
|
1251 |
+
scope = _constexpr_to_value(scope)
|
1252 |
+
return semantic.atomic_xor(pointer, val, mask, sem, scope, _builder)
|
1253 |
+
|
1254 |
+
|
1255 |
+
# -----------------------
|
1256 |
+
# Conditioning
|
1257 |
+
# -----------------------
|
1258 |
+
|
1259 |
+
|
1260 |
+
@builtin
|
1261 |
+
def where(condition, x, y, _builder=None):
|
1262 |
+
"""
|
1263 |
+
Returns a tensor of elements from either :code:`x` or :code:`y`, depending on :code:`condition`.
|
1264 |
+
|
1265 |
+
Note that :code:`x` and :code:`y` are always evaluated regardless of the value of :code:`condition`.
|
1266 |
+
|
1267 |
+
If you want to avoid unintended memory operations, use the :code:`mask` arguments in `triton.load` and `triton.store` instead.
|
1268 |
+
|
1269 |
+
The shape of :code:`x` and :code:`y` are both broadcast to the shape of :code:`condition`.
|
1270 |
+
:code:`x` and :code:`y` must have the same data type.
|
1271 |
+
|
1272 |
+
:param condition: When True (nonzero), yield x, otherwise yield y.
|
1273 |
+
:type condition: Block of triton.bool
|
1274 |
+
:param x: values selected at indices where condition is True.
|
1275 |
+
:param y: values selected at indices where condition is False.
|
1276 |
+
"""
|
1277 |
+
condition = _to_tensor(condition, _builder)
|
1278 |
+
x = _to_tensor(x, _builder)
|
1279 |
+
y = _to_tensor(y, _builder)
|
1280 |
+
return semantic.where(condition, x, y, _builder)
|
1281 |
+
|
1282 |
+
|
1283 |
+
# -----------------------
|
1284 |
+
# Math
|
1285 |
+
# -----------------------
|
1286 |
+
|
1287 |
+
|
1288 |
+
@builtin
|
1289 |
+
def umulhi(x, y, _builder=None):
|
1290 |
+
"""
|
1291 |
+
Returns the most significant 32 bits of the product of x and y.
|
1292 |
+
|
1293 |
+
:param x: the input tensor
|
1294 |
+
:type x: int32
|
1295 |
+
:param y: the input tensor
|
1296 |
+
:type y: int32
|
1297 |
+
"""
|
1298 |
+
x = _to_tensor(x, _builder)
|
1299 |
+
y = _to_tensor(y, _builder)
|
1300 |
+
return semantic.umulhi(x, y, _builder)
|
1301 |
+
|
1302 |
+
|
1303 |
+
@builtin
|
1304 |
+
def fdiv(x, y, ieee_rounding=False, _builder=None):
|
1305 |
+
"""
|
1306 |
+
Returns a floating-point resultant tensor of dividing x by y.
|
1307 |
+
|
1308 |
+
:param x: the input numerator value.
|
1309 |
+
:param y: the input denominator value.
|
1310 |
+
:param ieee_rounding: To follow IEEE-754 floating point number
|
1311 |
+
rounding mechanism
|
1312 |
+
:type ieee_rounding: bool
|
1313 |
+
"""
|
1314 |
+
ieee_rounding = _constexpr_to_value(ieee_rounding)
|
1315 |
+
x = _to_tensor(x, _builder)
|
1316 |
+
y = _to_tensor(y, _builder)
|
1317 |
+
return semantic.fdiv(x, y, ieee_rounding, _builder)
|
1318 |
+
|
1319 |
+
|
1320 |
+
def _add_math_1arg_docstr(name: str) -> Callable[[T], T]:
|
1321 |
+
|
1322 |
+
def _decorator(func: T) -> T:
|
1323 |
+
docstr = """
|
1324 |
+
Computes the element-wise {name} of :code:`x`.
|
1325 |
+
|
1326 |
+
:param x: the input values
|
1327 |
+
:type x: Block
|
1328 |
+
"""
|
1329 |
+
func.__doc__ = docstr.format(name=name)
|
1330 |
+
return func
|
1331 |
+
|
1332 |
+
return _decorator
|
1333 |
+
|
1334 |
+
|
1335 |
+
@builtin
|
1336 |
+
@_add_math_1arg_docstr("exponential")
|
1337 |
+
def exp(x, _builder=None):
|
1338 |
+
x = _to_tensor(x, _builder)
|
1339 |
+
return semantic.exp(x, _builder)
|
1340 |
+
|
1341 |
+
|
1342 |
+
@builtin
|
1343 |
+
@_add_math_1arg_docstr("natural logarithm")
|
1344 |
+
def log(x, _builder=None):
|
1345 |
+
x = _to_tensor(x, _builder)
|
1346 |
+
return semantic.log(x, _builder)
|
1347 |
+
|
1348 |
+
|
1349 |
+
@builtin
|
1350 |
+
@_add_math_1arg_docstr("cosine")
|
1351 |
+
def cos(x, _builder=None):
|
1352 |
+
x = _to_tensor(x, _builder)
|
1353 |
+
return semantic.cos(x, _builder)
|
1354 |
+
|
1355 |
+
|
1356 |
+
@builtin
|
1357 |
+
@_add_math_1arg_docstr("sine")
|
1358 |
+
def sin(x, _builder=None):
|
1359 |
+
x = _to_tensor(x, _builder)
|
1360 |
+
return semantic.sin(x, _builder)
|
1361 |
+
|
1362 |
+
|
1363 |
+
@builtin
|
1364 |
+
@_add_math_1arg_docstr("square root")
|
1365 |
+
def sqrt(x, _builder=None):
|
1366 |
+
x = _to_tensor(x, _builder)
|
1367 |
+
return semantic.sqrt(x, _builder)
|
1368 |
+
|
1369 |
+
|
1370 |
+
@builtin
|
1371 |
+
@_add_math_1arg_docstr("absolute value")
|
1372 |
+
def abs(x, _builder=None):
|
1373 |
+
x = _to_tensor(x, _builder)
|
1374 |
+
return semantic.abs(x, _builder)
|
1375 |
+
|
1376 |
+
|
1377 |
+
# -----------------------
|
1378 |
+
# Reductions
|
1379 |
+
# -----------------------
|
1380 |
+
|
1381 |
+
|
1382 |
+
def _add_reduction_docstr(name: str, return_indices_arg: str = None, tie_break_arg: str = None) -> Callable[[T], T]:
|
1383 |
+
|
1384 |
+
def _decorator(func: T) -> T:
|
1385 |
+
docstr = """
|
1386 |
+
Returns the {name} of all elements in the :code:`input` tensor along the provided :code:`axis`
|
1387 |
+
|
1388 |
+
:param input: the input values
|
1389 |
+
:param axis: the dimension along which the reduction should be done"""
|
1390 |
+
if return_indices_arg is not None:
|
1391 |
+
docstr += f"""
|
1392 |
+
:param {return_indices_arg}: if true, return index corresponding to the {name} value"""
|
1393 |
+
if tie_break_arg is not None:
|
1394 |
+
docstr += f"""
|
1395 |
+
:param {tie_break_arg}: if true, return the left-most indices in case of ties for values that aren't NaN"""
|
1396 |
+
|
1397 |
+
func.__doc__ = docstr.format(name=name)
|
1398 |
+
return func
|
1399 |
+
|
1400 |
+
return _decorator
|
1401 |
+
|
1402 |
+
|
1403 |
+
@contextmanager
|
1404 |
+
def _insertion_guard(builder):
|
1405 |
+
ip = builder.get_insertion_point()
|
1406 |
+
yield
|
1407 |
+
builder.restore_insertion_point(ip)
|
1408 |
+
|
1409 |
+
|
1410 |
+
@builtin
|
1411 |
+
def reduce(input, axis, combine_fn, _builder=None, _generator=None):
|
1412 |
+
"""Applies the combine_fn to all elements in :code:`input` tensors along the provided :code:`axis`
|
1413 |
+
|
1414 |
+
:param input: the input tensor, or tuple of tensors
|
1415 |
+
:param axis: the dimension along which the reduction should be done
|
1416 |
+
:param combine_fn: a function to combine two groups of scalar tensors (must be marked with @triton.jit)
|
1417 |
+
|
1418 |
+
"""
|
1419 |
+
if isinstance(input, tensor):
|
1420 |
+
return reduce((input, ), axis, combine_fn, _builder=_builder, _generator=_generator)[0]
|
1421 |
+
|
1422 |
+
def make_combine_region(reduce_op):
|
1423 |
+
in_scalar_tys = [t.type.scalar for t in input]
|
1424 |
+
prototype = function_type(in_scalar_tys, in_scalar_tys * 2)
|
1425 |
+
|
1426 |
+
region = reduce_op.get_region(0)
|
1427 |
+
with _insertion_guard(_builder):
|
1428 |
+
param_types = [ty.to_ir(_builder) for ty in prototype.param_types]
|
1429 |
+
block = _builder.create_block_with_parent(region, param_types)
|
1430 |
+
args = [tensor(block.arg(i), ty) for i, ty in enumerate(prototype.param_types)]
|
1431 |
+
results = _generator.call_JitFunction(combine_fn, args, kwargs={})
|
1432 |
+
if isinstance(results, tensor):
|
1433 |
+
handles = [results.handle]
|
1434 |
+
else:
|
1435 |
+
handles = [r.handle for r in results]
|
1436 |
+
_builder.create_reduce_ret(*handles)
|
1437 |
+
|
1438 |
+
if axis is not None:
|
1439 |
+
axis = _constexpr_to_value(axis)
|
1440 |
+
return semantic.reduction(input, axis, make_combine_region, _builder)
|
1441 |
+
|
1442 |
+
|
1443 |
+
@builtin
|
1444 |
+
def _promote_reduction_input(t, _builder=None):
|
1445 |
+
scalar_ty = t.type.scalar
|
1446 |
+
|
1447 |
+
# hardware doesn't support FMAX, FMIN, CMP for bfloat16
|
1448 |
+
if scalar_ty is bfloat16:
|
1449 |
+
return t.to(float32, _builder=_builder)
|
1450 |
+
|
1451 |
+
return t
|
1452 |
+
|
1453 |
+
|
1454 |
+
@builtin
|
1455 |
+
def _reduce_with_indices(input, axis, combine_fn, _builder=None, _generator=None):
|
1456 |
+
axis = _constexpr_to_value(axis)
|
1457 |
+
n = input.shape[axis]
|
1458 |
+
index = arange(0, n, _builder=_builder)
|
1459 |
+
|
1460 |
+
if len(input.shape) > 1:
|
1461 |
+
# Broadcast index across the non-reduced axes
|
1462 |
+
axes_to_expand = [constexpr(d) for d in range(len(input.shape))]
|
1463 |
+
del axes_to_expand[axis]
|
1464 |
+
index = expand_dims(index, axes_to_expand, _builder=_builder)
|
1465 |
+
index = broadcast_to(index, input.shape, _builder=_builder)
|
1466 |
+
|
1467 |
+
rvalue, rindices = reduce((input, index), axis, combine_fn, _builder=_builder, _generator=_generator)
|
1468 |
+
return rvalue, rindices
|
1469 |
+
|
1470 |
+
|
1471 |
+
# -----------------------
|
1472 |
+
# Scans
|
1473 |
+
# -----------------------
|
1474 |
+
|
1475 |
+
|
1476 |
+
def _add_scan_docstr(name: str, return_indices_arg: str = None, tie_break_arg: str = None) -> Callable[[T], T]:
|
1477 |
+
|
1478 |
+
def _decorator(func: T) -> T:
|
1479 |
+
docstr = """
|
1480 |
+
Returns the {name} of all elements in the :code:`input` tensor along the provided :code:`axis`
|
1481 |
+
|
1482 |
+
:param input: the input values
|
1483 |
+
:param axis: the dimension along which the scan should be done"""
|
1484 |
+
func.__doc__ = docstr.format(name=name)
|
1485 |
+
return func
|
1486 |
+
|
1487 |
+
return _decorator
|
1488 |
+
|
1489 |
+
|
1490 |
+
@builtin
|
1491 |
+
def associative_scan(input, axis, combine_fn, _builder=None, _generator=None):
|
1492 |
+
"""Applies the combine_fn to each elements with a carry in :code:`input` tensors along the provided :code:`axis` and update the carry
|
1493 |
+
|
1494 |
+
:param input: the input tensor, or tuple of tensors
|
1495 |
+
:param axis: the dimension along which the reduction should be done
|
1496 |
+
:param combine_fn: a function to combine two groups of scalar tensors (must be marked with @triton.jit)
|
1497 |
+
|
1498 |
+
"""
|
1499 |
+
if isinstance(input, tensor):
|
1500 |
+
return associative_scan((input, ), axis, combine_fn, _builder=_builder, _generator=_generator)[0]
|
1501 |
+
|
1502 |
+
def make_combine_region(scan_op):
|
1503 |
+
in_scalar_tys = [t.type.scalar for t in input]
|
1504 |
+
prototype = function_type(in_scalar_tys, in_scalar_tys * 2)
|
1505 |
+
|
1506 |
+
region = scan_op.get_region(0)
|
1507 |
+
with _insertion_guard(_builder):
|
1508 |
+
param_types = [ty.to_ir(_builder) for ty in prototype.param_types]
|
1509 |
+
block = _builder.create_block_with_parent(region, param_types)
|
1510 |
+
args = [tensor(block.arg(i), ty) for i, ty in enumerate(prototype.param_types)]
|
1511 |
+
results = _generator.call_JitFunction(combine_fn, args, kwargs={})
|
1512 |
+
if isinstance(results, tensor):
|
1513 |
+
handles = [results.handle]
|
1514 |
+
else:
|
1515 |
+
handles = [r.handle for r in results]
|
1516 |
+
_builder.create_scan_ret(*handles)
|
1517 |
+
|
1518 |
+
axis = _constexpr_to_value(axis)
|
1519 |
+
return semantic.associative_scan(input, axis, make_combine_region, _builder)
|
1520 |
+
|
1521 |
+
|
1522 |
+
# -----------------------
|
1523 |
+
# Compiler Hint Ops
|
1524 |
+
# -----------------------
|
1525 |
+
|
1526 |
+
|
1527 |
+
@builtin
|
1528 |
+
def debug_barrier(_builder=None):
|
1529 |
+
'''
|
1530 |
+
Insert a barrier to synchronize all threads in a block.
|
1531 |
+
'''
|
1532 |
+
return semantic.debug_barrier(_builder)
|
1533 |
+
|
1534 |
+
|
1535 |
+
@builtin
|
1536 |
+
def multiple_of(input, values, _builder=None):
|
1537 |
+
"""
|
1538 |
+
Let the compiler know that the values in :code:`input` are all multiples of :code:`value`.
|
1539 |
+
"""
|
1540 |
+
if isinstance(values, constexpr):
|
1541 |
+
values = [values]
|
1542 |
+
for i, d in enumerate(values):
|
1543 |
+
if not isinstance(d, constexpr):
|
1544 |
+
raise TypeError(f"values element {i} must have type `constexpr`")
|
1545 |
+
if not isinstance(d.value, int):
|
1546 |
+
raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]")
|
1547 |
+
values = [x.value for x in values]
|
1548 |
+
return semantic.multiple_of(input, values)
|
1549 |
+
|
1550 |
+
|
1551 |
+
@builtin
|
1552 |
+
def max_contiguous(input, values, _builder=None):
|
1553 |
+
"""
|
1554 |
+
Let the compiler know that the `value` first values in :code:`input` are contiguous.
|
1555 |
+
"""
|
1556 |
+
if isinstance(values, constexpr):
|
1557 |
+
values = [values]
|
1558 |
+
for i, d in enumerate(values):
|
1559 |
+
if not isinstance(d, constexpr):
|
1560 |
+
raise TypeError(f"values element {i} must have type `constexpr`")
|
1561 |
+
if not isinstance(d.value, int):
|
1562 |
+
raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]")
|
1563 |
+
values = [x.value for x in values]
|
1564 |
+
return semantic.max_contiguous(input, values)
|
1565 |
+
|
1566 |
+
|
1567 |
+
@builtin
|
1568 |
+
def max_constancy(input, values, _builder=None):
|
1569 |
+
"""
|
1570 |
+
Let the compiler know that the `value` first values in :code:`input` are constant.
|
1571 |
+
|
1572 |
+
e.g. if :code:`values` is [4], then each group of 4 values in :code:`input` should all be equal,
|
1573 |
+
for example [0, 0, 0, 0, 1, 1, 1, 1].
|
1574 |
+
"""
|
1575 |
+
if isinstance(values, constexpr):
|
1576 |
+
values = [values]
|
1577 |
+
for i, d in enumerate(values):
|
1578 |
+
if not isinstance(d, constexpr):
|
1579 |
+
raise TypeError(f"values element {i} must have type `constexpr`")
|
1580 |
+
if not isinstance(d.value, int):
|
1581 |
+
raise TypeError(f"values element {i} must have type `constexpr[int]`, got `constexpr[{type(d.value)}]")
|
1582 |
+
values = [x.value for x in values]
|
1583 |
+
return semantic.max_constancy(input, values)
|
1584 |
+
|
1585 |
+
|
1586 |
+
# -----------------------
|
1587 |
+
# Debugging functions
|
1588 |
+
# -----------------------
|
1589 |
+
|
1590 |
+
|
1591 |
+
@builtin
|
1592 |
+
def static_print(*values, sep: str = " ", end: str = "\n", file=None, flush=False, _builder=None):
|
1593 |
+
'''
|
1594 |
+
Print the values at compile time. The parameters are the same as the builtin :code:`print`.
|
1595 |
+
|
1596 |
+
NOTE: Calling the Python builtin :code:`print` is not the same as calling this, it instead maps to :code:`device_print`,
|
1597 |
+
which has special requirements for the arguments.
|
1598 |
+
|
1599 |
+
.. highlight:: python
|
1600 |
+
.. code-block:: python
|
1601 |
+
|
1602 |
+
tl.static_print(f"{BLOCK_SIZE=}")
|
1603 |
+
'''
|
1604 |
+
pass
|
1605 |
+
|
1606 |
+
|
1607 |
+
@builtin
|
1608 |
+
def static_assert(cond, msg="", _builder=None):
|
1609 |
+
'''
|
1610 |
+
Assert the condition at compile time. Does not require that the :code:`TRITON_DEBUG` environment variable
|
1611 |
+
is set.
|
1612 |
+
|
1613 |
+
.. highlight:: python
|
1614 |
+
.. code-block:: python
|
1615 |
+
|
1616 |
+
tl.static_assert(BLOCK_SIZE == 1024)
|
1617 |
+
'''
|
1618 |
+
pass
|
1619 |
+
|
1620 |
+
|
1621 |
+
@builtin
|
1622 |
+
def device_print(prefix, *args, _builder=None):
|
1623 |
+
'''
|
1624 |
+
Print the values at runtime from the device. String formatting does not work for runtime values, so you should
|
1625 |
+
provide the values you want to print as arguments. The first value must be a string, all following values must
|
1626 |
+
be scalars or tensors.
|
1627 |
+
|
1628 |
+
Calling the Python builtin :code:`print` is the same as calling this function, and the requirements for the arguments will match
|
1629 |
+
this function (not the normal requirements for :code:`print`).
|
1630 |
+
|
1631 |
+
.. highlight:: python
|
1632 |
+
.. code-block:: python
|
1633 |
+
|
1634 |
+
tl.device_print("pid", pid)
|
1635 |
+
print("pid", pid)
|
1636 |
+
|
1637 |
+
:param prefix: a prefix to print before the values. This is required to be a string literal.
|
1638 |
+
:param args: the values to print. They can be any tensor or scalar.
|
1639 |
+
'''
|
1640 |
+
import string
|
1641 |
+
prefix = _constexpr_to_value(prefix)
|
1642 |
+
assert isinstance(prefix, str), f"{prefix} is not string"
|
1643 |
+
b_ascii = True
|
1644 |
+
for ch in prefix:
|
1645 |
+
if ch not in string.printable:
|
1646 |
+
b_ascii = False
|
1647 |
+
break
|
1648 |
+
assert b_ascii, f"{prefix} is not an ascii string"
|
1649 |
+
new_args = []
|
1650 |
+
for arg in args:
|
1651 |
+
new_args.append(_to_tensor(arg, _builder))
|
1652 |
+
return semantic.device_print(prefix, new_args, _builder)
|
1653 |
+
|
1654 |
+
|
1655 |
+
@builtin
|
1656 |
+
def device_assert(cond, msg="", _builder=None):
|
1657 |
+
'''
|
1658 |
+
Assert the condition at runtime from the device. Requires that the environment variable :code:`TRITON_DEBUG`
|
1659 |
+
is set to a value besides :code:`0` in order for this to have any effect.
|
1660 |
+
|
1661 |
+
Using the Python :code:`assert` statement is the same as calling this function, except that the second argument
|
1662 |
+
must be provided and must be a string, e.g. :code:`assert pid == 0, "pid != 0"`. The environment variable must
|
1663 |
+
be set for this :code:`assert` statement to have any effect.
|
1664 |
+
|
1665 |
+
.. highlight:: python
|
1666 |
+
.. code-block:: python
|
1667 |
+
|
1668 |
+
tl.device_assert(pid == 0)
|
1669 |
+
assert pid == 0, f"pid != 0"
|
1670 |
+
|
1671 |
+
:param cond: the condition to assert. This is required to be a boolean tensor.
|
1672 |
+
:param msg: the message to print if the assertion fails. This is required to be a string literal.
|
1673 |
+
'''
|
1674 |
+
msg = _constexpr_to_value(msg)
|
1675 |
+
import inspect
|
1676 |
+
frame = inspect.currentframe()
|
1677 |
+
module = inspect.getmodule(frame)
|
1678 |
+
# The triton function module doesn't have the name attribute.
|
1679 |
+
# We use this trick to find the caller.
|
1680 |
+
while hasattr(module, "__name__"):
|
1681 |
+
frame = frame.f_back
|
1682 |
+
module = inspect.getmodule(frame)
|
1683 |
+
lineno = 0
|
1684 |
+
func_name = 'unknown'
|
1685 |
+
file_name = 'unknown'
|
1686 |
+
if frame is not None and frame.f_back is not None:
|
1687 |
+
func_name = frame.f_code.co_name
|
1688 |
+
file_name = frame.f_back.f_code.co_filename
|
1689 |
+
# TODO: The line number currently indicates the line
|
1690 |
+
# where the triton function is called but not where the
|
1691 |
+
# device_assert is called. Need to enhance this.
|
1692 |
+
lineno = frame.f_back.f_lineno
|
1693 |
+
return semantic.device_assert(_to_tensor(cond, _builder), msg, file_name, func_name, lineno, _builder)
|
1694 |
+
|
1695 |
+
|
1696 |
+
@builtin
|
1697 |
+
def inline_asm_elementwise(asm: str, constraints: str, args: list, dtype, is_pure: bool, pack: int, _builder=None):
|
1698 |
+
'''
|
1699 |
+
Execute the inline assembly to a packed of elements of the tensor
|
1700 |
+
:param asm: assembly to be inlined, it has to match the target assembly format
|
1701 |
+
:param constraints: string representing the mapping of operands to register
|
1702 |
+
:param args: the arguments of the operation
|
1703 |
+
:param dtype: the element type of the returned variable
|
1704 |
+
:param is_pure: whether the operation is pure
|
1705 |
+
:param pack: the number of elements to be processed by one instance of inline assembly
|
1706 |
+
:param _builder: the builder
|
1707 |
+
:return: the return value of the function
|
1708 |
+
'''
|
1709 |
+
asm = _constexpr_to_value(asm)
|
1710 |
+
constraints = _constexpr_to_value(constraints)
|
1711 |
+
pack = _constexpr_to_value(pack)
|
1712 |
+
is_pure = _constexpr_to_value(is_pure)
|
1713 |
+
res_ty = dtype
|
1714 |
+
dispatch_args = [_to_tensor(arg, _builder) for arg in args]
|
1715 |
+
if dispatch_args:
|
1716 |
+
bin_op_type_checking = partial(
|
1717 |
+
semantic.binary_op_type_checking_impl,
|
1718 |
+
builder=_builder,
|
1719 |
+
arithmetic_check=False,
|
1720 |
+
allow_lhs_ptr=True,
|
1721 |
+
allow_rhs_ptr=True,
|
1722 |
+
)
|
1723 |
+
broadcast_arg = dispatch_args[0]
|
1724 |
+
# Get the broadcast shape over all the arguments
|
1725 |
+
for item in dispatch_args:
|
1726 |
+
_, broadcast_arg = bin_op_type_checking(item, broadcast_arg)
|
1727 |
+
if broadcast_arg.shape:
|
1728 |
+
# Change the shape of each argument based on the broadcast shape
|
1729 |
+
for i, item in enumerate(dispatch_args):
|
1730 |
+
dispatch_args[i], _ = bin_op_type_checking(item, broadcast_arg)
|
1731 |
+
res_ty = block_type(dtype, broadcast_arg.shape)
|
1732 |
+
handles = [t.handle for t in dispatch_args]
|
1733 |
+
call = _builder.create_inline_asm(asm, constraints, handles, res_ty.to_ir(_builder), is_pure, pack)
|
1734 |
+
return tensor(call, res_ty)
|
1735 |
+
|
1736 |
+
|
1737 |
+
# -----------------------
|
1738 |
+
# Iterators
|
1739 |
+
# -----------------------
|
1740 |
+
|
1741 |
+
|
1742 |
+
class static_range:
|
1743 |
+
"""
|
1744 |
+
Iterator that counts upward forever.
|
1745 |
+
|
1746 |
+
.. highlight:: python
|
1747 |
+
.. code-block:: python
|
1748 |
+
|
1749 |
+
@triton.jit
|
1750 |
+
def kernel(...):
|
1751 |
+
for i in tl.static_range(10):
|
1752 |
+
...
|
1753 |
+
:note: This is a special iterator used to implement similar semantics to Python's :code:`range` in the context of
|
1754 |
+
:code:`triton.jit` functions. In addition, it also guides the compiler to unroll the loop aggressively.
|
1755 |
+
:param arg1: the start value.
|
1756 |
+
:param arg2: the end value.
|
1757 |
+
:param step: the step value.
|
1758 |
+
"""
|
1759 |
+
|
1760 |
+
def __init__(self, arg1, arg2=None, step=None):
|
1761 |
+
assert isinstance(arg1, constexpr)
|
1762 |
+
if step is None:
|
1763 |
+
self.step = constexpr(1)
|
1764 |
+
else:
|
1765 |
+
assert isinstance(step, constexpr)
|
1766 |
+
self.step = step
|
1767 |
+
if arg2 is None:
|
1768 |
+
self.start = constexpr(0)
|
1769 |
+
self.end = arg1
|
1770 |
+
else:
|
1771 |
+
assert isinstance(arg2, constexpr)
|
1772 |
+
self.start = arg1
|
1773 |
+
self.end = arg2
|
1774 |
+
|
1775 |
+
def __iter__(self):
|
1776 |
+
raise RuntimeError("static_range can only be used in @triton.jit'd functions")
|
1777 |
+
|
1778 |
+
def __next__(self):
|
1779 |
+
raise RuntimeError("static_range can only be used in @triton.jit'd functions")
|
1780 |
+
|
1781 |
+
|
1782 |
+
# -----------------------
|
1783 |
+
# Extern functions
|
1784 |
+
# -----------------------
|
1785 |
+
|
1786 |
+
|
1787 |
+
def dispatch(func, lib_name: str, lib_path: str, args: list, arg_type_symbol_dict: dict, ret_shape: tuple,
|
1788 |
+
is_pure: bool, _builder=None):
|
1789 |
+
'''
|
1790 |
+
Dispatch a function to a library
|
1791 |
+
:param func: the function to dispatch
|
1792 |
+
:param lib_name: the name of the library
|
1793 |
+
:param lib_path: the path of the library
|
1794 |
+
:param args: the arguments of the function
|
1795 |
+
:param arg_type_symbol_dict: the type of the arguments
|
1796 |
+
:param ret_shape: the shape of the return value
|
1797 |
+
:param _builder: the builder
|
1798 |
+
:return: the return value of the function
|
1799 |
+
'''
|
1800 |
+
if len(arg_type_symbol_dict) == 0:
|
1801 |
+
raise ValueError("arg_type_symbol_dict is empty")
|
1802 |
+
|
1803 |
+
num_args = len(list(arg_type_symbol_dict.keys())[0])
|
1804 |
+
if len(args) != num_args:
|
1805 |
+
raise ValueError(f"length of input args does not match."
|
1806 |
+
f"Expect {len(args)}, got {num_args}")
|
1807 |
+
|
1808 |
+
arg_types = []
|
1809 |
+
arg_list = []
|
1810 |
+
for arg in args:
|
1811 |
+
if isinstance(arg, tensor):
|
1812 |
+
arg_types.append(arg.dtype)
|
1813 |
+
arg_list.append(arg.handle)
|
1814 |
+
else:
|
1815 |
+
arg_types.append(type(arg))
|
1816 |
+
arg_list.append(arg)
|
1817 |
+
arg_types = tuple(arg_types)
|
1818 |
+
|
1819 |
+
if arg_types not in arg_type_symbol_dict:
|
1820 |
+
raise ValueError(f"input arg type does not match."
|
1821 |
+
f"Expect one of {arg_type_symbol_dict.keys()}, got {arg_types}")
|
1822 |
+
else:
|
1823 |
+
symbol = arg_type_symbol_dict[arg_types][0]
|
1824 |
+
ret_type = arg_type_symbol_dict[arg_types][1]
|
1825 |
+
if ret_shape:
|
1826 |
+
ret_type = block_type(ret_type, ret_shape)
|
1827 |
+
return tensor(func(lib_name, lib_path, symbol, arg_list, ret_type.to_ir(_builder), is_pure), ret_type)
|
1828 |
+
|
1829 |
+
|
1830 |
+
def extern_elementwise(lib_name: str, lib_path: str, args: list, arg_type_symbol_dict: dict, is_pure: bool,
|
1831 |
+
_builder=None):
|
1832 |
+
'''
|
1833 |
+
Dispatch an elementwise function to a library
|
1834 |
+
:param lib_name: the name of the library
|
1835 |
+
:param lib_path: the path of the library
|
1836 |
+
:param args: the arguments of the function
|
1837 |
+
:param arg_type_symbol_dict: the type of the arguments
|
1838 |
+
:param is_pure: whether the function is pure
|
1839 |
+
:param _builder: the builder
|
1840 |
+
:return: the return value of the function
|
1841 |
+
'''
|
1842 |
+
dispatch_args = args.copy()
|
1843 |
+
all_scalar = True
|
1844 |
+
ret_shape = None
|
1845 |
+
arg_types = []
|
1846 |
+
for i in range(len(dispatch_args)):
|
1847 |
+
dispatch_args[i] = _to_tensor(dispatch_args[i], _builder)
|
1848 |
+
arg_types.append(dispatch_args[i].dtype)
|
1849 |
+
if dispatch_args[i].type.is_block():
|
1850 |
+
all_scalar = False
|
1851 |
+
if len(arg_types) > 0:
|
1852 |
+
arg_types = tuple(arg_types)
|
1853 |
+
arithmetic_check = True
|
1854 |
+
# If there's a type tuple that is not supported by the library, we will do arithmetic check
|
1855 |
+
if arg_types in arg_type_symbol_dict:
|
1856 |
+
arithmetic_check = False
|
1857 |
+
broadcast_arg = dispatch_args[0]
|
1858 |
+
# Get the broadcast shape over all the arguments
|
1859 |
+
for i, item in enumerate(dispatch_args):
|
1860 |
+
_, broadcast_arg = semantic.binary_op_type_checking_impl(item, broadcast_arg, _builder,
|
1861 |
+
arithmetic_check=arithmetic_check)
|
1862 |
+
# Change the shape of each argument based on the broadcast shape
|
1863 |
+
for i in range(len(dispatch_args)):
|
1864 |
+
dispatch_args[i], _ = semantic.binary_op_type_checking_impl(dispatch_args[i], broadcast_arg, _builder,
|
1865 |
+
arithmetic_check=arithmetic_check)
|
1866 |
+
if not all_scalar:
|
1867 |
+
ret_shape = broadcast_arg.shape
|
1868 |
+
func = getattr(_builder, "create_extern_elementwise")
|
1869 |
+
return dispatch(func, lib_name, lib_path, dispatch_args, arg_type_symbol_dict, ret_shape, is_pure, _builder)
|
1870 |
+
|
1871 |
+
|
1872 |
+
def binary_op_type_legalization(lhs, rhs, builder):
|
1873 |
+
'''
|
1874 |
+
Convert both operands to a single common type
|
1875 |
+
:param lhs: the left operand
|
1876 |
+
:param rhs: the right operand
|
1877 |
+
:param builder: the builder
|
1878 |
+
'''
|
1879 |
+
return semantic.binary_op_type_checking_impl(lhs, rhs, builder)
|
1880 |
+
|
1881 |
+
|
1882 |
+
def extern(fn):
|
1883 |
+
"""A decorator for external functions."""
|
1884 |
+
return builtin(fn)
|
env-llmeval/lib/python3.10/site-packages/triton/language/extra/__init__.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
from . import cuda
|
2 |
+
|
3 |
+
__all__ = ['cuda']
|