diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/ElementInclude.py b/llmeval-env/lib/python3.10/site-packages/lxml/ElementInclude.py new file mode 100644 index 0000000000000000000000000000000000000000..21884336f534cd2013165934111146684c9909cf --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/ElementInclude.py @@ -0,0 +1,244 @@ +# +# ElementTree +# $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $ +# +# limited xinclude support for element trees +# +# history: +# 2003-08-15 fl created +# 2003-11-14 fl fixed default loader +# +# Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved. +# +# fredrik@pythonware.com +# http://www.pythonware.com +# +# -------------------------------------------------------------------- +# The ElementTree toolkit is +# +# Copyright (c) 1999-2004 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + +""" +Limited XInclude support for the ElementTree package. + +While lxml.etree has full support for XInclude (see +`etree.ElementTree.xinclude()`), this module provides a simpler, pure +Python, ElementTree compatible implementation that supports a simple +form of custom URL resolvers. +""" + +from lxml import etree +try: + from urlparse import urljoin + from urllib2 import urlopen +except ImportError: + # Python 3 + from urllib.parse import urljoin + from urllib.request import urlopen + +XINCLUDE = "{http://www.w3.org/2001/XInclude}" + +XINCLUDE_INCLUDE = XINCLUDE + "include" +XINCLUDE_FALLBACK = XINCLUDE + "fallback" +XINCLUDE_ITER_TAG = XINCLUDE + "*" + +# For security reasons, the inclusion depth is limited to this read-only value by default. +DEFAULT_MAX_INCLUSION_DEPTH = 6 + + +## +# Fatal include error. + +class FatalIncludeError(etree.LxmlSyntaxError): + pass + + +class LimitedRecursiveIncludeError(FatalIncludeError): + pass + + +## +# ET compatible default loader. +# This loader reads an included resource from disk. +# +# @param href Resource reference. +# @param parse Parse mode. Either "xml" or "text". +# @param encoding Optional text encoding. +# @return The expanded resource. If the parse mode is "xml", this +# is an ElementTree instance. If the parse mode is "text", this +# is a Unicode string. If the loader fails, it can return None +# or raise an IOError exception. +# @throws IOError If the loader fails to load the resource. + +def default_loader(href, parse, encoding=None): + file = open(href, 'rb') + if parse == "xml": + data = etree.parse(file).getroot() + else: + data = file.read() + if not encoding: + encoding = 'utf-8' + data = data.decode(encoding) + file.close() + return data + + +## +# Default loader used by lxml.etree - handles custom resolvers properly +# + +def _lxml_default_loader(href, parse, encoding=None, parser=None): + if parse == "xml": + data = etree.parse(href, parser).getroot() + else: + if "://" in href: + f = urlopen(href) + else: + f = open(href, 'rb') + data = f.read() + f.close() + if not encoding: + encoding = 'utf-8' + data = data.decode(encoding) + return data + + +## +# Wrapper for ET compatibility - drops the parser + +def _wrap_et_loader(loader): + def load(href, parse, encoding=None, parser=None): + return loader(href, parse, encoding) + return load + + +## +# Expand XInclude directives. +# +# @param elem Root element. +# @param loader Optional resource loader. If omitted, it defaults +# to {@link default_loader}. If given, it should be a callable +# that implements the same interface as default_loader. +# @param base_url The base URL of the original file, to resolve +# relative include file references. +# @param max_depth The maximum number of recursive inclusions. +# Limited to reduce the risk of malicious content explosion. +# Pass None to disable the limitation. +# @throws LimitedRecursiveIncludeError If the {@link max_depth} was exceeded. +# @throws FatalIncludeError If the function fails to include a given +# resource, or if the tree contains malformed XInclude elements. +# @throws IOError If the function fails to load a given resource. +# @returns the node or its replacement if it was an XInclude node + +def include(elem, loader=None, base_url=None, + max_depth=DEFAULT_MAX_INCLUSION_DEPTH): + if max_depth is None: + max_depth = -1 + elif max_depth < 0: + raise ValueError("expected non-negative depth or None for 'max_depth', got %r" % max_depth) + + if base_url is None: + if hasattr(elem, 'getroot'): + tree = elem + elem = elem.getroot() + else: + tree = elem.getroottree() + if hasattr(tree, 'docinfo'): + base_url = tree.docinfo.URL + elif hasattr(elem, 'getroot'): + elem = elem.getroot() + _include(elem, loader, base_url, max_depth) + + +def _include(elem, loader=None, base_url=None, + max_depth=DEFAULT_MAX_INCLUSION_DEPTH, _parent_hrefs=None): + if loader is not None: + load_include = _wrap_et_loader(loader) + else: + load_include = _lxml_default_loader + + if _parent_hrefs is None: + _parent_hrefs = set() + + parser = elem.getroottree().parser + + include_elements = list( + elem.iter(XINCLUDE_ITER_TAG)) + + for e in include_elements: + if e.tag == XINCLUDE_INCLUDE: + # process xinclude directive + href = urljoin(base_url, e.get("href")) + parse = e.get("parse", "xml") + parent = e.getparent() + if parse == "xml": + if href in _parent_hrefs: + raise FatalIncludeError( + "recursive include of %r detected" % href + ) + if max_depth == 0: + raise LimitedRecursiveIncludeError( + "maximum xinclude depth reached when including file %s" % href) + node = load_include(href, parse, parser=parser) + if node is None: + raise FatalIncludeError( + "cannot load %r as %r" % (href, parse) + ) + node = _include(node, loader, href, max_depth - 1, {href} | _parent_hrefs) + if e.tail: + node.tail = (node.tail or "") + e.tail + if parent is None: + return node # replaced the root node! + parent.replace(e, node) + elif parse == "text": + text = load_include(href, parse, encoding=e.get("encoding")) + if text is None: + raise FatalIncludeError( + "cannot load %r as %r" % (href, parse) + ) + predecessor = e.getprevious() + if predecessor is not None: + predecessor.tail = (predecessor.tail or "") + text + elif parent is None: + return text # replaced the root node! + else: + parent.text = (parent.text or "") + text + (e.tail or "") + parent.remove(e) + else: + raise FatalIncludeError( + "unknown parse type in xi:include tag (%r)" % parse + ) + elif e.tag == XINCLUDE_FALLBACK: + parent = e.getparent() + if parent is not None and parent.tag != XINCLUDE_INCLUDE: + raise FatalIncludeError( + "xi:fallback tag must be child of xi:include (%r)" % e.tag + ) + else: + raise FatalIncludeError( + "Invalid element found in XInclude namespace (%r)" % e.tag + ) + return elem diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__init__.py b/llmeval-env/lib/python3.10/site-packages/lxml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65a92c2faef38686ee59bfd6f6a08bdae73eece0 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/__init__.py @@ -0,0 +1,22 @@ +# this is a package + +__version__ = "5.2.1" + + +def get_include(): + """ + Returns a list of header include paths (for lxml itself, libxml2 + and libxslt) needed to compile C code against lxml if it was built + with statically linked libraries. + """ + import os + lxml_path = __path__[0] + include_path = os.path.join(lxml_path, 'includes') + includes = [include_path, lxml_path] + + for name in os.listdir(include_path): + path = os.path.join(include_path, name) + if os.path.isdir(path): + includes.append(path) + + return includes diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5810ccaef436f8ce9e25e01e238c1e5a7952f663 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cb01beb9d4504d4ef7aa958dcaf04a95175cb84 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b846e25d952c7d96a3b97e76678690a99f27b93e Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5139766a2e41989c9c57cc53a5c3aa84b8a12af Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c35ba1cdd949c62ec8135888e773c1709e7861c9 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b845760f99fa4a24aa156a130752d4a5d5f5719 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0f91aa4d77a720f8c02fce78144a8380de68bd0 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8688056ece4a86c229d7c07c6d5d1c8e074e3767 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f0c5ffe1cf0daf608f4b2fc61aec57cbf38e5de Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so b/llmeval-env/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e6a43a3fa8f2b6b43e51c8d51e1af9668d13018f Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/builder.py b/llmeval-env/lib/python3.10/site-packages/lxml/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..cff67b0bc006f7f7c184d74f76913c3e2c1a557b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/builder.py @@ -0,0 +1,232 @@ +# cython: language_level=2 + +# +# Element generator factory by Fredrik Lundh. +# +# Source: +# http://online.effbot.org/2006_11_01_archive.htm#et-builder +# http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/builder.py +# +# -------------------------------------------------------------------- +# The ElementTree toolkit is +# +# Copyright (c) 1999-2004 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its +# associated documentation, you agree that you have read, understood, +# and will comply with the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and +# its associated documentation for any purpose and without fee is +# hereby granted, provided that the above copyright notice appears in +# all copies, and that both that copyright notice and this permission +# notice appear in supporting documentation, and that the name of +# Secret Labs AB or the author not be used in advertising or publicity +# pertaining to distribution of the software without specific, written +# prior permission. +# +# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD +# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- +# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR +# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE +# OF THIS SOFTWARE. +# -------------------------------------------------------------------- + +""" +The ``E`` Element factory for generating XML documents. +""" + + +import lxml.etree as ET +_QName = ET.QName + +from functools import partial + +try: + basestring +except NameError: + basestring = str + +try: + unicode +except NameError: + unicode = str + + +class ElementMaker: + """Element generator factory. + + Unlike the ordinary Element factory, the E factory allows you to pass in + more than just a tag and some optional attributes; you can also pass in + text and other elements. The text is added as either text or tail + attributes, and elements are inserted at the right spot. Some small + examples:: + + >>> from lxml import etree as ET + >>> from lxml.builder import E + + >>> ET.tostring(E("tag")) + '' + >>> ET.tostring(E("tag", "text")) + 'text' + >>> ET.tostring(E("tag", "text", key="value")) + 'text' + >>> ET.tostring(E("tag", E("subtag", "text"), "tail")) + 'texttail' + + For simple tags, the factory also allows you to write ``E.tag(...)`` instead + of ``E('tag', ...)``:: + + >>> ET.tostring(E.tag()) + '' + >>> ET.tostring(E.tag("text")) + 'text' + >>> ET.tostring(E.tag(E.subtag("text"), "tail")) + 'texttail' + + Here's a somewhat larger example; this shows how to generate HTML + documents, using a mix of prepared factory functions for inline elements, + nested ``E.tag`` calls, and embedded XHTML fragments:: + + # some common inline elements + A = E.a + I = E.i + B = E.b + + def CLASS(v): + # helper function, 'class' is a reserved word + return {'class': v} + + page = ( + E.html( + E.head( + E.title("This is a sample document") + ), + E.body( + E.h1("Hello!", CLASS("title")), + E.p("This is a paragraph with ", B("bold"), " text in it!"), + E.p("This is another paragraph, with a ", + A("link", href="http://www.python.org"), "."), + E.p("Here are some reserved characters: ."), + ET.XML("

And finally, here is an embedded XHTML fragment.

"), + ) + ) + ) + + print ET.tostring(page) + + Here's a prettyprinted version of the output from the above script:: + + + + This is a sample document + + +

Hello!

+

This is a paragraph with bold text in it!

+

This is another paragraph, with link.

+

Here are some reserved characters: <spam&egg>.

+

And finally, here is an embedded XHTML fragment.

+ + + + For namespace support, you can pass a namespace map (``nsmap``) + and/or a specific target ``namespace`` to the ElementMaker class:: + + >>> E = ElementMaker(namespace="http://my.ns/") + >>> print(ET.tostring( E.test )) + + + >>> E = ElementMaker(namespace="http://my.ns/", nsmap={'p':'http://my.ns/'}) + >>> print(ET.tostring( E.test )) + + """ + + def __init__(self, typemap=None, + namespace=None, nsmap=None, makeelement=None): + self._namespace = '{' + namespace + '}' if namespace is not None else None + self._nsmap = dict(nsmap) if nsmap else None + + assert makeelement is None or callable(makeelement) + self._makeelement = makeelement if makeelement is not None else ET.Element + + # initialize the default type map functions for this element factory + typemap = dict(typemap) if typemap else {} + + def add_text(elem, item): + try: + last_child = elem[-1] + except IndexError: + elem.text = (elem.text or "") + item + else: + last_child.tail = (last_child.tail or "") + item + + def add_cdata(elem, cdata): + if elem.text: + raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text) + elem.text = cdata + + if str not in typemap: + typemap[str] = add_text + if unicode not in typemap: + typemap[unicode] = add_text + if ET.CDATA not in typemap: + typemap[ET.CDATA] = add_cdata + + def add_dict(elem, item): + attrib = elem.attrib + for k, v in item.items(): + if isinstance(v, basestring): + attrib[k] = v + else: + attrib[k] = typemap[type(v)](None, v) + + if dict not in typemap: + typemap[dict] = add_dict + + self._typemap = typemap + + def __call__(self, tag, *children, **attrib): + typemap = self._typemap + + # We'll usually get a 'str', and the compiled type check is very fast. + if not isinstance(tag, str) and isinstance(tag, _QName): + # A QName is explicitly qualified, do not look at self._namespace. + tag = tag.text + elif self._namespace is not None and tag[0] != '{': + tag = self._namespace + tag + elem = self._makeelement(tag, nsmap=self._nsmap) + if attrib: + typemap[dict](elem, attrib) + + for item in children: + if callable(item): + item = item() + t = typemap.get(type(item)) + if t is None: + if ET.iselement(item): + elem.append(item) + continue + for basetype in type(item).__mro__: + # See if the typemap knows of any of this type's bases. + t = typemap.get(basetype) + if t is not None: + break + else: + raise TypeError("bad argument type: %s(%r)" % + (type(item).__name__, item)) + v = t(elem, item) + if v: + typemap.get(type(v))(elem, v) + + return elem + + def __getattr__(self, tag): + return partial(self, tag) + + +# create factory object +E = ElementMaker() diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/cleanup.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/cleanup.pxi new file mode 100644 index 0000000000000000000000000000000000000000..8e266b33f0f3aef34f3448276abfb2cb8b1e4772 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/cleanup.pxi @@ -0,0 +1,215 @@ +# functions for tree cleanup and removing elements from subtrees + +def cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None): + """cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None) + + Remove all namespace declarations from a subtree that are not used + by any of the elements or attributes in that tree. + + If a 'top_nsmap' is provided, it must be a mapping from prefixes + to namespace URIs. These namespaces will be declared on the top + element of the subtree before running the cleanup, which allows + moving namespace declarations to the top of the tree. + + If a 'keep_ns_prefixes' is provided, it must be a list of prefixes. + These prefixes will not be removed as part of the cleanup. + """ + element = _rootNodeOrRaise(tree_or_element) + c_element = element._c_node + + if top_nsmap: + doc = element._doc + # declare namespaces from nsmap, then apply them to the subtree + _setNodeNamespaces(c_element, doc, None, top_nsmap) + moveNodeToDocument(doc, c_element.doc, c_element) + + keep_ns_prefixes = ( + set([_utf8(prefix) for prefix in keep_ns_prefixes]) + if keep_ns_prefixes else None) + + _removeUnusedNamespaceDeclarations(c_element, keep_ns_prefixes) + + +def strip_attributes(tree_or_element, *attribute_names): + """strip_attributes(tree_or_element, *attribute_names) + + Delete all attributes with the provided attribute names from an + Element (or ElementTree) and its descendants. + + Attribute names can contain wildcards as in `_Element.iter`. + + Example usage:: + + strip_attributes(root_element, + 'simpleattr', + '{http://some/ns}attrname', + '{http://other/ns}*') + """ + cdef _MultiTagMatcher matcher + element = _rootNodeOrRaise(tree_or_element) + if not attribute_names: + return + + matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, attribute_names) + matcher.cacheTags(element._doc) + if matcher.rejectsAllAttributes(): + return + _strip_attributes(element._c_node, matcher) + + +cdef _strip_attributes(xmlNode* c_node, _MultiTagMatcher matcher): + cdef xmlAttr* c_attr + cdef xmlAttr* c_next_attr + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + c_attr = c_node.properties + while c_attr is not NULL: + c_next_attr = c_attr.next + if matcher.matchesAttribute(c_attr): + tree.xmlRemoveProp(c_attr) + c_attr = c_next_attr + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + + +def strip_elements(tree_or_element, *tag_names, bint with_tail=True): + """strip_elements(tree_or_element, *tag_names, with_tail=True) + + Delete all elements with the provided tag names from a tree or + subtree. This will remove the elements and their entire subtree, + including all their attributes, text content and descendants. It + will also remove the tail text of the element unless you + explicitly set the ``with_tail`` keyword argument option to False. + + Tag names can contain wildcards as in `_Element.iter`. + + Note that this will not delete the element (or ElementTree root + element) that you passed even if it matches. It will only treat + its descendants. If you want to include the root element, check + its tag name directly before even calling this function. + + Example usage:: + + strip_elements(some_element, + 'simpletagname', # non-namespaced tag + '{http://some/ns}tagname', # namespaced tag + '{http://some/other/ns}*' # any tag from a namespace + lxml.etree.Comment # comments + ) + """ + cdef _MultiTagMatcher matcher + doc = _documentOrRaise(tree_or_element) + element = _rootNodeOrRaise(tree_or_element) + if not tag_names: + return + + matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names) + matcher.cacheTags(doc) + if matcher.rejectsAll(): + return + + if isinstance(tree_or_element, _ElementTree): + # include PIs and comments next to the root node + if matcher.matchesType(tree.XML_COMMENT_NODE): + _removeSiblings(element._c_node, tree.XML_COMMENT_NODE, with_tail) + if matcher.matchesType(tree.XML_PI_NODE): + _removeSiblings(element._c_node, tree.XML_PI_NODE, with_tail) + _strip_elements(doc, element._c_node, matcher, with_tail) + +cdef _strip_elements(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher, + bint with_tail): + cdef xmlNode* c_child + cdef xmlNode* c_next + + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + # we run through the children here to prevent any problems + # with the tree iteration which would occur if we unlinked the + # c_node itself + c_child = _findChildForwards(c_node, 0) + while c_child is not NULL: + c_next = _nextElement(c_child) + if matcher.matches(c_child): + if c_child.type == tree.XML_ELEMENT_NODE: + if not with_tail: + tree.xmlUnlinkNode(c_child) + _removeNode(doc, c_child) + else: + if with_tail: + _removeText(c_child.next) + tree.xmlUnlinkNode(c_child) + attemptDeallocation(c_child) + c_child = c_next + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + + +def strip_tags(tree_or_element, *tag_names): + """strip_tags(tree_or_element, *tag_names) + + Delete all elements with the provided tag names from a tree or + subtree. This will remove the elements and their attributes, but + *not* their text/tail content or descendants. Instead, it will + merge the text content and children of the element into its + parent. + + Tag names can contain wildcards as in `_Element.iter`. + + Note that this will not delete the element (or ElementTree root + element) that you passed even if it matches. It will only treat + its descendants. + + Example usage:: + + strip_tags(some_element, + 'simpletagname', # non-namespaced tag + '{http://some/ns}tagname', # namespaced tag + '{http://some/other/ns}*' # any tag from a namespace + Comment # comments (including their text!) + ) + """ + cdef _MultiTagMatcher matcher + doc = _documentOrRaise(tree_or_element) + element = _rootNodeOrRaise(tree_or_element) + if not tag_names: + return + + matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names) + matcher.cacheTags(doc) + if matcher.rejectsAll(): + return + + if isinstance(tree_or_element, _ElementTree): + # include PIs and comments next to the root node + if matcher.matchesType(tree.XML_COMMENT_NODE): + _removeSiblings(element._c_node, tree.XML_COMMENT_NODE, 0) + if matcher.matchesType(tree.XML_PI_NODE): + _removeSiblings(element._c_node, tree.XML_PI_NODE, 0) + _strip_tags(doc, element._c_node, matcher) + +cdef _strip_tags(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher): + cdef xmlNode* c_child + cdef xmlNode* c_next + + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + # we run through the children here to prevent any problems + # with the tree iteration which would occur if we unlinked the + # c_node itself + c_child = _findChildForwards(c_node, 0) + while c_child is not NULL: + if not matcher.matches(c_child): + c_child = _nextElement(c_child) + continue + if c_child.type == tree.XML_ELEMENT_NODE: + c_next = _findChildForwards(c_child, 0) or _nextElement(c_child) + _replaceNodeByChildren(doc, c_child) + if not attemptDeallocation(c_child): + if c_child.nsDef is not NULL: + # make namespaces absolute + moveNodeToDocument(doc, doc._c_doc, c_child) + c_child = c_next + else: + c_next = _nextElement(c_child) + tree.xmlUnlinkNode(c_child) + attemptDeallocation(c_child) + c_child = c_next + tree.END_FOR_EACH_ELEMENT_FROM(c_node) diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/debug.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/debug.pxi new file mode 100644 index 0000000000000000000000000000000000000000..e5bb061958f29a875e7df043f3b2aec9f550233f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/debug.pxi @@ -0,0 +1,90 @@ +@cython.final +@cython.internal +cdef class _MemDebug: + """Debugging support for the memory allocation in libxml2. + """ + def bytes_used(self): + """bytes_used(self) + + Returns the total amount of memory (in bytes) currently used by libxml2. + Note that libxml2 constrains this value to a C int, which limits + the accuracy on 64 bit systems. + """ + return tree.xmlMemUsed() + + def blocks_used(self): + """blocks_used(self) + + Returns the total number of memory blocks currently allocated by libxml2. + Note that libxml2 constrains this value to a C int, which limits + the accuracy on 64 bit systems. + """ + return tree.xmlMemBlocks() + + def dict_size(self): + """dict_size(self) + + Returns the current size of the global name dictionary used by libxml2 + for the current thread. Each thread has its own dictionary. + """ + c_dict = __GLOBAL_PARSER_CONTEXT._getThreadDict(NULL) + if c_dict is NULL: + raise MemoryError() + return tree.xmlDictSize(c_dict) + + def dump(self, output_file=None, byte_count=None): + """dump(self, output_file=None, byte_count=None) + + Dumps the current memory blocks allocated by libxml2 to a file. + + The optional parameter 'output_file' specifies the file path. It defaults + to the file ".memorylist" in the current directory. + + The optional parameter 'byte_count' limits the number of bytes in the dump. + Note that this parameter is ignored when lxml is compiled against a libxml2 + version before 2.7.0. + """ + cdef Py_ssize_t c_count + if output_file is None: + output_file = b'.memorylist' + elif isinstance(output_file, unicode): + output_file.encode(sys.getfilesystemencoding()) + + f = stdio.fopen(output_file, "w") + if f is NULL: + raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}") + try: + if byte_count is None: + tree.xmlMemDisplay(f) + else: + c_count = byte_count + tree.xmlMemDisplayLast(f, c_count) + finally: + stdio.fclose(f) + + def show(self, output_file=None, block_count=None): + """show(self, output_file=None, block_count=None) + + Dumps the current memory blocks allocated by libxml2 to a file. + The output file format is suitable for line diffing. + + The optional parameter 'output_file' specifies the file path. It defaults + to the file ".memorydump" in the current directory. + + The optional parameter 'block_count' limits the number of blocks + in the dump. + """ + if output_file is None: + output_file = b'.memorydump' + elif isinstance(output_file, unicode): + output_file.encode(sys.getfilesystemencoding()) + + f = stdio.fopen(output_file, "w") + if f is NULL: + raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}") + try: + tree.xmlMemShow(f, block_count if block_count is not None else tree.xmlMemBlocks()) + finally: + stdio.fclose(f) + +memory_debugger = _MemDebug() diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/docloader.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/docloader.pxi new file mode 100644 index 0000000000000000000000000000000000000000..7b38f43838592445d2618440b178bd9c8557073c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/docloader.pxi @@ -0,0 +1,178 @@ +# Custom resolver API + +ctypedef enum _InputDocumentDataType: + PARSER_DATA_INVALID + PARSER_DATA_EMPTY + PARSER_DATA_STRING + PARSER_DATA_FILENAME + PARSER_DATA_FILE + +@cython.final +@cython.internal +cdef class _InputDocument: + cdef _InputDocumentDataType _type + cdef bytes _data_bytes + cdef object _filename + cdef object _file + cdef bint _close_file + + def __cinit__(self): + self._type = PARSER_DATA_INVALID + + +cdef class Resolver: + "This is the base class of all resolvers." + def resolve(self, system_url, public_id, context): + """resolve(self, system_url, public_id, context) + + Override this method to resolve an external source by + ``system_url`` and ``public_id``. The third argument is an + opaque context object. + + Return the result of one of the ``resolve_*()`` methods. + """ + return None + + def resolve_empty(self, context): + """resolve_empty(self, context) + + Return an empty input document. + + Pass context as parameter. + """ + cdef _InputDocument doc_ref + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_EMPTY + return doc_ref + + def resolve_string(self, string, context, *, base_url=None): + """resolve_string(self, string, context, base_url=None) + + Return a parsable string as input document. + + Pass data string and context as parameters. You can pass the + source URL or filename through the ``base_url`` keyword + argument. + """ + cdef _InputDocument doc_ref + if isinstance(string, unicode): + string = (string).encode('utf8') + elif not isinstance(string, bytes): + raise TypeError, "argument must be a byte string or unicode string" + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_STRING + doc_ref._data_bytes = string + if base_url is not None: + doc_ref._filename = _encodeFilename(base_url) + return doc_ref + + def resolve_filename(self, filename, context): + """resolve_filename(self, filename, context) + + Return the name of a parsable file as input document. + + Pass filename and context as parameters. You can also pass a + URL with an HTTP, FTP or file target. + """ + cdef _InputDocument doc_ref + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_FILENAME + doc_ref._filename = _encodeFilename(filename) + return doc_ref + + def resolve_file(self, f, context, *, base_url=None, bint close=True): + """resolve_file(self, f, context, base_url=None, close=True) + + Return an open file-like object as input document. + + Pass open file and context as parameters. You can pass the + base URL or filename of the file through the ``base_url`` + keyword argument. If the ``close`` flag is True (the + default), the file will be closed after reading. + + Note that using ``.resolve_filename()`` is more efficient, + especially in threaded environments. + """ + cdef _InputDocument doc_ref + try: + f.read + except AttributeError: + raise TypeError, "Argument is not a file-like object" + doc_ref = _InputDocument() + doc_ref._type = PARSER_DATA_FILE + if base_url is not None: + doc_ref._filename = _encodeFilename(base_url) + else: + doc_ref._filename = _getFilenameForFile(f) + doc_ref._close_file = close + doc_ref._file = f + return doc_ref + +@cython.final +@cython.internal +cdef class _ResolverRegistry: + cdef object _resolvers + cdef Resolver _default_resolver + def __cinit__(self, Resolver default_resolver=None): + self._resolvers = set() + self._default_resolver = default_resolver + + def add(self, Resolver resolver not None): + """add(self, resolver) + + Register a resolver. + + For each requested entity, the 'resolve' method of the resolver will + be called and the result will be passed to the parser. If this method + returns None, the request will be delegated to other resolvers or the + default resolver. The resolvers will be tested in an arbitrary order + until the first match is found. + """ + self._resolvers.add(resolver) + + def remove(self, resolver): + "remove(self, resolver)" + self._resolvers.discard(resolver) + + cdef _ResolverRegistry _copy(self): + cdef _ResolverRegistry registry + registry = _ResolverRegistry(self._default_resolver) + registry._resolvers = self._resolvers.copy() + return registry + + def copy(self): + "copy(self)" + return self._copy() + + def resolve(self, system_url, public_id, context): + "resolve(self, system_url, public_id, context)" + for resolver in self._resolvers: + result = resolver.resolve(system_url, public_id, context) + if result is not None: + return result + if self._default_resolver is None: + return None + return self._default_resolver.resolve(system_url, public_id, context) + + def __repr__(self): + return repr(self._resolvers) + + +@cython.internal +cdef class _ResolverContext(_ExceptionContext): + cdef _ResolverRegistry _resolvers + cdef _TempStore _storage + + cdef int clear(self) except -1: + _ExceptionContext.clear(self) + self._storage.clear() + return 0 + + +cdef _initResolverContext(_ResolverContext context, + _ResolverRegistry resolvers): + if resolvers is None: + context._resolvers = _ResolverRegistry() + else: + context._resolvers = resolvers + context._storage = _TempStore() diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/doctestcompare.py b/llmeval-env/lib/python3.10/site-packages/lxml/doctestcompare.py new file mode 100644 index 0000000000000000000000000000000000000000..8099771de906a37ed007c779f152fe96f182060d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/doctestcompare.py @@ -0,0 +1,488 @@ +""" +lxml-based doctest output comparison. + +Note: normally, you should just import the `lxml.usedoctest` and +`lxml.html.usedoctest` modules from within a doctest, instead of this +one:: + + >>> import lxml.usedoctest # for XML output + + >>> import lxml.html.usedoctest # for HTML output + +To use this module directly, you must call ``lxmldoctest.install()``, +which will cause doctest to use this in all subsequent calls. + +This changes the way output is checked and comparisons are made for +XML or HTML-like content. + +XML or HTML content is noticed because the example starts with ``<`` +(it's HTML if it starts with ```` or include an ``any`` +attribute in the tag. An ``any`` tag matches any tag, while the +attribute matches any and all attributes. + +When a match fails, the reformatted example and gotten text is +displayed (indented), and a rough diff-like output is given. Anything +marked with ``+`` is in the output but wasn't supposed to be, and +similarly ``-`` means its in the example but wasn't in the output. + +You can disable parsing on one line with ``# doctest:+NOPARSE_MARKUP`` +""" + +from lxml import etree +import sys +import re +import doctest +try: + from html import escape as html_escape +except ImportError: + from cgi import escape as html_escape + +__all__ = ['PARSE_HTML', 'PARSE_XML', 'NOPARSE_MARKUP', 'LXMLOutputChecker', + 'LHTMLOutputChecker', 'install', 'temp_install'] + +PARSE_HTML = doctest.register_optionflag('PARSE_HTML') +PARSE_XML = doctest.register_optionflag('PARSE_XML') +NOPARSE_MARKUP = doctest.register_optionflag('NOPARSE_MARKUP') + +OutputChecker = doctest.OutputChecker + +def strip(v): + if v is None: + return None + else: + return v.strip() + +def norm_whitespace(v): + return _norm_whitespace_re.sub(' ', v) + +_html_parser = etree.HTMLParser(recover=False, remove_blank_text=True) + +def html_fromstring(html): + return etree.fromstring(html, _html_parser) + +# We use this to distinguish repr()s from elements: +_repr_re = re.compile(r'^<[^>]+ (at|object) ') +_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+') + +class LXMLOutputChecker(OutputChecker): + + empty_tags = ( + 'param', 'img', 'area', 'br', 'basefont', 'input', + 'base', 'meta', 'link', 'col') + + def get_default_parser(self): + return etree.XML + + def check_output(self, want, got, optionflags): + alt_self = getattr(self, '_temp_override_self', None) + if alt_self is not None: + super_method = self._temp_call_super_check_output + self = alt_self + else: + super_method = OutputChecker.check_output + parser = self.get_parser(want, got, optionflags) + if not parser: + return super_method( + self, want, got, optionflags) + try: + want_doc = parser(want) + except etree.XMLSyntaxError: + return False + try: + got_doc = parser(got) + except etree.XMLSyntaxError: + return False + return self.compare_docs(want_doc, got_doc) + + def get_parser(self, want, got, optionflags): + parser = None + if NOPARSE_MARKUP & optionflags: + return None + if PARSE_HTML & optionflags: + parser = html_fromstring + elif PARSE_XML & optionflags: + parser = etree.XML + elif (want.strip().lower().startswith('' % el.tag + return '<%s %s>' % (el.tag, ' '.join(attrs)) + + def format_end_tag(self, el): + if isinstance(el, etree.CommentBase): + # FIXME: probably PIs should be handled specially too? + return '-->' + return '' % el.tag + + def collect_diff(self, want, got, html, indent): + parts = [] + if not len(want) and not len(got): + parts.append(' '*indent) + parts.append(self.collect_diff_tag(want, got)) + if not self.html_empty_tag(got, html): + parts.append(self.collect_diff_text(want.text, got.text)) + parts.append(self.collect_diff_end_tag(want, got)) + parts.append(self.collect_diff_text(want.tail, got.tail)) + parts.append('\n') + return ''.join(parts) + parts.append(' '*indent) + parts.append(self.collect_diff_tag(want, got)) + parts.append('\n') + if strip(want.text) or strip(got.text): + parts.append(' '*indent) + parts.append(self.collect_diff_text(want.text, got.text)) + parts.append('\n') + want_children = list(want) + got_children = list(got) + while want_children or got_children: + if not want_children: + parts.append(self.format_doc(got_children.pop(0), html, indent+2, '+')) + continue + if not got_children: + parts.append(self.format_doc(want_children.pop(0), html, indent+2, '-')) + continue + parts.append(self.collect_diff( + want_children.pop(0), got_children.pop(0), html, indent+2)) + parts.append(' '*indent) + parts.append(self.collect_diff_end_tag(want, got)) + parts.append('\n') + if strip(want.tail) or strip(got.tail): + parts.append(' '*indent) + parts.append(self.collect_diff_text(want.tail, got.tail)) + parts.append('\n') + return ''.join(parts) + + def collect_diff_tag(self, want, got): + if not self.tag_compare(want.tag, got.tag): + tag = '%s (got: %s)' % (want.tag, got.tag) + else: + tag = got.tag + attrs = [] + any = want.tag == 'any' or 'any' in want.attrib + for name, value in sorted(got.attrib.items()): + if name not in want.attrib and not any: + attrs.append('+%s="%s"' % (name, self.format_text(value, False))) + else: + if name in want.attrib: + text = self.collect_diff_text(want.attrib[name], value, False) + else: + text = self.format_text(value, False) + attrs.append('%s="%s"' % (name, text)) + if not any: + for name, value in sorted(want.attrib.items()): + if name in got.attrib: + continue + attrs.append('-%s="%s"' % (name, self.format_text(value, False))) + if attrs: + tag = '<%s %s>' % (tag, ' '.join(attrs)) + else: + tag = '<%s>' % tag + return tag + + def collect_diff_end_tag(self, want, got): + if want.tag != got.tag: + tag = '%s (got: %s)' % (want.tag, got.tag) + else: + tag = got.tag + return '' % tag + + def collect_diff_text(self, want, got, strip=True): + if self.text_compare(want, got, strip): + if not got: + return '' + return self.format_text(got, strip) + text = '%s (got: %s)' % (want, got) + return self.format_text(text, strip) + +class LHTMLOutputChecker(LXMLOutputChecker): + def get_default_parser(self): + return html_fromstring + +def install(html=False): + """ + Install doctestcompare for all future doctests. + + If html is true, then by default the HTML parser will be used; + otherwise the XML parser is used. + """ + if html: + doctest.OutputChecker = LHTMLOutputChecker + else: + doctest.OutputChecker = LXMLOutputChecker + +def temp_install(html=False, del_module=None): + """ + Use this *inside* a doctest to enable this checker for this + doctest only. + + If html is true, then by default the HTML parser will be used; + otherwise the XML parser is used. + """ + if html: + Checker = LHTMLOutputChecker + else: + Checker = LXMLOutputChecker + frame = _find_doctest_frame() + dt_self = frame.f_locals['self'] + checker = Checker() + old_checker = dt_self._checker + dt_self._checker = checker + # The unfortunate thing is that there is a local variable 'check' + # in the function that runs the doctests, that is a bound method + # into the output checker. We have to update that. We can't + # modify the frame, so we have to modify the object in place. The + # only way to do this is to actually change the func_code + # attribute of the method. We change it, and then wait for + # __record_outcome to be run, which signals the end of the __run + # method, at which point we restore the previous check_output + # implementation. + check_func = frame.f_locals['check'].__func__ + checker_check_func = checker.check_output.__func__ + # Because we can't patch up func_globals, this is the only global + # in check_output that we care about: + doctest.etree = etree + _RestoreChecker(dt_self, old_checker, checker, + check_func, checker_check_func, + del_module) + +class _RestoreChecker: + def __init__(self, dt_self, old_checker, new_checker, check_func, clone_func, + del_module): + self.dt_self = dt_self + self.checker = old_checker + self.checker._temp_call_super_check_output = self.call_super + self.checker._temp_override_self = new_checker + self.check_func = check_func + self.clone_func = clone_func + self.del_module = del_module + self.install_clone() + self.install_dt_self() + def install_clone(self): + self.func_code = self.check_func.__code__ + self.func_globals = self.check_func.__globals__ + self.check_func.__code__ = self.clone_func.__code__ + def uninstall_clone(self): + self.check_func.__code__ = self.func_code + def install_dt_self(self): + self.prev_func = self.dt_self._DocTestRunner__record_outcome + self.dt_self._DocTestRunner__record_outcome = self + def uninstall_dt_self(self): + self.dt_self._DocTestRunner__record_outcome = self.prev_func + def uninstall_module(self): + if self.del_module: + import sys + del sys.modules[self.del_module] + if '.' in self.del_module: + package, module = self.del_module.rsplit('.', 1) + package_mod = sys.modules[package] + delattr(package_mod, module) + def __call__(self, *args, **kw): + self.uninstall_clone() + self.uninstall_dt_self() + del self.checker._temp_override_self + del self.checker._temp_call_super_check_output + result = self.prev_func(*args, **kw) + self.uninstall_module() + return result + def call_super(self, *args, **kw): + self.uninstall_clone() + try: + return self.check_func(*args, **kw) + finally: + self.install_clone() + +def _find_doctest_frame(): + import sys + frame = sys._getframe(1) + while frame: + l = frame.f_locals + if 'BOOM' in l: + # Sign of doctest + return frame + frame = frame.f_back + raise LookupError( + "Could not find doctest (only use this function *inside* a doctest)") + +__test__ = { + 'basic': ''' + >>> temp_install() + >>> print """stuff""" + ... + >>> print """""" + + + + >>> print """blahblahblah""" # doctest: +NOPARSE_MARKUP, +ELLIPSIS + ...foo /> + '''} + +if __name__ == '__main__': + import doctest + doctest.testmod() + + diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/dtd.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/dtd.pxi new file mode 100644 index 0000000000000000000000000000000000000000..348212c3dccaa4c70f57b572ebec9229a16981d9 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/dtd.pxi @@ -0,0 +1,478 @@ +# support for DTD validation +from lxml.includes cimport dtdvalid + +cdef class DTDError(LxmlError): + """Base class for DTD errors. + """ + +cdef class DTDParseError(DTDError): + """Error while parsing a DTD. + """ + +cdef class DTDValidateError(DTDError): + """Error while validating an XML document with a DTD. + """ + + +cdef inline int _assertValidDTDNode(node, void *c_node) except -1: + assert c_node is not NULL, "invalid DTD proxy at %s" % id(node) + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDElementContentDecl: + cdef DTD _dtd + cdef tree.xmlElementContent* _c_node + + def __repr__(self): + return "<%s.%s object name=%r type=%r occur=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.type, self.occur, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def type(self): + _assertValidDTDNode(self, self._c_node) + cdef int type = self._c_node.type + if type == tree.XML_ELEMENT_CONTENT_PCDATA: + return "pcdata" + elif type == tree.XML_ELEMENT_CONTENT_ELEMENT: + return "element" + elif type == tree.XML_ELEMENT_CONTENT_SEQ: + return "seq" + elif type == tree.XML_ELEMENT_CONTENT_OR: + return "or" + else: + return None + + @property + def occur(self): + _assertValidDTDNode(self, self._c_node) + cdef int occur = self._c_node.ocur + if occur == tree.XML_ELEMENT_CONTENT_ONCE: + return "once" + elif occur == tree.XML_ELEMENT_CONTENT_OPT: + return "opt" + elif occur == tree.XML_ELEMENT_CONTENT_MULT: + return "mult" + elif occur == tree.XML_ELEMENT_CONTENT_PLUS: + return "plus" + else: + return None + + @property + def left(self): + _assertValidDTDNode(self, self._c_node) + c1 = self._c_node.c1 + if c1: + node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl) + node._dtd = self._dtd + node._c_node = c1 + return node + else: + return None + + @property + def right(self): + _assertValidDTDNode(self, self._c_node) + c2 = self._c_node.c2 + if c2: + node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl) + node._dtd = self._dtd + node._c_node = c2 + return node + else: + return None + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDAttributeDecl: + cdef DTD _dtd + cdef tree.xmlAttribute* _c_node + + def __repr__(self): + return "<%s.%s object name=%r elemname=%r prefix=%r type=%r default=%r default_value=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.elemname, self.prefix, self.type, self.default, self.default_value, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def elemname(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.elem) + + @property + def prefix(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.prefix) + + @property + def type(self): + _assertValidDTDNode(self, self._c_node) + cdef int type = self._c_node.atype + if type == tree.XML_ATTRIBUTE_CDATA: + return "cdata" + elif type == tree.XML_ATTRIBUTE_ID: + return "id" + elif type == tree.XML_ATTRIBUTE_IDREF: + return "idref" + elif type == tree.XML_ATTRIBUTE_IDREFS: + return "idrefs" + elif type == tree.XML_ATTRIBUTE_ENTITY: + return "entity" + elif type == tree.XML_ATTRIBUTE_ENTITIES: + return "entities" + elif type == tree.XML_ATTRIBUTE_NMTOKEN: + return "nmtoken" + elif type == tree.XML_ATTRIBUTE_NMTOKENS: + return "nmtokens" + elif type == tree.XML_ATTRIBUTE_ENUMERATION: + return "enumeration" + elif type == tree.XML_ATTRIBUTE_NOTATION: + return "notation" + else: + return None + + @property + def default(self): + _assertValidDTDNode(self, self._c_node) + cdef int default = self._c_node.def_ + if default == tree.XML_ATTRIBUTE_NONE: + return "none" + elif default == tree.XML_ATTRIBUTE_REQUIRED: + return "required" + elif default == tree.XML_ATTRIBUTE_IMPLIED: + return "implied" + elif default == tree.XML_ATTRIBUTE_FIXED: + return "fixed" + else: + return None + + @property + def default_value(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.defaultValue) + + def itervalues(self): + _assertValidDTDNode(self, self._c_node) + cdef tree.xmlEnumeration *c_node = self._c_node.tree + while c_node is not NULL: + yield funicode(c_node.name) + c_node = c_node.next + + def values(self): + return list(self.itervalues()) + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDElementDecl: + cdef DTD _dtd + cdef tree.xmlElement* _c_node + + def __repr__(self): + return "<%s.%s object name=%r prefix=%r type=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.prefix, self.type, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def prefix(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.prefix) + + @property + def type(self): + _assertValidDTDNode(self, self._c_node) + cdef int type = self._c_node.etype + if type == tree.XML_ELEMENT_TYPE_UNDEFINED: + return "undefined" + elif type == tree.XML_ELEMENT_TYPE_EMPTY: + return "empty" + elif type == tree.XML_ELEMENT_TYPE_ANY: + return "any" + elif type == tree.XML_ELEMENT_TYPE_MIXED: + return "mixed" + elif type == tree.XML_ELEMENT_TYPE_ELEMENT: + return "element" + else: + return None + + @property + def content(self): + _assertValidDTDNode(self, self._c_node) + cdef tree.xmlElementContent *content = self._c_node.content + if content: + node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl) + node._dtd = self._dtd + node._c_node = content + return node + else: + return None + + def iterattributes(self): + _assertValidDTDNode(self, self._c_node) + cdef tree.xmlAttribute *c_node = self._c_node.attributes + while c_node: + node = <_DTDAttributeDecl>_DTDAttributeDecl.__new__(_DTDAttributeDecl) + node._dtd = self._dtd + node._c_node = c_node + yield node + c_node = c_node.nexth + + def attributes(self): + return list(self.iterattributes()) + + +@cython.final +@cython.internal +@cython.freelist(8) +cdef class _DTDEntityDecl: + cdef DTD _dtd + cdef tree.xmlEntity* _c_node + def __repr__(self): + return "<%s.%s object name=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, id(self)) + + @property + def name(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.name) + + @property + def orig(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.orig) + + @property + def content(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.content) + + @property + def system_url(self): + _assertValidDTDNode(self, self._c_node) + return funicodeOrNone(self._c_node.SystemID) + + +################################################################################ +# DTD + +cdef class DTD(_Validator): + """DTD(self, file=None, external_id=None) + A DTD validator. + + Can load from filesystem directly given a filename or file-like object. + Alternatively, pass the keyword parameter ``external_id`` to load from a + catalog. + """ + cdef tree.xmlDtd* _c_dtd + def __init__(self, file=None, *, external_id=None): + _Validator.__init__(self) + if file is not None: + file = _getFSPathOrObject(file) + if _isString(file): + file = _encodeFilename(file) + with self._error_log: + orig_loader = _register_document_loader() + self._c_dtd = xmlparser.xmlParseDTD(NULL, _xcstr(file)) + _reset_document_loader(orig_loader) + elif hasattr(file, 'read'): + orig_loader = _register_document_loader() + self._c_dtd = _parseDtdFromFilelike(file) + _reset_document_loader(orig_loader) + else: + raise DTDParseError, "file must be a filename, file-like or path-like object" + elif external_id is not None: + with self._error_log: + orig_loader = _register_document_loader() + self._c_dtd = xmlparser.xmlParseDTD(external_id, NULL) + _reset_document_loader(orig_loader) + else: + raise DTDParseError, "either filename or external ID required" + + if self._c_dtd is NULL: + raise DTDParseError( + self._error_log._buildExceptionMessage("error parsing DTD"), + self._error_log) + + @property + def name(self): + if self._c_dtd is NULL: + return None + return funicodeOrNone(self._c_dtd.name) + + @property + def external_id(self): + if self._c_dtd is NULL: + return None + return funicodeOrNone(self._c_dtd.ExternalID) + + @property + def system_url(self): + if self._c_dtd is NULL: + return None + return funicodeOrNone(self._c_dtd.SystemID) + + def iterelements(self): + cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_DECL: + node = _DTDElementDecl() + node._dtd = self + node._c_node = c_node + yield node + c_node = c_node.next + + def elements(self): + return list(self.iterelements()) + + def iterentities(self): + cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL + while c_node is not NULL: + if c_node.type == tree.XML_ENTITY_DECL: + node = _DTDEntityDecl() + node._dtd = self + node._c_node = c_node + yield node + c_node = c_node.next + + def entities(self): + return list(self.iterentities()) + + def __dealloc__(self): + tree.xmlFreeDtd(self._c_dtd) + + def __call__(self, etree): + """__call__(self, etree) + + Validate doc using the DTD. + + Returns true if the document is valid, false if not. + """ + cdef _Document doc + cdef _Element root_node + cdef xmlDoc* c_doc + cdef dtdvalid.xmlValidCtxt* valid_ctxt + cdef int ret = -1 + + assert self._c_dtd is not NULL, "DTD not initialised" + doc = _documentOrRaise(etree) + root_node = _rootNodeOrRaise(etree) + + valid_ctxt = dtdvalid.xmlNewValidCtxt() + if valid_ctxt is NULL: + raise DTDError("Failed to create validation context") + + # work around error reporting bug in libxml2 <= 2.9.1 (and later?) + # https://bugzilla.gnome.org/show_bug.cgi?id=724903 + valid_ctxt.error = _nullGenericErrorFunc + valid_ctxt.userData = NULL + + try: + with self._error_log: + c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node) + ret = dtdvalid.xmlValidateDtd(valid_ctxt, c_doc, self._c_dtd) + _destroyFakeDoc(doc._c_doc, c_doc) + finally: + dtdvalid.xmlFreeValidCtxt(valid_ctxt) + + if ret == -1: + raise DTDValidateError("Internal error in DTD validation", + self._error_log) + return ret == 1 + + +cdef tree.xmlDtd* _parseDtdFromFilelike(file) except NULL: + cdef _ExceptionContext exc_context + cdef _FileReaderContext dtd_parser + cdef _ErrorLog error_log + cdef tree.xmlDtd* c_dtd = NULL + exc_context = _ExceptionContext() + dtd_parser = _FileReaderContext(file, exc_context, None) + error_log = _ErrorLog() + + with error_log: + c_dtd = dtd_parser._readDtd() + + exc_context._raise_if_stored() + if c_dtd is NULL: + raise DTDParseError("error parsing DTD", error_log) + return c_dtd + +cdef DTD _dtdFactory(tree.xmlDtd* c_dtd): + # do not run through DTD.__init__()! + cdef DTD dtd + if c_dtd is NULL: + return None + dtd = DTD.__new__(DTD) + dtd._c_dtd = _copyDtd(c_dtd) + _Validator.__init__(dtd) + return dtd + + +cdef tree.xmlDtd* _copyDtd(tree.xmlDtd* c_orig_dtd) except NULL: + """ + Copy a DTD. libxml2 (currently) fails to set up the element->attributes + links when copying DTDs, so we have to rebuild them here. + """ + c_dtd = tree.xmlCopyDtd(c_orig_dtd) + if not c_dtd: + raise MemoryError + cdef tree.xmlNode* c_node = c_dtd.children + while c_node: + if c_node.type == tree.XML_ATTRIBUTE_DECL: + _linkDtdAttribute(c_dtd, c_node) + c_node = c_node.next + return c_dtd + + +cdef void _linkDtdAttribute(tree.xmlDtd* c_dtd, tree.xmlAttribute* c_attr) noexcept: + """ + Create the link to the DTD attribute declaration from the corresponding + element declaration. + """ + c_elem = dtdvalid.xmlGetDtdElementDesc(c_dtd, c_attr.elem) + if not c_elem: + # no such element? something is wrong with the DTD ... + return + c_pos = c_elem.attributes + if not c_pos: + c_elem.attributes = c_attr + c_attr.nexth = NULL + return + # libxml2 keeps namespace declarations first, and we need to make + # sure we don't re-insert attributes that are already there + if _isDtdNsDecl(c_attr): + if not _isDtdNsDecl(c_pos): + c_elem.attributes = c_attr + c_attr.nexth = c_pos + return + while c_pos != c_attr and c_pos.nexth and _isDtdNsDecl(c_pos.nexth): + c_pos = c_pos.nexth + else: + # append at end + while c_pos != c_attr and c_pos.nexth: + c_pos = c_pos.nexth + if c_pos == c_attr: + return + c_attr.nexth = c_pos.nexth + c_pos.nexth = c_attr + + +cdef bint _isDtdNsDecl(tree.xmlAttribute* c_attr) noexcept: + if cstring_h.strcmp(c_attr.name, "xmlns") == 0: + return True + if (c_attr.prefix is not NULL and + cstring_h.strcmp(c_attr.prefix, "xmlns") == 0): + return True + return False diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/etree_api.h b/llmeval-env/lib/python3.10/site-packages/lxml/etree_api.h new file mode 100644 index 0000000000000000000000000000000000000000..b0ebb13dbd535c0b4bcb4ef39536aaf0aa0f0ffe --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/etree_api.h @@ -0,0 +1,195 @@ +/* Generated by Cython 3.0.10 */ + +#ifndef __PYX_HAVE_API__lxml__etree +#define __PYX_HAVE_API__lxml__etree +#ifdef __MINGW64__ +#define MS_WIN64 +#endif +#include "Python.h" +#include "etree.h" + +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0; +#define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0; +#define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0; +#define newElementTree __pyx_api_f_4lxml_5etree_newElementTree +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0; +#define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0; +#define elementFactory __pyx_api_f_4lxml_5etree_elementFactory +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0; +#define makeElement __pyx_api_f_4lxml_5etree_makeElement +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0; +#define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement +static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0; +#define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction +static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0; +#define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass +static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0; +#define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass +static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0; +#define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback +static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define tagMatches __pyx_api_f_4lxml_5etree_tagMatches +static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0; +#define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0; +#define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise +static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0; +#define hasText __pyx_api_f_4lxml_5etree_hasText +static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0; +#define hasTail __pyx_api_f_4lxml_5etree_hasTail +static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0; +#define textOf __pyx_api_f_4lxml_5etree_textOf +static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0; +#define tailOf __pyx_api_f_4lxml_5etree_tailOf +static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0; +#define setNodeText __pyx_api_f_4lxml_5etree_setNodeText +static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0; +#define setTailText __pyx_api_f_4lxml_5etree_setTailText +static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0; +#define attributeValue __pyx_api_f_4lxml_5etree_attributeValue +static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName +static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0; +#define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue +static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0; +#define iterattributes __pyx_api_f_4lxml_5etree_iterattributes +static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0; +#define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes +static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0; +#define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue +static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0; +#define delAttribute __pyx_api_f_4lxml_5etree_delAttribute +static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName +static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0; +#define hasChild __pyx_api_f_4lxml_5etree_hasChild +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0; +#define findChild __pyx_api_f_4lxml_5etree_findChild +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0; +#define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0; +#define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards +static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0; +#define nextElement __pyx_api_f_4lxml_5etree_nextElement +static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0; +#define previousElement __pyx_api_f_4lxml_5etree_previousElement +static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0; +#define appendChild __pyx_api_f_4lxml_5etree_appendChild +static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0; +#define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement +static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0; +#define pyunicode __pyx_api_f_4lxml_5etree_pyunicode +static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0; +#define utf8 __pyx_api_f_4lxml_5etree_utf8 +static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0; +#define getNsTag __pyx_api_f_4lxml_5etree_getNsTag +static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0; +#define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs +static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0; +#define namespacedName __pyx_api_f_4lxml_5etree_namespacedName +static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0; +#define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName +static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0; +#define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext +static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0; +#define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch +static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix +#ifndef __PYX_HAVE_RT_ImportFunction_3_0_10 +#define __PYX_HAVE_RT_ImportFunction_3_0_10 +static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); + if (!d) + goto bad; + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); + goto bad; + } + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(d); + return -1; +} +#endif + + +static int import_lxml__etree(void) { + PyObject *module = 0; + module = PyImport_ImportModule("lxml.etree"); + if (!module) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad; + 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; + 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; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad; + 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; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad; + 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; + Py_DECREF(module); module = 0; + return 0; + bad: + Py_XDECREF(module); + return -1; +} + +#endif /* !__PYX_HAVE_API__lxml__etree */ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_diffcommand.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_diffcommand.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..927c2713e13a8b2ece4459700e5df0cae7062c32 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_diffcommand.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_setmixin.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_setmixin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e5aef556cee4e565b98deddd012aaddead066f8 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/_setmixin.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/builder.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ef4e827d07835be076f3ef9b569fea2707e6733 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/builder.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/diff.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/diff.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca59a4d5abfd4d02365c22d84f74aa98b72a29ab Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/diff.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/soupparser.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/soupparser.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..226340edc56f200507f985c086caea74ac860548 Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/html/__pycache__/soupparser.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/_html5builder.py b/llmeval-env/lib/python3.10/site-packages/lxml/html/_html5builder.py new file mode 100644 index 0000000000000000000000000000000000000000..a88ed944f47067f0560821c8e749c0bbb5f08e00 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/html/_html5builder.py @@ -0,0 +1,100 @@ +""" +Legacy module - don't use in new code! + +html5lib now has its own proper implementation. + +This module implements a tree builder for html5lib that generates lxml +html element trees. This module uses camelCase as it follows the +html5lib style guide. +""" + +from html5lib.treebuilders import _base, etree as etree_builders +from lxml import html, etree + + +class DocumentType: + + def __init__(self, name, publicId, systemId): + self.name = name + self.publicId = publicId + self.systemId = systemId + +class Document: + + def __init__(self): + self._elementTree = None + self.childNodes = [] + + def appendChild(self, element): + self._elementTree.getroot().addnext(element._element) + + +class TreeBuilder(_base.TreeBuilder): + documentClass = Document + doctypeClass = DocumentType + elementClass = None + commentClass = None + fragmentClass = Document + + def __init__(self, *args, **kwargs): + html_builder = etree_builders.getETreeModule(html, fullTree=False) + etree_builder = etree_builders.getETreeModule(etree, fullTree=False) + self.elementClass = html_builder.Element + self.commentClass = etree_builder.Comment + _base.TreeBuilder.__init__(self, *args, **kwargs) + + def reset(self): + _base.TreeBuilder.reset(self) + self.rootInserted = False + self.initialComments = [] + self.doctype = None + + def getDocument(self): + return self.document._elementTree + + def getFragment(self): + fragment = [] + element = self.openElements[0]._element + if element.text: + fragment.append(element.text) + fragment.extend(element.getchildren()) + if element.tail: + fragment.append(element.tail) + return fragment + + def insertDoctype(self, name, publicId, systemId): + doctype = self.doctypeClass(name, publicId, systemId) + self.doctype = doctype + + def insertComment(self, data, parent=None): + if not self.rootInserted: + self.initialComments.append(data) + else: + _base.TreeBuilder.insertComment(self, data, parent) + + def insertRoot(self, name): + buf = [] + if self.doctype and self.doctype.name: + buf.append('') + buf.append('') + root = html.fromstring(''.join(buf)) + + # Append the initial comments: + for comment in self.initialComments: + root.addprevious(etree.Comment(comment)) + + # Create the root document and add the ElementTree to it + self.document = self.documentClass() + self.document._elementTree = root.getroottree() + + # Add the root element to the internal child/open data structures + root_element = self.elementClass(name) + root_element._element = root + self.document.childNodes.append(root_element) + self.openElements.append(root_element) + + self.rootInserted = True diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/clean.py b/llmeval-env/lib/python3.10/site-packages/lxml/html/clean.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b9e96d8745e99cef8d217cbddc34f60186862a --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/html/clean.py @@ -0,0 +1,21 @@ +# cython: language_level=3str + +"""Backward-compatibility module for lxml_html_clean""" + +try: + from lxml_html_clean import * + + __all__ = [ + "clean_html", + "clean", + "Cleaner", + "autolink", + "autolink_html", + "word_break", + "word_break_html", + ] +except ImportError: + raise ImportError( + "lxml.html.clean module is now a separate project lxml_html_clean.\n" + "Install lxml[html_clean] or lxml_html_clean directly." + ) from None diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so b/llmeval-env/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..449c670484a2d8c67a2e391e9deec687c7f8a85c Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/html/diff.cpython-310-x86_64-linux-gnu.so differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/html5parser.py b/llmeval-env/lib/python3.10/site-packages/lxml/html/html5parser.py new file mode 100644 index 0000000000000000000000000000000000000000..2f7be1568977aff1ccc6533f0626226e0f57bec9 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/html/html5parser.py @@ -0,0 +1,260 @@ +""" +An interface to html5lib that mimics the lxml.html interface. +""" +import sys +import string + +from html5lib import HTMLParser as _HTMLParser +from html5lib.treebuilders.etree_lxml import TreeBuilder +from lxml import etree +from lxml.html import Element, XHTML_NAMESPACE, _contains_block_level_tag + +# python3 compatibility +try: + _strings = basestring +except NameError: + _strings = (bytes, str) +try: + from urllib2 import urlopen +except ImportError: + from urllib.request import urlopen +try: + from urlparse import urlparse +except ImportError: + from urllib.parse import urlparse + + +class HTMLParser(_HTMLParser): + """An html5lib HTML parser with lxml as tree.""" + + def __init__(self, strict=False, **kwargs): + _HTMLParser.__init__(self, strict=strict, tree=TreeBuilder, **kwargs) + + +try: + from html5lib import XHTMLParser as _XHTMLParser +except ImportError: + pass +else: + class XHTMLParser(_XHTMLParser): + """An html5lib XHTML Parser with lxml as tree.""" + + def __init__(self, strict=False, **kwargs): + _XHTMLParser.__init__(self, strict=strict, tree=TreeBuilder, **kwargs) + + xhtml_parser = XHTMLParser() + + +def _find_tag(tree, tag): + elem = tree.find(tag) + if elem is not None: + return elem + return tree.find('{%s}%s' % (XHTML_NAMESPACE, tag)) + + +def document_fromstring(html, guess_charset=None, parser=None): + """ + Parse a whole document into a string. + + If `guess_charset` is true, or if the input is not Unicode but a + byte string, the `chardet` library will perform charset guessing + on the string. + """ + if not isinstance(html, _strings): + raise TypeError('string required') + + if parser is None: + parser = html_parser + + options = {} + if guess_charset is None and isinstance(html, bytes): + # html5lib does not accept useChardet as an argument, if it + # detected the html argument would produce unicode objects. + guess_charset = True + if guess_charset is not None: + options['useChardet'] = guess_charset + return parser.parse(html, **options).getroot() + + +def fragments_fromstring(html, no_leading_text=False, + guess_charset=None, parser=None): + """Parses several HTML elements, returning a list of elements. + + The first item in the list may be a string. If no_leading_text is true, + then it will be an error if there is leading text, and it will always be + a list of only elements. + + If `guess_charset` is true, the `chardet` library will perform charset + guessing on the string. + """ + if not isinstance(html, _strings): + raise TypeError('string required') + + if parser is None: + parser = html_parser + + options = {} + if guess_charset is None and isinstance(html, bytes): + # html5lib does not accept useChardet as an argument, if it + # detected the html argument would produce unicode objects. + guess_charset = False + if guess_charset is not None: + options['useChardet'] = guess_charset + children = parser.parseFragment(html, 'div', **options) + if children and isinstance(children[0], _strings): + if no_leading_text: + if children[0].strip(): + raise etree.ParserError('There is leading text: %r' % + children[0]) + del children[0] + return children + + +def fragment_fromstring(html, create_parent=False, + guess_charset=None, parser=None): + """Parses a single HTML element; it is an error if there is more than + one element, or if anything but whitespace precedes or follows the + element. + + If 'create_parent' is true (or is a tag name) then a parent node + will be created to encapsulate the HTML in a single element. In + this case, leading or trailing text is allowed. + + If `guess_charset` is true, the `chardet` library will perform charset + guessing on the string. + """ + if not isinstance(html, _strings): + raise TypeError('string required') + + accept_leading_text = bool(create_parent) + + elements = fragments_fromstring( + html, guess_charset=guess_charset, parser=parser, + no_leading_text=not accept_leading_text) + + if create_parent: + if not isinstance(create_parent, _strings): + create_parent = 'div' + new_root = Element(create_parent) + if elements: + if isinstance(elements[0], _strings): + new_root.text = elements[0] + del elements[0] + new_root.extend(elements) + return new_root + + if not elements: + raise etree.ParserError('No elements found') + if len(elements) > 1: + raise etree.ParserError('Multiple elements found') + result = elements[0] + if result.tail and result.tail.strip(): + raise etree.ParserError('Element followed by text: %r' % result.tail) + result.tail = None + return result + + +def fromstring(html, guess_charset=None, parser=None): + """Parse the html, returning a single element/document. + + This tries to minimally parse the chunk of text, without knowing if it + is a fragment or a document. + + 'base_url' will set the document's base_url attribute (and the tree's + docinfo.URL) + + If `guess_charset` is true, or if the input is not Unicode but a + byte string, the `chardet` library will perform charset guessing + on the string. + """ + if not isinstance(html, _strings): + raise TypeError('string required') + doc = document_fromstring(html, parser=parser, + guess_charset=guess_charset) + + # document starts with doctype or , full document! + start = html[:50] + if isinstance(start, bytes): + # Allow text comparison in python3. + # Decode as ascii, that also covers latin-1 and utf-8 for the + # characters we need. + start = start.decode('ascii', 'replace') + + start = start.lstrip().lower() + if start.startswith(' implies too much structure. + if _contains_block_level_tag(body): + body.tag = 'div' + else: + body.tag = 'span' + return body + + +def parse(filename_url_or_file, guess_charset=None, parser=None): + """Parse a filename, URL, or file-like object into an HTML document + tree. Note: this returns a tree, not an element. Use + ``parse(...).getroot()`` to get the document root. + + If ``guess_charset`` is true, the ``useChardet`` option is passed into + html5lib to enable character detection. This option is on by default + when parsing from URLs, off by default when parsing from file(-like) + objects (which tend to return Unicode more often than not), and on by + default when parsing from a file path (which is read in binary mode). + """ + if parser is None: + parser = html_parser + if not isinstance(filename_url_or_file, _strings): + fp = filename_url_or_file + if guess_charset is None: + # assume that file-like objects return Unicode more often than bytes + guess_charset = False + elif _looks_like_url(filename_url_or_file): + fp = urlopen(filename_url_or_file) + if guess_charset is None: + # assume that URLs return bytes + guess_charset = True + else: + fp = open(filename_url_or_file, 'rb') + if guess_charset is None: + guess_charset = True + + options = {} + # html5lib does not accept useChardet as an argument, if it + # detected the html argument would produce unicode objects. + if guess_charset: + options['useChardet'] = guess_charset + return parser.parse(fp, **options) + + +def _looks_like_url(str): + scheme = urlparse(str)[0] + if not scheme: + return False + elif (sys.platform == 'win32' and + scheme in string.ascii_letters + and len(scheme) == 1): + # looks like a 'normal' absolute path + return False + else: + return True + + +html_parser = HTMLParser() diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/html/soupparser.py b/llmeval-env/lib/python3.10/site-packages/lxml/html/soupparser.py new file mode 100644 index 0000000000000000000000000000000000000000..b288a8a1597663ea2cbaa55bc41e46434a3a589f --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/html/soupparser.py @@ -0,0 +1,314 @@ +"""External interface to the BeautifulSoup HTML parser. +""" + +__all__ = ["fromstring", "parse", "convert_tree"] + +import re +from lxml import etree, html + +try: + from bs4 import ( + BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString, + Declaration, Doctype) + _DECLARATION_OR_DOCTYPE = (Declaration, Doctype) +except ImportError: + from BeautifulSoup import ( + BeautifulSoup, Tag, Comment, ProcessingInstruction, NavigableString, + Declaration) + _DECLARATION_OR_DOCTYPE = Declaration + + +def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs): + """Parse a string of HTML data into an Element tree using the + BeautifulSoup parser. + + Returns the root ```` Element of the tree. + + You can pass a different BeautifulSoup parser through the + `beautifulsoup` keyword, and a diffent Element factory function + through the `makeelement` keyword. By default, the standard + ``BeautifulSoup`` class and the default factory of `lxml.html` are + used. + """ + return _parse(data, beautifulsoup, makeelement, **bsargs) + + +def parse(file, beautifulsoup=None, makeelement=None, **bsargs): + """Parse a file into an ElemenTree using the BeautifulSoup parser. + + You can pass a different BeautifulSoup parser through the + `beautifulsoup` keyword, and a diffent Element factory function + through the `makeelement` keyword. By default, the standard + ``BeautifulSoup`` class and the default factory of `lxml.html` are + used. + """ + if not hasattr(file, 'read'): + file = open(file) + root = _parse(file, beautifulsoup, makeelement, **bsargs) + return etree.ElementTree(root) + + +def convert_tree(beautiful_soup_tree, makeelement=None): + """Convert a BeautifulSoup tree to a list of Element trees. + + Returns a list instead of a single root Element to support + HTML-like soup with more than one root element. + + You can pass a different Element factory through the `makeelement` + keyword. + """ + root = _convert_tree(beautiful_soup_tree, makeelement) + children = root.getchildren() + for child in children: + root.remove(child) + return children + + +# helpers + +def _parse(source, beautifulsoup, makeelement, **bsargs): + if beautifulsoup is None: + beautifulsoup = BeautifulSoup + if hasattr(beautifulsoup, "HTML_ENTITIES"): # bs3 + if 'convertEntities' not in bsargs: + bsargs['convertEntities'] = 'html' + if hasattr(beautifulsoup, "DEFAULT_BUILDER_FEATURES"): # bs4 + if 'features' not in bsargs: + bsargs['features'] = 'html.parser' # use Python html parser + tree = beautifulsoup(source, **bsargs) + root = _convert_tree(tree, makeelement) + # from ET: wrap the document in a html root element, if necessary + if len(root) == 1 and root[0].tag == "html": + return root[0] + root.tag = "html" + return root + + +_parse_doctype_declaration = re.compile( + r'(?:\s|[ element. However, the document + # may be a soup like 'Hello</head><body>Hi + # all<\p>'. In this example roots is a list containing meta, head + # and body elements. + if first_element_idx is None: + pre_root = post_root = [] + roots = beautiful_soup_tree.contents + else: + pre_root = beautiful_soup_tree.contents[:first_element_idx] + roots = beautiful_soup_tree.contents[first_element_idx:last_element_idx+1] + post_root = beautiful_soup_tree.contents[last_element_idx+1:] + + # Reorganize so that there is one <html> root... + if html_root is not None: + # ... use existing one if possible, ... + i = roots.index(html_root) + html_root.contents = roots[:i] + html_root.contents + roots[i+1:] + else: + # ... otherwise create a new one. + html_root = _PseudoTag(roots) + + convert_node = _init_node_converters(makeelement) + + # Process pre_root + res_root = convert_node(html_root) + prev = res_root + for e in reversed(pre_root): + converted = convert_node(e) + if converted is not None: + prev.addprevious(converted) + prev = converted + + # ditto for post_root + prev = res_root + for e in post_root: + converted = convert_node(e) + if converted is not None: + prev.addnext(converted) + prev = converted + + if declaration is not None: + try: + # bs4 provides full Doctype string + doctype_string = declaration.output_ready() + except AttributeError: + doctype_string = declaration.string + + match = _parse_doctype_declaration(doctype_string) + if not match: + # Something is wrong if we end up in here. Since soupparser should + # tolerate errors, do not raise Exception, just let it pass. + pass + else: + external_id, sys_uri = match.groups() + docinfo = res_root.getroottree().docinfo + # strip quotes and update DOCTYPE values (any of None, '', '...') + docinfo.public_id = external_id and external_id[1:-1] + docinfo.system_url = sys_uri and sys_uri[1:-1] + + return res_root + + +def _init_node_converters(makeelement): + converters = {} + ordered_node_types = [] + + def converter(*types): + def add(handler): + for t in types: + converters[t] = handler + ordered_node_types.append(t) + return handler + return add + + def find_best_converter(node): + for t in ordered_node_types: + if isinstance(node, t): + return converters[t] + return None + + def convert_node(bs_node, parent=None): + # duplicated in convert_tag() below + try: + handler = converters[type(bs_node)] + except KeyError: + handler = converters[type(bs_node)] = find_best_converter(bs_node) + if handler is None: + return None + return handler(bs_node, parent) + + def map_attrs(bs_attrs): + if isinstance(bs_attrs, dict): # bs4 + attribs = {} + for k, v in bs_attrs.items(): + if isinstance(v, list): + v = " ".join(v) + attribs[k] = unescape(v) + else: + attribs = {k: unescape(v) for k, v in bs_attrs} + return attribs + + def append_text(parent, text): + if len(parent) == 0: + parent.text = (parent.text or '') + text + else: + parent[-1].tail = (parent[-1].tail or '') + text + + # converters are tried in order of their definition + + @converter(Tag, _PseudoTag) + def convert_tag(bs_node, parent): + attrs = bs_node.attrs + if parent is not None: + attribs = map_attrs(attrs) if attrs else None + res = etree.SubElement(parent, bs_node.name, attrib=attribs) + else: + attribs = map_attrs(attrs) if attrs else {} + res = makeelement(bs_node.name, attrib=attribs) + + for child in bs_node: + # avoid double recursion by inlining convert_node(), see above + try: + handler = converters[type(child)] + except KeyError: + pass + else: + if handler is not None: + handler(child, res) + continue + convert_node(child, res) + return res + + @converter(Comment) + def convert_comment(bs_node, parent): + res = html.HtmlComment(bs_node) + if parent is not None: + parent.append(res) + return res + + @converter(ProcessingInstruction) + def convert_pi(bs_node, parent): + if bs_node.endswith('?'): + # The PI is of XML style (<?as df?>) but BeautifulSoup + # interpreted it as being SGML style (<?as df>). Fix. + bs_node = bs_node[:-1] + res = etree.ProcessingInstruction(*bs_node.split(' ', 1)) + if parent is not None: + parent.append(res) + return res + + @converter(NavigableString) + def convert_text(bs_node, parent): + if parent is not None: + append_text(parent, unescape(bs_node)) + return None + + return convert_node + + +# copied from ET's ElementSoup + +try: + from html.entities import name2codepoint # Python 3 +except ImportError: + from htmlentitydefs import name2codepoint + + +handle_entities = re.compile(r"&(\w+);").sub + + +try: + unichr +except NameError: + # Python 3 + unichr = chr + + +def unescape(string): + if not string: + return '' + # work around oddities in BeautifulSoup's entity handling + def unescape_entity(m): + try: + return unichr(name2codepoint[m.group(1)]) + except KeyError: + return m.group(0) # use as is + return handle_entities(unescape_entity, string) diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__init__.py b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a157a8224e7941828a9fbf8c9994bc5325ee7b05 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__init__.py @@ -0,0 +1,348 @@ +"""The ``lxml.isoschematron`` package implements ISO Schematron support on top +of the pure-xslt 'skeleton' implementation. +""" + +import sys +import os.path +from lxml import etree as _etree # due to validator __init__ signature + + +# some compat stuff, borrowed from lxml.html +try: + unicode +except NameError: + # Python 3 + unicode = str +try: + basestring +except NameError: + # Python 3 + basestring = str + + +__all__ = ['extract_xsd', 'extract_rng', 'iso_dsdl_include', + 'iso_abstract_expand', 'iso_svrl_for_xslt1', + 'svrl_validation_errors', 'schematron_schema_valid', + 'stylesheet_params', 'Schematron'] + + +# some namespaces +#FIXME: Maybe lxml should provide a dedicated place for common namespace +#FIXME: definitions? +XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema" +RELAXNG_NS = "http://relaxng.org/ns/structure/1.0" +SCHEMATRON_NS = "http://purl.oclc.org/dsdl/schematron" +SVRL_NS = "http://purl.oclc.org/dsdl/svrl" + + +# some helpers +_schematron_root = '{%s}schema' % SCHEMATRON_NS +_xml_schema_root = '{%s}schema' % XML_SCHEMA_NS +_resources_dir = os.path.join(os.path.dirname(__file__), 'resources') + + +# the iso-schematron skeleton implementation steps aka xsl transformations +extract_xsd = _etree.XSLT(_etree.parse( + os.path.join(_resources_dir, 'xsl', 'XSD2Schtrn.xsl'))) +extract_rng = _etree.XSLT(_etree.parse( + os.path.join(_resources_dir, 'xsl', 'RNG2Schtrn.xsl'))) +iso_dsdl_include = _etree.XSLT(_etree.parse( + os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1', + 'iso_dsdl_include.xsl'))) +iso_abstract_expand = _etree.XSLT(_etree.parse( + os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1', + 'iso_abstract_expand.xsl'))) +iso_svrl_for_xslt1 = _etree.XSLT(_etree.parse( + os.path.join(_resources_dir, + 'xsl', 'iso-schematron-xslt1', 'iso_svrl_for_xslt1.xsl'))) + + +# svrl result accessors +svrl_validation_errors = _etree.XPath( + '//svrl:failed-assert', namespaces={'svrl': SVRL_NS}) + +# RelaxNG validator for schematron schemas +schematron_schema_valid_supported = False +try: + schematron_schema_valid = _etree.RelaxNG( + file=os.path.join(_resources_dir, 'rng', 'iso-schematron.rng')) + schematron_schema_valid_supported = True +except _etree.RelaxNGParseError: + # Some distributions delete the file due to licensing issues. + def schematron_schema_valid(arg): + raise NotImplementedError("Validating the ISO schematron requires iso-schematron.rng") + + +def stylesheet_params(**kwargs): + """Convert keyword args to a dictionary of stylesheet parameters. + XSL stylesheet parameters must be XPath expressions, i.e.: + + * string expressions, like "'5'" + * simple (number) expressions, like "5" + * valid XPath expressions, like "/a/b/text()" + + This function converts native Python keyword arguments to stylesheet + parameters following these rules: + If an arg is a string wrap it with XSLT.strparam(). + If an arg is an XPath object use its path string. + If arg is None raise TypeError. + Else convert arg to string. + """ + result = {} + for key, val in kwargs.items(): + if isinstance(val, basestring): + val = _etree.XSLT.strparam(val) + elif val is None: + raise TypeError('None not allowed as a stylesheet parameter') + elif not isinstance(val, _etree.XPath): + val = unicode(val) + result[key] = val + return result + + +# helper function for use in Schematron __init__ +def _stylesheet_param_dict(paramsDict, kwargsDict): + """Return a copy of paramsDict, updated with kwargsDict entries, wrapped as + stylesheet arguments. + kwargsDict entries with a value of None are ignored. + """ + # beware of changing mutable default arg + paramsDict = dict(paramsDict) + for k, v in kwargsDict.items(): + if v is not None: # None values do not override + paramsDict[k] = v + paramsDict = stylesheet_params(**paramsDict) + return paramsDict + + +class Schematron(_etree._Validator): + """An ISO Schematron validator. + + Pass a root Element or an ElementTree to turn it into a validator. + Alternatively, pass a filename as keyword argument 'file' to parse from + the file system. + + Schematron is a less well known, but very powerful schema language. + The main idea is to use the capabilities of XPath to put restrictions on + the structure and the content of XML documents. + + The standard behaviour is to fail on ``failed-assert`` findings only + (``ASSERTS_ONLY``). To change this, you can either pass a report filter + function to the ``error_finder`` parameter (e.g. ``ASSERTS_AND_REPORTS`` + or a custom ``XPath`` object), or subclass isoschematron.Schematron for + complete control of the validation process. + + Built on the Schematron language 'reference' skeleton pure-xslt + implementation, the validator is created as an XSLT 1.0 stylesheet using + these steps: + + 0) (Extract from XML Schema or RelaxNG schema) + 1) Process inclusions + 2) Process abstract patterns + 3) Compile the schematron schema to XSLT + + The ``include`` and ``expand`` keyword arguments can be used to switch off + steps 1) and 2). + To set parameters for steps 1), 2) and 3) hand parameter dictionaries to the + keyword arguments ``include_params``, ``expand_params`` or + ``compile_params``. + For convenience, the compile-step parameter ``phase`` is also exposed as a + keyword argument ``phase``. This takes precedence if the parameter is also + given in the parameter dictionary. + + If ``store_schematron`` is set to True, the (included-and-expanded) + schematron document tree is stored and available through the ``schematron`` + property. + If ``store_xslt`` is set to True, the validation XSLT document tree will be + stored and can be retrieved through the ``validator_xslt`` property. + With ``store_report`` set to True (default: False), the resulting validation + report document gets stored and can be accessed as the ``validation_report`` + property. + + If ``validate_schema`` is set to False, the validation of the schema file + itself is disabled. Validation happens by default after building the full + schema, unless the schema validation file cannot be found at import time, + in which case the validation gets disabled. Some lxml distributions exclude + this file due to licensing issues. ISO-Schematron validation can then still + be used normally, but the schemas themselves cannot be validated. + + Here is a usage example:: + + >>> from lxml import etree + >>> from lxml.isoschematron import Schematron + + >>> schematron = Schematron(etree.XML(''' + ... <schema xmlns="http://purl.oclc.org/dsdl/schematron" > + ... <pattern id="id_only_attribute"> + ... <title>id is the only permitted attribute name + ... + ... Attribute + ... is forbidden + ... + ... + ... + ... '''), + ... error_finder=Schematron.ASSERTS_AND_REPORTS) + + >>> xml = etree.XML(''' + ... + ... + ... + ... + ... ''') + + >>> schematron.validate(xml) + False + + >>> xml = etree.XML(''' + ... + ... + ... + ... + ... ''') + + >>> schematron.validate(xml) + True + """ + + # libxml2 error categorization for validation errors + _domain = _etree.ErrorDomains.SCHEMATRONV + _level = _etree.ErrorLevels.ERROR + _error_type = _etree.ErrorTypes.SCHEMATRONV_ASSERT + + # convenience definitions for common behaviours + ASSERTS_ONLY = svrl_validation_errors # Default + ASSERTS_AND_REPORTS = _etree.XPath( + '//svrl:failed-assert | //svrl:successful-report', + namespaces={'svrl': SVRL_NS}) + + def _extract(self, element): + """Extract embedded schematron schema from non-schematron host schema. + This method will only be called by __init__ if the given schema document + is not a schematron schema by itself. + Must return a schematron schema document tree or None. + """ + schematron = None + if element.tag == _xml_schema_root: + schematron = self._extract_xsd(element) + elif element.nsmap[element.prefix] == RELAXNG_NS: + # RelaxNG does not have a single unique root element + schematron = self._extract_rng(element) + return schematron + + # customization points + # etree.XSLT objects that provide the extract, include, expand, compile + # steps + _extract_xsd = extract_xsd + _extract_rng = extract_rng + _include = iso_dsdl_include + _expand = iso_abstract_expand + _compile = iso_svrl_for_xslt1 + + # etree.xpath object that determines input document validity when applied to + # the svrl result report; must return a list of result elements (empty if + # valid) + _validation_errors = ASSERTS_ONLY + + def __init__(self, etree=None, file=None, include=True, expand=True, + include_params={}, expand_params={}, compile_params={}, + store_schematron=False, store_xslt=False, store_report=False, + phase=None, error_finder=ASSERTS_ONLY, + validate_schema=schematron_schema_valid_supported): + super().__init__() + + self._store_report = store_report + self._schematron = None + self._validator_xslt = None + self._validation_report = None + if error_finder is not self.ASSERTS_ONLY: + self._validation_errors = error_finder + + # parse schema document, may be a schematron schema or an XML Schema or + # a RelaxNG schema with embedded schematron rules + root = None + try: + if etree is not None: + if _etree.iselement(etree): + root = etree + else: + root = etree.getroot() + elif file is not None: + root = _etree.parse(file).getroot() + except Exception: + raise _etree.SchematronParseError( + "No tree or file given: %s" % sys.exc_info()[1]) + if root is None: + raise ValueError("Empty tree") + if root.tag == _schematron_root: + schematron = root + else: + schematron = self._extract(root) + if schematron is None: + raise _etree.SchematronParseError( + "Document is not a schematron schema or schematron-extractable") + # perform the iso-schematron skeleton implementation steps to get a + # validating xslt + if include: + schematron = self._include(schematron, **include_params) + if expand: + schematron = self._expand(schematron, **expand_params) + if validate_schema and not schematron_schema_valid(schematron): + raise _etree.SchematronParseError( + "invalid schematron schema: %s" % + schematron_schema_valid.error_log) + if store_schematron: + self._schematron = schematron + # add new compile keyword args here if exposing them + compile_kwargs = {'phase': phase} + compile_params = _stylesheet_param_dict(compile_params, compile_kwargs) + validator_xslt = self._compile(schematron, **compile_params) + if store_xslt: + self._validator_xslt = validator_xslt + self._validator = _etree.XSLT(validator_xslt) + + def __call__(self, etree): + """Validate doc using Schematron. + + Returns true if document is valid, false if not. + """ + self._clear_error_log() + result = self._validator(etree) + if self._store_report: + self._validation_report = result + errors = self._validation_errors(result) + if errors: + if _etree.iselement(etree): + fname = etree.getroottree().docinfo.URL or '' + else: + fname = etree.docinfo.URL or '' + for error in errors: + # Does svrl report the line number, anywhere? Don't think so. + self._append_log_message( + domain=self._domain, type=self._error_type, + level=self._level, line=0, + message=_etree.tostring(error, encoding='unicode'), + filename=fname) + return False + return True + + @property + def schematron(self): + """ISO-schematron schema document (None if object has been initialized + with store_schematron=False). + """ + return self._schematron + + @property + def validator_xslt(self): + """ISO-schematron skeleton implementation XSLT validator document (None + if object has been initialized with store_xslt=False). + """ + return self._validator_xslt + + @property + def validation_report(self): + """ISO-schematron validation result report (None if result-storing has + been turned off). + """ + return self._validation_report diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__pycache__/__init__.cpython-310.pyc b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90e634b62341320e5da758b181b5a89b782bf35f Binary files /dev/null and b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/__pycache__/__init__.cpython-310.pyc differ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng new file mode 100644 index 0000000000000000000000000000000000000000..a4f504af1f7d6f01f7523d447b9304f417c01800 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng @@ -0,0 +1,709 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ltr + rtl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + preserve + default + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl new file mode 100644 index 0000000000000000000000000000000000000000..21a5d2a069cab9fa327d9a3cd4e4d56c21bb10db --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl new file mode 100644 index 0000000000000000000000000000000000000000..de0c9ea700d20c78111660e5fe8bf4ddc5a88137 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl new file mode 100644 index 0000000000000000000000000000000000000000..5018395234799dd65d53a339daaddf445a09dbea --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl @@ -0,0 +1,313 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Suppressed abstract pattern was here + + + + + + + Start pattern based on abstract + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl new file mode 100644 index 0000000000000000000000000000000000000000..44e5573b73077e015d404935479bdc9344c5ea4d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl @@ -0,0 +1,1160 @@ + + + + + + + + + + true + true + true + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Error: Impossible URL in RELAX NG extRef + include + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Error: Impossible URL in Schematron include + + + + + + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + + Schema error: Use include to + include fragments, not a whole + schema + + + + + + + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + Schema error: Use include to include + fragments, not a whole schema + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Error: Impossible URL in Schematron include + + + + + + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Error: Impossible URL in Schematron include + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + Schema error: Use include to include + fragments, not a whole schema + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + Schema error: Use include to include + fragments, not a whole schema + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Error: Impossible URL in DTLL include + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Error: Impossible URL in CRDL include + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Fatal error: Xinclude href contains fragment + identifier # + + + + + + + Fatal error: Sorry, this software only + supports simple ids in XInclude xpointers + + + + + + + Fatal Error: Impossible URL in XInclude + include + + + + + + + + + + + + + + + + + + + + + + + + + + + Unable to open referenced included file and fallback + file: + + + + + + + Unable to open referenced included file: + + + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Error: Impossible URL in XLink embedding + link + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + Unable to open referenced included file: + + + + + + + Unable to locate id attribute: + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl new file mode 100644 index 0000000000000000000000000000000000000000..d59b8f38fe0bf28bc089b033c2acdd314839b8cc --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + ( + / + ) + + + \ No newline at end of file diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl new file mode 100644 index 0000000000000000000000000000000000000000..b0e7175cfff34fb05d631622c9429f0adcda8d5d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl @@ -0,0 +1,1796 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #ALL + + + +false + +true + + + + + true + false + + + + + + + true + false + + + + + + + + + @*| + + * + node() + *|comment()|processing-instruction() + + + + + + + + + + + + +default + +false + + + +1 + + + + + Schema error: Schematron elements in old and new namespaces found + + + + + + + + + + + + + + + + + Schema error: in the queryBinding attribute, use 'xslt' + + + + + 1.0 + + + + + + + + + This XSLT was automatically generated from a Schematron schema. + + + + + 1.0 + + + + + + + + + + Fail: This implementation of ISO Schematron does not work with + schemas using the "" query language. + + + + + Implementers: please note that overriding process-prolog or process-root is + the preferred method for meta-stylesheets to use where possible. + + + + + + + + + + PHASES + + PROLOG + + KEYS + + DEFAULT RULES + + SCHEMA METADATA + + SCHEMATRON PATTERNS + + + + + + + + + + + + + + + + + + + + + + + Phase Error: no phase with name has been defined. + + + + + + + MODE: SCHEMATRON-SELECT-FULL-PATH + This mode can be used to generate an ugly though full XPath for locators + + + + + + + + + + + + + + + + + + + + + + + + + MODE: SCHEMATRON-FULL-PATH + This mode can be used to generate an ugly though full XPath for locators + + + + + + / + + + + + + [] + + + + *[local-name()=' + ' and namespace-uri()=' + + '] + + + [] + + + + + + + + + + / + + @ + + @*[local-name()=' + + ' and namespace-uri()=' + + '] + + + + + + + + + MODE: SCHEMATRON-FULL-PATH-2 + + This mode can be used to generate prefixed XPath for humans + + + + + + / + + + [ + + ] + + + + + /@ + + + + + MODE: GENERATE-ID-FROM-PATH + + + + + + + + + + + + + + + + + + + + + + . + + + + + + + MODE: SCHEMATRON-FULL-PATH-3 + + + This mode can be used to generate prefixed XPath for humans + (Top-level element has index) + + + + + + / + + + [ + + ] + + + + + /@ + + + + + MODE: GENERATE-ID-2 + + + U + + + U + + + + + U. + + n + + + + + U. + + _ + + _ + + + + + Strip characters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Markup Error: no pattern attribute in <active> + + + + Reference Error: the pattern "" has been activated but is not declared + + + + + + + + Markup Error: no test attribute in <assert + + + ASSERT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Markup Error: no test attribute in <report> + + + + REPORT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Markup Error: no id attribute in <diagnostic> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Markup Error: no rule attribute in <extends> + + + Reference Error: the abstract rule "" has been referenced but is not declared + + + + + + + + + + + + + + Markup Error: no name attribute in <key> + + + Markup Error: no path or use attribute in <key> + + + + + + + + + + + + + + + + Markup Error: no path or use attribute in <key> + + + + + + + + + + + + Schema error: The key element is not in the ISO Schematron namespace. Use the XSLT namespace. + + + + + + + + Schema error: Empty href= attribute for include directive. + + + + + + + + + + + + + + Error: Impossible URL in Schematron include + + + + + + + Schema error: Use include to include fragments, not a whole schema + + + + + + + + + + Schema error: Use include to include fragments, not a whole schema + + + + + + + + + + + + + + + Error: Impossible URL in Schematron include + + + + + + + Schema error: Use include to include fragments, not a whole schema + + + + + + + + + + + Schema error: Use include to include fragments, not a whole schema + + + + + + + + + + Warning: Variables should not be used with the "xpath" query language binding. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Markup Error: no uri attribute in <ns> + + + Markup Error: no prefix attribute in <ns> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + //( + + ( + + ) + | + + ) + [not(self::text())] + + + + + + + + + + + + + Schema implementation error: This schema has abstract patterns, yet they are supposed to be preprocessed out already + + + + + + + + + + PATTERN + + + + + + + + + + + + + + + + + + + + Markup Error: no id attribute in <phase> + + + + + + + + Markup Error: no context attribute in <rule> + + + RULE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Markup Error: no id attribute on abstract <rule> + + + Markup Error: (2) context attribute on abstract <rule> + + + + + + Markup Error: context attribute on abstract <rule> + + + + + + + + + + + + + + + + + + + + + + + + + + + Markup Error: no select attribute in <value-of> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Warning: + + must not contain any child elements + + + + + + + + + + + + + + + + + + + + + + + + + Reference error: A diagnostic "" has been referenced but is not declared + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Using the XSLT namespace with a prefix other than "xsl" in + Schematron rules is not supported + in this processor: + + + + + + + + + + + + + + + + + + + + Error: unrecognized element in ISO Schematron namespace: check spelling + and capitalization + + + + + + + + + + + + + Warning: unrecognized element + + + + + + + + + + + + + + + Warning: unrecognized element + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + title + + + + + + + schema-title + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl new file mode 100644 index 0000000000000000000000000000000000000000..dae74ff6a2bd56a4f21147905c3a1661baf0b3ab --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl @@ -0,0 +1,588 @@ + + + + + + + + + + + + + + + + +true + + + + + + + + + + + #ALL + + +false +true +true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + xslt1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +   +   +   + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..e5d6dfcd9e9c2787c32d98b0063a1fa1ec3236ad --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt @@ -0,0 +1,84 @@ +ISO SCHEMATRON 2010 + +XSLT implementation by Rick Jelliffe with assistance from members of Schematron-love-in maillist. + +2010-04-21 + +Two distributions are available. One is for XSLT1 engines. +The other is for XSLT2 engines, such as SAXON 9. + + +This version of Schematron splits the process into a pipeline of several different XSLT stages. + +1) First, preprocess your Schematron schema with iso_dsdl_include.xsl. +This is a macro processor to assemble the schema from various parts. +If your schema is not in separate parts, you can skip this stage. +This stage also generates error messages for some common XPath syntax problems. + +2) Second, preprocess the output from stage 1 with iso_abstract_expand.xsl. +This is a macro processor to convert abstract patterns to real patterns. +If your schema does not use abstract patterns, you can skip this +stage. + +3) Third, compile the Schematron schema into an XSLT script. +This will typically use iso_svrl_for_xslt1.xsl or iso_svrl_for_xslt2.xsl +(which in turn invoke iso_schematron_skeleton_for_xslt1.xsl or iso_schematron_skeleton_for_saxon.xsl) +However, other "meta-stylesheets" are also in common use; the principle of operation is the same. +If your schema uses Schematron phases, supply these as command line/invocation parameters +to this process. + +4) Fourth, run the script generated by stage 3 against the document being validated. +If you are using the SVRL script, then the output of validation will be an XML document. +If your schema uses Schematron parameters, supply these as command line/invocation parameters +to this process. + + +The XSLT2 distribution also features several next generation features, +such as validating multiple documents. See the source code for details. + +Schematron assertions can be written in any language, of course; the file +sch-messages-en.xhtml contains the diagnostics messages from the XSLT2 skeleton +in English, and this can be used as template to localize the skeleton's +error messages. Note that typically programming errors in Schematron are XPath +errors, which requires localized messages from the XSLT engine. + +ANT +--- +To give an example of how to process a document, here is a sample ANT task. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/iterparse.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/iterparse.pxi new file mode 100644 index 0000000000000000000000000000000000000000..f569b865ee980c16c7c8a679ae0f5475745817cc --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/iterparse.pxi @@ -0,0 +1,438 @@ +# iterparse -- event-driven parsing + +DEF __ITERPARSE_CHUNK_SIZE = 32768 + +cdef class iterparse: + """iterparse(self, source, events=("end",), tag=None, \ + attribute_defaults=False, dtd_validation=False, \ + load_dtd=False, no_network=True, remove_blank_text=False, \ + remove_comments=False, remove_pis=False, encoding=None, \ + html=False, recover=None, huge_tree=False, schema=None) + + Incremental parser. + + Parses XML into a tree and generates tuples (event, element) in a + SAX-like fashion. ``event`` is any of 'start', 'end', 'start-ns', + 'end-ns'. + + For 'start' and 'end', ``element`` is the Element that the parser just + found opening or closing. For 'start-ns', it is a tuple (prefix, URI) of + a new namespace declaration. For 'end-ns', it is simply None. Note that + all start and end events are guaranteed to be properly nested. + + The keyword argument ``events`` specifies a sequence of event type names + that should be generated. By default, only 'end' events will be + generated. + + The additional ``tag`` argument restricts the 'start' and 'end' events to + those elements that match the given tag. The ``tag`` argument can also be + a sequence of tags to allow matching more than one tag. By default, + events are generated for all elements. Note that the 'start-ns' and + 'end-ns' events are not impacted by this restriction. + + The other keyword arguments in the constructor are mainly based on the + libxml2 parser configuration. A DTD will also be loaded if validation or + attribute default values are requested. + + Available boolean keyword arguments: + - attribute_defaults: read default attributes from DTD + - dtd_validation: validate (if DTD is available) + - load_dtd: use DTD for parsing + - no_network: prevent network access for related files + - remove_blank_text: discard blank text nodes + - remove_comments: discard comments + - remove_pis: discard processing instructions + - strip_cdata: replace CDATA sections by normal text content (default: True) + - compact: safe memory for short text content (default: True) + - resolve_entities: replace entities by their text value (default: True) + - huge_tree: disable security restrictions and support very deep trees + and very long text content (only affects libxml2 2.7+) + - html: parse input as HTML (default: XML) + - recover: try hard to parse through broken input (default: True for HTML, + False otherwise) + + Other keyword arguments: + - encoding: override the document encoding + - schema: an XMLSchema to validate against + """ + cdef _FeedParser _parser + cdef object _tag + cdef object _events + cdef readonly object root + cdef object _source + cdef object _filename + cdef object _error + cdef bint _close_source_after_read + + def __init__(self, source, events=("end",), *, tag=None, + attribute_defaults=False, dtd_validation=False, + load_dtd=False, no_network=True, remove_blank_text=False, + compact=True, resolve_entities=True, remove_comments=False, + remove_pis=False, strip_cdata=True, encoding=None, + html=False, recover=None, huge_tree=False, collect_ids=True, + XMLSchema schema=None): + if not hasattr(source, 'read'): + source = _getFSPathOrObject(source) + self._filename = source + self._source = open(source, 'rb') + self._close_source_after_read = True + else: + self._filename = _getFilenameForFile(source) + self._source = source + self._close_source_after_read = False + + if recover is None: + recover = html + + if html: + # make sure we're not looking for namespaces + events = [event for event in events + if event not in ('start-ns', 'end-ns')] + parser = HTMLPullParser( + events, + tag=tag, + recover=recover, + base_url=self._filename, + encoding=encoding, + remove_blank_text=remove_blank_text, + remove_comments=remove_comments, + remove_pis=remove_pis, + strip_cdata=strip_cdata, + no_network=no_network, + target=None, # TODO + schema=schema, + compact=compact) + else: + parser = XMLPullParser( + events, + tag=tag, + recover=recover, + base_url=self._filename, + encoding=encoding, + attribute_defaults=attribute_defaults, + dtd_validation=dtd_validation, + load_dtd=load_dtd, + no_network=no_network, + schema=schema, + huge_tree=huge_tree, + remove_blank_text=remove_blank_text, + resolve_entities=resolve_entities, + remove_comments=remove_comments, + remove_pis=remove_pis, + strip_cdata=strip_cdata, + collect_ids=True, + target=None, # TODO + compact=compact) + + self._events = parser.read_events() + self._parser = parser + + @property + def error_log(self): + """The error log of the last (or current) parser run. + """ + return self._parser.feed_error_log + + @property + def resolvers(self): + """The custom resolver registry of the last (or current) parser run. + """ + return self._parser.resolvers + + @property + def version(self): + """The version of the underlying XML parser.""" + return self._parser.version + + def set_element_class_lookup(self, ElementClassLookup lookup = None): + """set_element_class_lookup(self, lookup = None) + + Set a lookup scheme for element classes generated from this parser. + + Reset it by passing None or nothing. + """ + self._parser.set_element_class_lookup(lookup) + + def makeelement(self, _tag, attrib=None, nsmap=None, **_extra): + """makeelement(self, _tag, attrib=None, nsmap=None, **_extra) + + Creates a new element associated with this parser. + """ + self._parser.makeelement( + _tag, attrib=None, nsmap=None, **_extra) + + @cython.final + cdef _close_source(self): + if self._source is None: + return + if not self._close_source_after_read: + self._source = None + return + try: + close = self._source.close + except AttributeError: + close = None + finally: + self._source = None + if close is not None: + close() + + def __iter__(self): + return self + + def __next__(self): + try: + return next(self._events) + except StopIteration: + pass + context = <_SaxParserContext>self._parser._getPushParserContext() + if self._source is not None: + done = False + while not done: + try: + done = self._read_more_events(context) + return next(self._events) + except StopIteration: + pass # no events yet + except Exception as e: + self._error = e + self._close_source() + try: + return next(self._events) + except StopIteration: + break + # nothing left to read or return + if self._error is not None: + error = self._error + self._error = None + raise error + if (context._validator is not None + and not context._validator.isvalid()): + _raiseParseError(context._c_ctxt, self._filename, + context._error_log) + # no errors => all done + raise StopIteration + + @cython.final + cdef bint _read_more_events(self, _SaxParserContext context) except -123: + data = self._source.read(__ITERPARSE_CHUNK_SIZE) + if not isinstance(data, bytes): + self._close_source() + raise TypeError("reading file objects must return bytes objects") + if not data: + try: + self.root = self._parser.close() + finally: + self._close_source() + return True + self._parser.feed(data) + return False + + +cdef enum _IterwalkSkipStates: + IWSKIP_NEXT_IS_START + IWSKIP_SKIP_NEXT + IWSKIP_CAN_SKIP + IWSKIP_CANNOT_SKIP + + +cdef class iterwalk: + """iterwalk(self, element_or_tree, events=("end",), tag=None) + + A tree walker that generates events from an existing tree as if it + was parsing XML data with ``iterparse()``. + + Just as for ``iterparse()``, the ``tag`` argument can be a single tag or a + sequence of tags. + + After receiving a 'start' or 'start-ns' event, the children and + descendants of the current element can be excluded from iteration + by calling the ``skip_subtree()`` method. + """ + cdef _MultiTagMatcher _matcher + cdef list _node_stack + cdef list _events + cdef object _pop_event + cdef object _include_siblings + cdef int _index + cdef int _event_filter + cdef _IterwalkSkipStates _skip_state + + def __init__(self, element_or_tree, events=("end",), tag=None): + cdef _Element root + cdef int ns_count + root = _rootNodeOrRaise(element_or_tree) + self._event_filter = _buildParseEventFilter(events) + if tag is None or tag == '*': + self._matcher = None + else: + self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag) + self._node_stack = [] + self._events = [] + self._pop_event = self._events.pop + self._skip_state = IWSKIP_CANNOT_SKIP # ignore all skip requests by default + + if self._event_filter: + self._index = 0 + if self._matcher is not None and self._event_filter & PARSE_EVENT_FILTER_START: + self._matcher.cacheTags(root._doc) + + # When processing an ElementTree, add events for the preceding comments/PIs. + if self._event_filter & (PARSE_EVENT_FILTER_COMMENT | PARSE_EVENT_FILTER_PI): + if isinstance(element_or_tree, _ElementTree): + self._include_siblings = root + for elem in list(root.itersiblings(preceding=True))[::-1]: + if self._event_filter & PARSE_EVENT_FILTER_COMMENT and elem.tag is Comment: + self._events.append(('comment', elem)) + elif self._event_filter & PARSE_EVENT_FILTER_PI and elem.tag is PI: + self._events.append(('pi', elem)) + + ns_count = self._start_node(root) + self._node_stack.append( (root, ns_count) ) + else: + self._index = -1 + + def __iter__(self): + return self + + def __next__(self): + cdef xmlNode* c_child + cdef _Element node + cdef _Element next_node + cdef int ns_count = 0 + if self._events: + return self._next_event() + if self._matcher is not None and self._index >= 0: + node = self._node_stack[self._index][0] + self._matcher.cacheTags(node._doc) + + # find next node + while self._index >= 0: + node = self._node_stack[self._index][0] + + if self._skip_state == IWSKIP_SKIP_NEXT: + c_child = NULL + else: + c_child = self._process_non_elements( + node._doc, _findChildForwards(node._c_node, 0)) + self._skip_state = IWSKIP_CANNOT_SKIP + + while c_child is NULL: + # back off through parents + self._index -= 1 + node = self._end_node() + if self._index < 0: + break + c_child = self._process_non_elements( + node._doc, _nextElement(node._c_node)) + + if c_child is not NULL: + next_node = _elementFactory(node._doc, c_child) + if self._event_filter & (PARSE_EVENT_FILTER_START | + PARSE_EVENT_FILTER_START_NS): + ns_count = self._start_node(next_node) + elif self._event_filter & PARSE_EVENT_FILTER_END_NS: + ns_count = _countNsDefs(next_node._c_node) + self._node_stack.append( (next_node, ns_count) ) + self._index += 1 + if self._events: + return self._next_event() + + if self._include_siblings is not None: + node, self._include_siblings = self._include_siblings, None + self._process_non_elements(node._doc, _nextElement(node._c_node)) + if self._events: + return self._next_event() + + raise StopIteration + + @cython.final + cdef xmlNode* _process_non_elements(self, _Document doc, xmlNode* c_node): + while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE: + if c_node.type == tree.XML_COMMENT_NODE: + if self._event_filter & PARSE_EVENT_FILTER_COMMENT: + self._events.append( + ("comment", _elementFactory(doc, c_node))) + c_node = _nextElement(c_node) + elif c_node.type == tree.XML_PI_NODE: + if self._event_filter & PARSE_EVENT_FILTER_PI: + self._events.append( + ("pi", _elementFactory(doc, c_node))) + c_node = _nextElement(c_node) + else: + break + return c_node + + @cython.final + cdef _next_event(self): + if self._skip_state == IWSKIP_NEXT_IS_START: + if self._events[0][0] in ('start', 'start-ns'): + self._skip_state = IWSKIP_CAN_SKIP + return self._pop_event(0) + + def skip_subtree(self): + """Prevent descending into the current subtree. + Instead, the next returned event will be the 'end' event of the current element + (if included), ignoring any children or descendants. + + This has no effect right after an 'end' or 'end-ns' event. + """ + if self._skip_state == IWSKIP_CAN_SKIP: + self._skip_state = IWSKIP_SKIP_NEXT + + @cython.final + cdef int _start_node(self, _Element node) except -1: + cdef int ns_count + if self._event_filter & PARSE_EVENT_FILTER_START_NS: + ns_count = _appendStartNsEvents(node._c_node, self._events) + if self._events: + self._skip_state = IWSKIP_NEXT_IS_START + elif self._event_filter & PARSE_EVENT_FILTER_END_NS: + ns_count = _countNsDefs(node._c_node) + else: + ns_count = 0 + if self._event_filter & PARSE_EVENT_FILTER_START: + if self._matcher is None or self._matcher.matches(node._c_node): + self._events.append( ("start", node) ) + self._skip_state = IWSKIP_NEXT_IS_START + return ns_count + + @cython.final + cdef _Element _end_node(self): + cdef _Element node + cdef int i, ns_count + node, ns_count = self._node_stack.pop() + if self._event_filter & PARSE_EVENT_FILTER_END: + if self._matcher is None or self._matcher.matches(node._c_node): + self._events.append( ("end", node) ) + if self._event_filter & PARSE_EVENT_FILTER_END_NS and ns_count: + event = ("end-ns", None) + for i in range(ns_count): + self._events.append(event) + return node + + +cdef int _countNsDefs(xmlNode* c_node) noexcept: + cdef xmlNs* c_ns + cdef int count + count = 0 + c_ns = c_node.nsDef + while c_ns is not NULL: + count += (c_ns.href is not NULL) + c_ns = c_ns.next + return count + + +cdef int _appendStartNsEvents(xmlNode* c_node, list event_list) except -1: + cdef xmlNs* c_ns + cdef int count + count = 0 + c_ns = c_node.nsDef + while c_ns is not NULL: + if c_ns.href: + ns_tuple = (funicodeOrEmpty(c_ns.prefix), + funicode(c_ns.href)) + event_list.append( ("start-ns", ns_tuple) ) + count += 1 + c_ns = c_ns.next + return count diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/lxml.etree_api.h b/llmeval-env/lib/python3.10/site-packages/lxml/lxml.etree_api.h new file mode 100644 index 0000000000000000000000000000000000000000..5efcb431f45d1cb937ce5a9fbf047b6e339fd72d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/lxml.etree_api.h @@ -0,0 +1,195 @@ +/* Generated by Cython 3.0.10 */ + +#ifndef __PYX_HAVE_API__lxml__etree +#define __PYX_HAVE_API__lxml__etree +#ifdef __MINGW64__ +#define MS_WIN64 +#endif +#include "Python.h" +#include "lxml.etree.h" + +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0; +#define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0; +#define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0; +#define newElementTree __pyx_api_f_4lxml_5etree_newElementTree +static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0; +#define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0; +#define elementFactory __pyx_api_f_4lxml_5etree_elementFactory +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0; +#define makeElement __pyx_api_f_4lxml_5etree_makeElement +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0; +#define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement +static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0; +#define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction +static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0; +#define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass +static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0; +#define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass +static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0; +#define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback +static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define tagMatches __pyx_api_f_4lxml_5etree_tagMatches +static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0; +#define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise +static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0; +#define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise +static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0; +#define hasText __pyx_api_f_4lxml_5etree_hasText +static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0; +#define hasTail __pyx_api_f_4lxml_5etree_hasTail +static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0; +#define textOf __pyx_api_f_4lxml_5etree_textOf +static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0; +#define tailOf __pyx_api_f_4lxml_5etree_tailOf +static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0; +#define setNodeText __pyx_api_f_4lxml_5etree_setNodeText +static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0; +#define setTailText __pyx_api_f_4lxml_5etree_setTailText +static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0; +#define attributeValue __pyx_api_f_4lxml_5etree_attributeValue +static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName +static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0; +#define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue +static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0; +#define iterattributes __pyx_api_f_4lxml_5etree_iterattributes +static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0; +#define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes +static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0; +#define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue +static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0; +#define delAttribute __pyx_api_f_4lxml_5etree_delAttribute +static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName +static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0; +#define hasChild __pyx_api_f_4lxml_5etree_hasChild +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0; +#define findChild __pyx_api_f_4lxml_5etree_findChild +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0; +#define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards +static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0; +#define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards +static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0; +#define nextElement __pyx_api_f_4lxml_5etree_nextElement +static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0; +#define previousElement __pyx_api_f_4lxml_5etree_previousElement +static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0; +#define appendChild __pyx_api_f_4lxml_5etree_appendChild +static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0; +#define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement +static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0; +#define pyunicode __pyx_api_f_4lxml_5etree_pyunicode +static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0; +#define utf8 __pyx_api_f_4lxml_5etree_utf8 +static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0; +#define getNsTag __pyx_api_f_4lxml_5etree_getNsTag +static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0; +#define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs +static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0; +#define namespacedName __pyx_api_f_4lxml_5etree_namespacedName +static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0; +#define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName +static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0; +#define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext +static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0; +#define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch +static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0; +#define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix +#ifndef __PYX_HAVE_RT_ImportFunction_3_0_10 +#define __PYX_HAVE_RT_ImportFunction_3_0_10 +static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) { + PyObject *d = 0; + PyObject *cobj = 0; + union { + void (*fp)(void); + void *p; + } tmp; + d = PyObject_GetAttrString(module, (char *)"__pyx_capi__"); + if (!d) + goto bad; + cobj = PyDict_GetItemString(d, funcname); + if (!cobj) { + PyErr_Format(PyExc_ImportError, + "%.200s does not export expected C function %.200s", + PyModule_GetName(module), funcname); + goto bad; + } + if (!PyCapsule_IsValid(cobj, sig)) { + PyErr_Format(PyExc_TypeError, + "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)", + PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj)); + goto bad; + } + tmp.p = PyCapsule_GetPointer(cobj, sig); + *f = tmp.fp; + if (!(*f)) + goto bad; + Py_DECREF(d); + return 0; +bad: + Py_XDECREF(d); + return -1; +} +#endif + + +static int import_lxml__etree(void) { + PyObject *module = 0; + module = PyImport_ImportModule("lxml.etree"); + if (!module) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad; + 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; + 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; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad; + 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; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad; + 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; + if (__Pyx_ImportFunction_3_0_10(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad; + if (__Pyx_ImportFunction_3_0_10(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad; + 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; + Py_DECREF(module); module = 0; + return 0; + bad: + Py_XDECREF(module); + return -1; +} + +#endif /* !__PYX_HAVE_API__lxml__etree */ diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/objectify.pyx b/llmeval-env/lib/python3.10/site-packages/lxml/objectify.pyx new file mode 100644 index 0000000000000000000000000000000000000000..0ff922262ed55ef2d04bdea0f196bd724b736550 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/objectify.pyx @@ -0,0 +1,2145 @@ +# cython: binding=True +# cython: auto_pickle=False +# cython: language_level=3 + +""" +The ``lxml.objectify`` module implements a Python object API for XML. +It is based on `lxml.etree`. +""" + +cimport cython + +from lxml.includes.etreepublic cimport _Document, _Element, ElementBase, ElementClassLookup +from lxml.includes.etreepublic cimport elementFactory, import_lxml__etree, textOf, pyunicode +from lxml.includes.tree cimport const_xmlChar, _xcstr +from lxml cimport python +from lxml.includes cimport tree + +cimport lxml.includes.etreepublic as cetree +cimport libc.string as cstring_h # not to be confused with stdlib 'string' +from libc.string cimport const_char + +__all__ = ['BoolElement', 'DataElement', 'E', 'Element', 'ElementMaker', + 'FloatElement', 'IntElement', 'NoneElement', + 'NumberElement', 'ObjectPath', 'ObjectifiedDataElement', + 'ObjectifiedElement', 'ObjectifyElementClassLookup', + 'PYTYPE_ATTRIBUTE', 'PyType', 'StringElement', 'SubElement', + 'XML', 'annotate', 'deannotate', 'dump', 'enable_recursive_str', + 'fromstring', 'getRegisteredTypes', 'makeparser', 'parse', + 'pyannotate', 'pytypename', 'set_default_parser', + 'set_pytype_attribute_tag', 'xsiannotate'] + +cdef object etree +from lxml import etree +# initialize C-API of lxml.etree +import_lxml__etree() + +__version__ = etree.__version__ + +cdef object _float_is_inf, _float_is_nan +from math import isinf as _float_is_inf, isnan as _float_is_nan + +cdef object re +import re + +cdef tuple IGNORABLE_ERRORS = (ValueError, TypeError) +cdef object is_special_method = re.compile('__.*__$').match + + +cdef object _typename(object t): + cdef const_char* c_name + c_name = python._fqtypename(t) + s = cstring_h.strrchr(c_name, c'.') + if s is not NULL: + c_name = s + 1 + return pyunicode(c_name) + + +# namespace/name for "pytype" hint attribute +cdef object PYTYPE_NAMESPACE +cdef bytes PYTYPE_NAMESPACE_UTF8 +cdef const_xmlChar* _PYTYPE_NAMESPACE + +cdef object PYTYPE_ATTRIBUTE_NAME +cdef bytes PYTYPE_ATTRIBUTE_NAME_UTF8 +cdef const_xmlChar* _PYTYPE_ATTRIBUTE_NAME + +PYTYPE_ATTRIBUTE = None + +cdef unicode TREE_PYTYPE_NAME = "TREE" + +cdef tuple _unicodeAndUtf8(s): + return s, python.PyUnicode_AsUTF8String(s) + +def set_pytype_attribute_tag(attribute_tag=None): + """set_pytype_attribute_tag(attribute_tag=None) + Change name and namespace of the XML attribute that holds Python type + information. + + Do not use this unless you know what you are doing. + + Reset by calling without argument. + + Default: "{http://codespeak.net/lxml/objectify/pytype}pytype" + """ + global PYTYPE_ATTRIBUTE, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME + global PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8 + global PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8 + if attribute_tag is None: + PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8 = \ + _unicodeAndUtf8("http://codespeak.net/lxml/objectify/pytype") + PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8 = \ + _unicodeAndUtf8("pytype") + else: + PYTYPE_NAMESPACE_UTF8, PYTYPE_ATTRIBUTE_NAME_UTF8 = \ + cetree.getNsTag(attribute_tag) + PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8.decode('utf8') + PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8.decode('utf8') + + _PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8 + _PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8 + PYTYPE_ATTRIBUTE = cetree.namespacedNameFromNsName( + _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME) + +set_pytype_attribute_tag() + + +# namespaces for XML Schema +cdef object XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8 +XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8 = \ + _unicodeAndUtf8("http://www.w3.org/2001/XMLSchema") +cdef const_xmlChar* _XML_SCHEMA_NS = _xcstr(XML_SCHEMA_NS_UTF8) + +cdef object XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8 +XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8 = \ + _unicodeAndUtf8("http://www.w3.org/2001/XMLSchema-instance") +cdef const_xmlChar* _XML_SCHEMA_INSTANCE_NS = _xcstr(XML_SCHEMA_INSTANCE_NS_UTF8) + +cdef object XML_SCHEMA_INSTANCE_NIL_ATTR = "{%s}nil" % XML_SCHEMA_INSTANCE_NS +cdef object XML_SCHEMA_INSTANCE_TYPE_ATTR = "{%s}type" % XML_SCHEMA_INSTANCE_NS + + +################################################################################ +# Element class for the main API + +cdef class ObjectifiedElement(ElementBase): + """Main XML Element class. + + Element children are accessed as object attributes. Multiple children + with the same name are available through a list index. Example:: + + >>> root = XML("01") + >>> second_c2 = root.c1.c2[1] + >>> print(second_c2.text) + 1 + + Note that you cannot (and must not) instantiate this class or its + subclasses. + """ + def __iter__(self): + """Iterate over self and all siblings with the same tag. + """ + parent = self.getparent() + if parent is None: + return iter([self]) + return etree.ElementChildIterator(parent, tag=self.tag) + + def __str__(self): + if __RECURSIVE_STR: + return _dump(self, 0) + else: + return textOf(self._c_node) or '' + + # pickle support for objectified Element + def __reduce__(self): + return fromstring, (etree.tostring(self),) + + @property + def text(self): + return textOf(self._c_node) + + @property + def __dict__(self): + """A fake implementation for __dict__ to support dir() etc. + + Note that this only considers the first child with a given name. + """ + cdef _Element child + cdef dict children + c_ns = tree._getNs(self._c_node) + tag = "{%s}*" % pyunicode(c_ns) if c_ns is not NULL else None + children = {} + for child in etree.ElementChildIterator(self, tag=tag): + if c_ns is NULL and tree._getNs(child._c_node) is not NULL: + continue + name = pyunicode(child._c_node.name) + if name not in children: + children[name] = child + return children + + def __len__(self): + """Count self and siblings with the same tag. + """ + return _countSiblings(self._c_node) + + def countchildren(self): + """countchildren(self) + + Return the number of children of this element, regardless of their + name. + """ + # copied from etree + cdef Py_ssize_t c + cdef tree.xmlNode* c_node + c = 0 + c_node = self._c_node.children + while c_node is not NULL: + if tree._isElement(c_node): + c += 1 + c_node = c_node.next + return c + + def getchildren(self): + """getchildren(self) + + Returns a sequence of all direct children. The elements are + returned in document order. + """ + cdef tree.xmlNode* c_node + result = [] + c_node = self._c_node.children + while c_node is not NULL: + if tree._isElement(c_node): + result.append(cetree.elementFactory(self._doc, c_node)) + c_node = c_node.next + return result + + def __getattr__(self, tag): + """Return the (first) child with the given tag name. If no namespace + is provided, the child will be looked up in the same one as self. + """ + return _lookupChildOrRaise(self, tag) + + def __setattr__(self, tag, value): + """Set the value of the (first) child with the given tag name. If no + namespace is provided, the child will be looked up in the same one as + self. + """ + cdef _Element element + # properties are looked up /after/ __setattr__, so we must emulate them + if tag == 'text' or tag == 'pyval': + # read-only ! + raise TypeError, f"attribute '{tag}' of '{_typename(self)}' objects is not writable" + elif tag == 'tail': + cetree.setTailText(self._c_node, value) + return + elif tag == 'tag': + ElementBase.tag.__set__(self, value) + return + elif tag == 'base': + ElementBase.base.__set__(self, value) + return + tag = _buildChildTag(self, tag) + element = _lookupChild(self, tag) + if element is None: + _appendValue(self, tag, value) + else: + _replaceElement(element, value) + + def __delattr__(self, tag): + child = _lookupChildOrRaise(self, tag) + self.remove(child) + + def addattr(self, tag, value): + """addattr(self, tag, value) + + Add a child value to the element. + + As opposed to append(), it sets a data value, not an element. + """ + _appendValue(self, _buildChildTag(self, tag), value) + + def __getitem__(self, key): + """Return a sibling, counting from the first child of the parent. The + method behaves like both a dict and a sequence. + + * If argument is an integer, returns the sibling at that position. + + * If argument is a string, does the same as getattr(). This can be + used to provide namespaces for element lookup, or to look up + children with special names (``text`` etc.). + + * If argument is a slice object, returns the matching slice. + """ + cdef tree.xmlNode* c_self_node + cdef tree.xmlNode* c_parent + cdef tree.xmlNode* c_node + cdef Py_ssize_t c_index + if python._isString(key): + return _lookupChildOrRaise(self, key) + elif isinstance(key, slice): + return list(self)[key] + # normal item access + c_index = key # raises TypeError if necessary + c_self_node = self._c_node + c_parent = c_self_node.parent + if c_parent is NULL: + if c_index == 0 or c_index == -1: + return self + raise IndexError, unicode(key) + if c_index < 0: + c_node = c_parent.last + else: + c_node = c_parent.children + c_node = _findFollowingSibling( + c_node, tree._getNs(c_self_node), c_self_node.name, c_index) + if c_node is NULL: + raise IndexError, unicode(key) + return elementFactory(self._doc, c_node) + + def __setitem__(self, key, value): + """Set the value of a sibling, counting from the first child of the + parent. Implements key assignment, item assignment and slice + assignment. + + * If argument is an integer, sets the sibling at that position. + + * If argument is a string, does the same as setattr(). This is used + to provide namespaces for element lookup. + + * If argument is a sequence (list, tuple, etc.), assign the contained + items to the siblings. + """ + cdef _Element element + cdef tree.xmlNode* c_node + if python._isString(key): + key = _buildChildTag(self, key) + element = _lookupChild(self, key) + if element is None: + _appendValue(self, key, value) + else: + _replaceElement(element, value) + return + + if self._c_node.parent is NULL: + # the 'root[i] = ...' case + raise TypeError, "assignment to root element is invalid" + + if isinstance(key, slice): + # slice assignment + _setSlice(key, self, value) + else: + # normal index assignment + if key < 0: + c_node = self._c_node.parent.last + else: + c_node = self._c_node.parent.children + c_node = _findFollowingSibling( + c_node, tree._getNs(self._c_node), self._c_node.name, key) + if c_node is NULL: + raise IndexError, unicode(key) + element = elementFactory(self._doc, c_node) + _replaceElement(element, value) + + def __delitem__(self, key): + parent = self.getparent() + if parent is None: + raise TypeError, "deleting items not supported by root element" + if isinstance(key, slice): + # slice deletion + del_items = list(self)[key] + remove = parent.remove + for el in del_items: + remove(el) + else: + # normal index deletion + sibling = self.__getitem__(key) + parent.remove(sibling) + + def descendantpaths(self, prefix=None): + """descendantpaths(self, prefix=None) + + Returns a list of object path expressions for all descendants. + """ + if prefix is not None and not python._isString(prefix): + prefix = '.'.join(prefix) + return _build_descendant_paths(self._c_node, prefix) + + +cdef inline bint _tagMatches(tree.xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name): + if c_node.name != c_name: + return 0 + if c_href == NULL: + return 1 + c_node_href = tree._getNs(c_node) + if c_node_href == NULL: + return c_href[0] == c'\0' + return tree.xmlStrcmp(c_node_href, c_href) == 0 + + +cdef Py_ssize_t _countSiblings(tree.xmlNode* c_start_node): + cdef tree.xmlNode* c_node + cdef Py_ssize_t count + c_tag = c_start_node.name + c_href = tree._getNs(c_start_node) + count = 1 + c_node = c_start_node.next + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_NODE and \ + _tagMatches(c_node, c_href, c_tag): + count += 1 + c_node = c_node.next + c_node = c_start_node.prev + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_NODE and \ + _tagMatches(c_node, c_href, c_tag): + count += 1 + c_node = c_node.prev + return count + +cdef tree.xmlNode* _findFollowingSibling(tree.xmlNode* c_node, + const_xmlChar* href, const_xmlChar* name, + Py_ssize_t index): + cdef tree.xmlNode* (*next)(tree.xmlNode*) + if index >= 0: + next = cetree.nextElement + else: + index = -1 - index + next = cetree.previousElement + while c_node is not NULL: + if c_node.type == tree.XML_ELEMENT_NODE and \ + _tagMatches(c_node, href, name): + index = index - 1 + if index < 0: + return c_node + c_node = next(c_node) + return NULL + +cdef object _lookupChild(_Element parent, tag): + cdef tree.xmlNode* c_result + cdef tree.xmlNode* c_node + c_node = parent._c_node + ns, tag = cetree.getNsTagWithEmptyNs(tag) + c_tag = tree.xmlDictExists( + c_node.doc.dict, _xcstr(tag), python.PyBytes_GET_SIZE(tag)) + if c_tag is NULL: + return None # not in the hash map => not in the tree + if ns is None: + # either inherit ns from parent or use empty (i.e. no) namespace + c_href = tree._getNs(c_node) or '' + else: + c_href = _xcstr(ns) + c_result = _findFollowingSibling(c_node.children, c_href, c_tag, 0) + if c_result is NULL: + return None + return elementFactory(parent._doc, c_result) + +cdef object _lookupChildOrRaise(_Element parent, tag): + element = _lookupChild(parent, tag) + if element is None: + raise AttributeError, "no such child: " + _buildChildTag(parent, tag) + return element + +cdef object _buildChildTag(_Element parent, tag): + ns, tag = cetree.getNsTag(tag) + c_tag = _xcstr(tag) + c_href = tree._getNs(parent._c_node) if ns is None else _xcstr(ns) + return cetree.namespacedNameFromNsName(c_href, c_tag) + +cdef _replaceElement(_Element element, value): + cdef _Element new_element + if isinstance(value, _Element): + # deep copy the new element + new_element = cetree.deepcopyNodeToDocument( + element._doc, (<_Element>value)._c_node) + new_element.tag = element.tag + elif isinstance(value, (list, tuple)): + element[:] = value + return + else: + new_element = element.makeelement(element.tag) + _setElementValue(new_element, value) + element.getparent().replace(element, new_element) + +cdef _appendValue(_Element parent, tag, value): + cdef _Element new_element + if isinstance(value, _Element): + # deep copy the new element + new_element = cetree.deepcopyNodeToDocument( + parent._doc, (<_Element>value)._c_node) + new_element.tag = tag + cetree.appendChildToElement(parent, new_element) + elif isinstance(value, (list, tuple)): + for item in value: + _appendValue(parent, tag, item) + else: + new_element = cetree.makeElement( + tag, parent._doc, None, None, None, None, None) + _setElementValue(new_element, value) + cetree.appendChildToElement(parent, new_element) + +cdef _setElementValue(_Element element, value): + if value is None: + cetree.setAttributeValue( + element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true") + elif isinstance(value, _Element): + _replaceElement(element, value) + return + else: + cetree.delAttributeFromNsName( + element._c_node, _XML_SCHEMA_INSTANCE_NS, "nil") + if python._isString(value): + pytype_name = "str" + py_type = _PYTYPE_DICT.get(pytype_name) + else: + pytype_name = _typename(value) + py_type = _PYTYPE_DICT.get(pytype_name) + if py_type is not None: + value = py_type.stringify(value) + else: + value = unicode(value) + if py_type is not None: + cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name) + else: + cetree.delAttributeFromNsName( + element._c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME) + cetree.setNodeText(element._c_node, value) + +cdef _setSlice(sliceobject, _Element target, items): + cdef _Element parent + cdef tree.xmlNode* c_node + cdef Py_ssize_t c_step, c_start, pos + # collect existing slice + if (sliceobject).step is None: + c_step = 1 + else: + c_step = (sliceobject).step + if c_step == 0: + raise ValueError, "Invalid slice" + cdef list del_items = target[sliceobject] + + # collect new values + new_items = [] + tag = target.tag + for item in items: + if isinstance(item, _Element): + # deep copy the new element + new_element = cetree.deepcopyNodeToDocument( + target._doc, (<_Element>item)._c_node) + new_element.tag = tag + else: + new_element = cetree.makeElement( + tag, target._doc, None, None, None, None, None) + _setElementValue(new_element, item) + new_items.append(new_element) + + # sanity check - raise what a list would raise + if c_step != 1 and len(del_items) != len(new_items): + raise ValueError, \ + f"attempt to assign sequence of size {len(new_items)} to extended slice of size {len(del_items)}" + + # replace existing items + pos = 0 + parent = target.getparent() + replace = parent.replace + while pos < len(new_items) and pos < len(del_items): + replace(del_items[pos], new_items[pos]) + pos += 1 + # remove leftover items + if pos < len(del_items): + remove = parent.remove + while pos < len(del_items): + remove(del_items[pos]) + pos += 1 + # append remaining new items + if pos < len(new_items): + # the sanity check above guarantees (step == 1) + if pos > 0: + item = new_items[pos-1] + else: + if (sliceobject).start > 0: + c_node = parent._c_node.children + else: + c_node = parent._c_node.last + c_node = _findFollowingSibling( + c_node, tree._getNs(target._c_node), target._c_node.name, + (sliceobject).start - 1) + if c_node is NULL: + while pos < len(new_items): + cetree.appendChildToElement(parent, new_items[pos]) + pos += 1 + return + item = cetree.elementFactory(parent._doc, c_node) + while pos < len(new_items): + add = item.addnext + item = new_items[pos] + add(item) + pos += 1 + +################################################################################ +# Data type support in subclasses + +cdef class ObjectifiedDataElement(ObjectifiedElement): + """This is the base class for all data type Elements. Subclasses should + override the 'pyval' property and possibly the __str__ method. + """ + @property + def pyval(self): + return textOf(self._c_node) + + def __str__(self): + return textOf(self._c_node) or '' + + def __repr__(self): + return textOf(self._c_node) or '' + + def _setText(self, s): + """For use in subclasses only. Don't use unless you know what you are + doing. + """ + cetree.setNodeText(self._c_node, s) + + +cdef class NumberElement(ObjectifiedDataElement): + cdef object _parse_value + + def _setValueParser(self, function): + """Set the function that parses the Python value from a string. + + Do not use this unless you know what you are doing. + """ + self._parse_value = function + + @property + def pyval(self): + return _parseNumber(self) + + def __int__(self): + return int(_parseNumber(self)) + + def __float__(self): + return float(_parseNumber(self)) + + def __complex__(self): + return complex(_parseNumber(self)) + + def __str__(self): + return unicode(_parseNumber(self)) + + def __repr__(self): + return repr(_parseNumber(self)) + + def __oct__(self): + return oct(_parseNumber(self)) + + def __hex__(self): + return hex(_parseNumber(self)) + + def __richcmp__(self, other, int op): + return _richcmpPyvals(self, other, op) + + def __hash__(self): + return hash(_parseNumber(self)) + + def __add__(self, other): + return _numericValueOf(self) + _numericValueOf(other) + + def __radd__(self, other): + return _numericValueOf(other) + _numericValueOf(self) + + def __sub__(self, other): + return _numericValueOf(self) - _numericValueOf(other) + + def __rsub__(self, other): + return _numericValueOf(other) - _numericValueOf(self) + + def __mul__(self, other): + return _numericValueOf(self) * _numericValueOf(other) + + def __rmul__(self, other): + return _numericValueOf(other) * _numericValueOf(self) + + def __div__(self, other): + return _numericValueOf(self) / _numericValueOf(other) + + def __rdiv__(self, other): + return _numericValueOf(other) / _numericValueOf(self) + + def __truediv__(self, other): + return _numericValueOf(self) / _numericValueOf(other) + + def __rtruediv__(self, other): + return _numericValueOf(other) / _numericValueOf(self) + + def __floordiv__(self, other): + return _numericValueOf(self) // _numericValueOf(other) + + def __rfloordiv__(self, other): + return _numericValueOf(other) // _numericValueOf(self) + + def __mod__(self, other): + return _numericValueOf(self) % _numericValueOf(other) + + def __rmod__(self, other): + return _numericValueOf(other) % _numericValueOf(self) + + def __divmod__(self, other): + return divmod(_numericValueOf(self), _numericValueOf(other)) + + def __rdivmod__(self, other): + return divmod(_numericValueOf(other), _numericValueOf(self)) + + def __pow__(self, other, modulo): + if modulo is None: + return _numericValueOf(self) ** _numericValueOf(other) + else: + return pow(_numericValueOf(self), _numericValueOf(other), modulo) + + def __rpow__(self, other, modulo): + if modulo is None: + return _numericValueOf(other) ** _numericValueOf(self) + else: + return pow(_numericValueOf(other), _numericValueOf(self), modulo) + + def __neg__(self): + return - _numericValueOf(self) + + def __pos__(self): + return + _numericValueOf(self) + + def __abs__(self): + return abs( _numericValueOf(self) ) + + def __bool__(self): + return bool(_numericValueOf(self)) + + def __invert__(self): + return ~ _numericValueOf(self) + + def __lshift__(self, other): + return _numericValueOf(self) << _numericValueOf(other) + + def __rlshift__(self, other): + return _numericValueOf(other) << _numericValueOf(self) + + def __rshift__(self, other): + return _numericValueOf(self) >> _numericValueOf(other) + + def __rrshift__(self, other): + return _numericValueOf(other) >> _numericValueOf(self) + + def __and__(self, other): + return _numericValueOf(self) & _numericValueOf(other) + + def __rand__(self, other): + return _numericValueOf(other) & _numericValueOf(self) + + def __or__(self, other): + return _numericValueOf(self) | _numericValueOf(other) + + def __ror__(self, other): + return _numericValueOf(other) | _numericValueOf(self) + + def __xor__(self, other): + return _numericValueOf(self) ^ _numericValueOf(other) + + def __rxor__(self, other): + return _numericValueOf(other) ^ _numericValueOf(self) + + +cdef class IntElement(NumberElement): + def _init(self): + self._parse_value = int + + def __index__(self): + return int(_parseNumber(self)) + + +cdef class FloatElement(NumberElement): + def _init(self): + self._parse_value = float + + +cdef class StringElement(ObjectifiedDataElement): + """String data class. + + Note that this class does *not* support the sequence protocol of strings: + len(), iter(), str_attr[0], str_attr[0:1], etc. are *not* supported. + Instead, use the .text attribute to get a 'real' string. + """ + @property + def pyval(self): + return textOf(self._c_node) or '' + + def __repr__(self): + return repr(textOf(self._c_node) or '') + + def strlen(self): + text = textOf(self._c_node) + if text is None: + return 0 + else: + return len(text) + + def __bool__(self): + return bool(textOf(self._c_node)) + + def __richcmp__(self, other, int op): + return _richcmpPyvals(self, other, op) + + def __hash__(self): + return hash(textOf(self._c_node) or '') + + def __add__(self, other): + text = _strValueOf(self) + other = _strValueOf(other) + return text + other + + def __radd__(self, other): + text = _strValueOf(self) + other = _strValueOf(other) + return other + text + + def __mul__(self, other): + if isinstance(self, StringElement): + return (textOf((self)._c_node) or '') * _numericValueOf(other) + elif isinstance(other, StringElement): + return _numericValueOf(self) * (textOf((other)._c_node) or '') + else: + return NotImplemented + + def __rmul__(self, other): + return _numericValueOf(other) * (textOf((self)._c_node) or '') + + def __mod__(self, other): + return (_strValueOf(self) or '') % other + + def __int__(self): + return int(textOf(self._c_node)) + + def __float__(self): + return float(textOf(self._c_node)) + + def __complex__(self): + return complex(textOf(self._c_node)) + + +cdef class NoneElement(ObjectifiedDataElement): + def __str__(self): + return "None" + + def __repr__(self): + return "None" + + def __bool__(self): + return False + + def __richcmp__(self, other, int op): + if other is None or self is None: + return python.PyObject_RichCompare(None, None, op) + if isinstance(self, NoneElement): + return python.PyObject_RichCompare(None, other, op) + else: + return python.PyObject_RichCompare(self, None, op) + + def __hash__(self): + return hash(None) + + @property + def pyval(self): + return None + + +cdef class BoolElement(IntElement): + """Boolean type base on string values: 'true' or 'false'. + + Note that this inherits from IntElement to mimic the behaviour of + Python's bool type. + """ + def _init(self): + self._parse_value = _parseBool # wraps as Python callable + + def __bool__(self): + return _parseBool(textOf(self._c_node)) + + def __int__(self): + return 0 + _parseBool(textOf(self._c_node)) + + def __float__(self): + return 0.0 + _parseBool(textOf(self._c_node)) + + def __richcmp__(self, other, int op): + return _richcmpPyvals(self, other, op) + + def __hash__(self): + return hash(_parseBool(textOf(self._c_node))) + + def __str__(self): + return unicode(_parseBool(textOf(self._c_node))) + + def __repr__(self): + return repr(_parseBool(textOf(self._c_node))) + + @property + def pyval(self): + return _parseBool(textOf(self._c_node)) + + +cdef _checkBool(s): + cdef int value = -1 + if s is not None: + value = __parseBoolAsInt(s) + if value == -1: + raise ValueError + + +cdef bint _parseBool(s) except -1: + cdef int value + if s is None: + return False + value = __parseBoolAsInt(s) + if value == -1: + raise ValueError, f"Invalid boolean value: '{s}'" + return value + + +cdef inline int __parseBoolAsInt(text) except -2: + if text == 'false': + return 0 + elif text == 'true': + return 1 + elif text == '0': + return 0 + elif text == '1': + return 1 + return -1 + + +cdef object _parseNumber(NumberElement element): + return element._parse_value(textOf(element._c_node)) + + +cdef enum NumberParserState: + NPS_SPACE_PRE = 0 + NPS_SIGN = 1 + NPS_DIGITS = 2 + NPS_POINT_LEAD = 3 + NPS_POINT = 4 + NPS_FRACTION = 5 + NPS_EXP = 6 + NPS_EXP_SIGN = 7 + NPS_DIGITS_EXP = 8 + NPS_SPACE_TAIL = 9 + NPS_INF1 = 20 + NPS_INF2 = 21 + NPS_INF3 = 22 + NPS_NAN1 = 23 + NPS_NAN2 = 24 + NPS_NAN3 = 25 + NPS_ERROR = 99 + + +ctypedef fused bytes_unicode: + bytes + unicode + + +cdef _checkNumber(bytes_unicode s, bint allow_float): + cdef Py_UCS4 c + cdef NumberParserState state = NPS_SPACE_PRE + + for c in s: + if c in '0123456789': + if state in (NPS_DIGITS, NPS_FRACTION, NPS_DIGITS_EXP): + pass + elif state in (NPS_SPACE_PRE, NPS_SIGN): + state = NPS_DIGITS + elif state in (NPS_POINT_LEAD, NPS_POINT): + state = NPS_FRACTION + elif state in (NPS_EXP, NPS_EXP_SIGN): + state = NPS_DIGITS_EXP + else: + state = NPS_ERROR + else: + if c == '.': + if state in (NPS_SPACE_PRE, NPS_SIGN): + state = NPS_POINT_LEAD + elif state == NPS_DIGITS: + state = NPS_POINT + else: + state = NPS_ERROR + if not allow_float: + state = NPS_ERROR + elif c in '-+': + if state == NPS_SPACE_PRE: + state = NPS_SIGN + elif state == NPS_EXP: + state = NPS_EXP_SIGN + else: + state = NPS_ERROR + elif c == 'E': + if state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION): + state = NPS_EXP + else: + state = NPS_ERROR + if not allow_float: + state = NPS_ERROR + # Allow INF and NaN. XMLSchema requires case, we don't, like Python. + elif c in 'iI': + state = NPS_INF1 if allow_float and state in (NPS_SPACE_PRE, NPS_SIGN) else NPS_ERROR + elif c in 'fF': + state = NPS_INF3 if state == NPS_INF2 else NPS_ERROR + elif c in 'aA': + state = NPS_NAN2 if state == NPS_NAN1 else NPS_ERROR + elif c in 'nN': + # Python also allows [+-]NaN, so let's accept that. + if state in (NPS_SPACE_PRE, NPS_SIGN): + state = NPS_NAN1 if allow_float else NPS_ERROR + elif state == NPS_NAN2: + state = NPS_NAN3 + elif state == NPS_INF1: + state = NPS_INF2 + else: + state = NPS_ERROR + # Allow spaces around text values. + else: + if c.isspace() if (bytes_unicode is unicode) else c in b'\x09\x0a\x0b\x0c\x0d\x20': + if state in (NPS_SPACE_PRE, NPS_SPACE_TAIL): + pass + elif state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3): + state = NPS_SPACE_TAIL + else: + state = NPS_ERROR + else: + state = NPS_ERROR + + if state == NPS_ERROR: + break + + if state not in (NPS_DIGITS, NPS_FRACTION, NPS_POINT, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3, NPS_SPACE_TAIL): + raise ValueError + + +cdef _checkInt(s): + return _checkNumber(s, allow_float=False) + + +cdef _checkFloat(s): + return _checkNumber(s, allow_float=True) + + +cdef object _strValueOf(obj): + if python._isString(obj): + return obj + if isinstance(obj, _Element): + return textOf((<_Element>obj)._c_node) or '' + if obj is None: + return '' + return unicode(obj) + + +cdef object _numericValueOf(obj): + if isinstance(obj, NumberElement): + return _parseNumber(obj) + try: + # not always numeric, but Python will raise the right exception + return obj.pyval + except AttributeError: + pass + return obj + + +cdef _richcmpPyvals(left, right, int op): + left = getattr(left, 'pyval', left) + right = getattr(right, 'pyval', right) + return python.PyObject_RichCompare(left, right, op) + + +################################################################################ +# Python type registry + +cdef class PyType: + """PyType(self, name, type_check, type_class, stringify=None) + User defined type. + + Named type that contains a type check function, a type class that + inherits from ObjectifiedDataElement and an optional "stringification" + function. The type check must take a string as argument and raise + ValueError or TypeError if it cannot handle the string value. It may be + None in which case it is not considered for type guessing. For registered + named types, the 'stringify' function (or unicode() if None) is used to + convert a Python object with type name 'name' to the string representation + stored in the XML tree. + + Example:: + + PyType('int', int, MyIntClass).register() + + Note that the order in which types are registered matters. The first + matching type will be used. + """ + cdef readonly object name + cdef readonly object type_check + cdef readonly object stringify + cdef object _type + cdef list _schema_types + def __init__(self, name, type_check, type_class, stringify=None): + if isinstance(name, bytes): + name = (name).decode('ascii') + elif not isinstance(name, unicode): + raise TypeError, "Type name must be a string" + if type_check is not None and not callable(type_check): + raise TypeError, "Type check function must be callable (or None)" + if name != TREE_PYTYPE_NAME and \ + not issubclass(type_class, ObjectifiedDataElement): + raise TypeError, \ + "Data classes must inherit from ObjectifiedDataElement" + self.name = name + self._type = type_class + self.type_check = type_check + if stringify is None: + stringify = unicode + self.stringify = stringify + self._schema_types = [] + + def __repr__(self): + return "PyType(%s, %s)" % (self.name, self._type.__name__) + + def register(self, before=None, after=None): + """register(self, before=None, after=None) + + Register the type. + + The additional keyword arguments 'before' and 'after' accept a + sequence of type names that must appear before/after the new type in + the type list. If any of them is not currently known, it is simply + ignored. Raises ValueError if the dependencies cannot be fulfilled. + """ + if self.name == TREE_PYTYPE_NAME: + raise ValueError, "Cannot register tree type" + if self.type_check is not None: + for item in _TYPE_CHECKS: + if item[0] is self.type_check: + _TYPE_CHECKS.remove(item) + break + entry = (self.type_check, self) + first_pos = 0 + last_pos = -1 + if before or after: + if before is None: + before = () + elif after is None: + after = () + for i, (check, pytype) in enumerate(_TYPE_CHECKS): + if last_pos == -1 and pytype.name in before: + last_pos = i + if pytype.name in after: + first_pos = i+1 + if last_pos == -1: + _TYPE_CHECKS.append(entry) + elif first_pos > last_pos: + raise ValueError, "inconsistent before/after dependencies" + else: + _TYPE_CHECKS.insert(last_pos, entry) + + _PYTYPE_DICT[self.name] = self + for xs_type in self._schema_types: + _SCHEMA_TYPE_DICT[xs_type] = self + + def unregister(self): + "unregister(self)" + if _PYTYPE_DICT.get(self.name) is self: + del _PYTYPE_DICT[self.name] + for xs_type, pytype in list(_SCHEMA_TYPE_DICT.items()): + if pytype is self: + del _SCHEMA_TYPE_DICT[xs_type] + if self.type_check is None: + return + try: + _TYPE_CHECKS.remove( (self.type_check, self) ) + except ValueError: + pass + + property xmlSchemaTypes: + """The list of XML Schema datatypes this Python type maps to. + + Note that this must be set before registering the type! + """ + def __get__(self): + return self._schema_types + def __set__(self, types): + self._schema_types = list(map(unicode, types)) + + +cdef dict _PYTYPE_DICT = {} +cdef dict _SCHEMA_TYPE_DICT = {} +cdef list _TYPE_CHECKS = [] + +cdef unicode _xml_bool(value): + return "true" if value else "false" + +cdef unicode _xml_float(value): + if _float_is_inf(value): + if value > 0: + return "INF" + return "-INF" + if _float_is_nan(value): + return "NaN" + return unicode(repr(value)) + +cdef _pytypename(obj): + return "str" if python._isString(obj) else _typename(obj) + +def pytypename(obj): + """pytypename(obj) + + Find the name of the corresponding PyType for a Python object. + """ + return _pytypename(obj) + +cdef _registerPyTypes(): + pytype = PyType('int', _checkInt, IntElement) # wraps functions for Python + pytype.xmlSchemaTypes = ("integer", "int", "short", "byte", "unsignedShort", + "unsignedByte", "nonPositiveInteger", + "negativeInteger", "long", "nonNegativeInteger", + "unsignedLong", "unsignedInt", "positiveInteger",) + pytype.register() + + # 'long' type just for backwards compatibility + pytype = PyType('long', None, IntElement) + pytype.register() + + pytype = PyType('float', _checkFloat, FloatElement, _xml_float) # wraps functions for Python + pytype.xmlSchemaTypes = ("double", "float") + pytype.register() + + pytype = PyType('bool', _checkBool, BoolElement, _xml_bool) # wraps functions for Python + pytype.xmlSchemaTypes = ("boolean",) + pytype.register() + + pytype = PyType('str', None, StringElement) + pytype.xmlSchemaTypes = ("string", "normalizedString", "token", "language", + "Name", "NCName", "ID", "IDREF", "ENTITY", + "NMTOKEN", ) + pytype.register() + + # since lxml 2.0 + pytype = PyType('NoneType', None, NoneElement) + pytype.register() + + # backwards compatibility + pytype = PyType('none', None, NoneElement) + pytype.register() + +# non-registered PyType for inner tree elements +cdef PyType TREE_PYTYPE = PyType(TREE_PYTYPE_NAME, None, ObjectifiedElement) + +_registerPyTypes() + +def getRegisteredTypes(): + """getRegisteredTypes() + + Returns a list of the currently registered PyType objects. + + To add a new type, retrieve this list and call unregister() for all + entries. Then add the new type at a suitable position (possibly replacing + an existing one) and call register() for all entries. + + This is necessary if the new type interferes with the type check functions + of existing ones (normally only int/float/bool) and must the tried before + other types. To add a type that is not yet parsable by the current type + check functions, you can simply register() it, which will append it to the + end of the type list. + """ + cdef list types = [] + cdef set known = set() + for check, pytype in _TYPE_CHECKS: + name = pytype.name + if name not in known: + known.add(name) + types.append(pytype) + for pytype in _PYTYPE_DICT.values(): + name = pytype.name + if name not in known: + known.add(name) + types.append(pytype) + return types + +cdef PyType _guessPyType(value, PyType defaulttype): + if value is None: + return None + for type_check, tested_pytype in _TYPE_CHECKS: + try: + type_check(value) + return tested_pytype + except IGNORABLE_ERRORS: + # could not be parsed as the specified type => ignore + pass + return defaulttype + +cdef object _guessElementClass(tree.xmlNode* c_node): + value = textOf(c_node) + if value is None: + return None + if value == '': + return StringElement + + for type_check, pytype in _TYPE_CHECKS: + try: + type_check(value) + return (pytype)._type + except IGNORABLE_ERRORS: + pass + return None + +################################################################################ +# adapted ElementMaker supports registered PyTypes + +@cython.final +@cython.internal +cdef class _ObjectifyElementMakerCaller: + cdef object _tag + cdef object _nsmap + cdef object _element_factory + cdef bint _annotate + + def __call__(self, *children, **attrib): + "__call__(self, *children, **attrib)" + cdef _ObjectifyElementMakerCaller elementMaker + cdef _Element element + cdef _Element childElement + cdef bint has_children + cdef bint has_string_value + if self._element_factory is None: + element = _makeElement(self._tag, None, attrib, self._nsmap) + else: + element = self._element_factory(self._tag, attrib, self._nsmap) + + pytype_name = None + has_children = False + has_string_value = False + for child in children: + if child is None: + if len(children) == 1: + cetree.setAttributeValue( + element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true") + elif python._isString(child): + _add_text(element, child) + has_string_value = True + elif isinstance(child, _Element): + cetree.appendChildToElement(element, <_Element>child) + has_children = True + elif isinstance(child, _ObjectifyElementMakerCaller): + elementMaker = <_ObjectifyElementMakerCaller>child + if elementMaker._element_factory is None: + cetree.makeSubElement(element, elementMaker._tag, + None, None, None, None) + else: + childElement = elementMaker._element_factory( + elementMaker._tag) + cetree.appendChildToElement(element, childElement) + has_children = True + elif isinstance(child, dict): + for name, value in child.items(): + # keyword arguments in attrib take precedence + if name in attrib: + continue + pytype = _PYTYPE_DICT.get(_typename(value)) + if pytype is not None: + value = (pytype).stringify(value) + elif not python._isString(value): + value = unicode(value) + cetree.setAttributeValue(element, name, value) + else: + if pytype_name is not None: + # concatenation always makes the result a string + has_string_value = True + pytype_name = _typename(child) + pytype = _PYTYPE_DICT.get(_typename(child)) + if pytype is not None: + _add_text(element, (pytype).stringify(child)) + else: + has_string_value = True + child = unicode(child) + _add_text(element, child) + + if self._annotate and not has_children: + if has_string_value: + cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, "str") + elif pytype_name is not None: + cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name) + + return element + +cdef _add_text(_Element elem, text): + # add text to the tree in construction, either as element text or + # tail text, depending on the current tree state + cdef tree.xmlNode* c_child + c_child = cetree.findChildBackwards(elem._c_node, 0) + if c_child is not NULL: + old = cetree.tailOf(c_child) + if old is not None: + text = old + text + cetree.setTailText(c_child, text) + else: + old = cetree.textOf(elem._c_node) + if old is not None: + text = old + text + cetree.setNodeText(elem._c_node, text) + +cdef class ElementMaker: + """ElementMaker(self, namespace=None, nsmap=None, annotate=True, makeelement=None) + + An ElementMaker that can be used for constructing trees. + + Example:: + + >>> M = ElementMaker(annotate=False) + >>> attributes = {'class': 'par'} + >>> html = M.html( M.body( M.p('hello', attributes, M.br, 'objectify', style="font-weight: bold") ) ) + + >>> from lxml.etree import tostring + >>> print(tostring(html, method='html').decode('ascii')) +

hello
objectify

+ + To create tags that are not valid Python identifiers, call the factory + directly and pass the tag name as first argument:: + + >>> root = M('tricky-tag', 'some text') + >>> print(root.tag) + tricky-tag + >>> print(root.text) + some text + + Note that this module has a predefined ElementMaker instance called ``E``. + """ + cdef object _makeelement + cdef object _namespace + cdef object _nsmap + cdef bint _annotate + cdef dict _cache + def __init__(self, *, namespace=None, nsmap=None, annotate=True, + makeelement=None): + if nsmap is None: + nsmap = _DEFAULT_NSMAP if annotate else {} + self._nsmap = nsmap + self._namespace = None if namespace is None else "{%s}" % namespace + self._annotate = annotate + if makeelement is not None: + if not callable(makeelement): + raise TypeError( + f"argument of 'makeelement' parameter must be callable, got {type(makeelement)}") + self._makeelement = makeelement + else: + self._makeelement = None + self._cache = {} + + @cython.final + cdef _build_element_maker(self, tag, bint caching): + cdef _ObjectifyElementMakerCaller element_maker + element_maker = _ObjectifyElementMakerCaller.__new__(_ObjectifyElementMakerCaller) + if self._namespace is not None and tag[0] != "{": + element_maker._tag = self._namespace + tag + else: + element_maker._tag = tag + element_maker._nsmap = self._nsmap + element_maker._annotate = self._annotate + element_maker._element_factory = self._makeelement + if caching: + if len(self._cache) > 200: + self._cache.clear() + self._cache[tag] = element_maker + return element_maker + + def __getattr__(self, tag): + element_maker = self._cache.get(tag) + if element_maker is None: + return self._build_element_maker(tag, caching=True) + return element_maker + + def __call__(self, tag, *args, **kwargs): + element_maker = self._cache.get(tag) + if element_maker is None: + element_maker = self._build_element_maker( + tag, caching=not is_special_method(tag)) + return element_maker(*args, **kwargs) + +################################################################################ +# Recursive element dumping + +cdef bint __RECURSIVE_STR = 0 # default: off + +def enable_recursive_str(on=True): + """enable_recursive_str(on=True) + + Enable a recursively generated tree representation for str(element), + based on objectify.dump(element). + """ + global __RECURSIVE_STR + __RECURSIVE_STR = on + +def dump(_Element element not None): + """dump(_Element element not None) + + Return a recursively generated string representation of an element. + """ + return _dump(element, 0) + +cdef object _dump(_Element element, int indent): + indentstr = " " * indent + if isinstance(element, ObjectifiedDataElement): + value = repr(element) + else: + value = textOf(element._c_node) + if value is not None: + if not value.strip(): + value = None + else: + value = repr(value) + result = f"{indentstr}{element.tag} = {value} [{_typename(element)}]\n" + xsi_ns = "{%s}" % XML_SCHEMA_INSTANCE_NS + pytype_ns = "{%s}" % PYTYPE_NAMESPACE + for name, value in sorted(cetree.iterattributes(element, 3)): + if '{' in name: + if name == PYTYPE_ATTRIBUTE: + if value == TREE_PYTYPE_NAME: + continue + else: + name = name.replace(pytype_ns, 'py:') + name = name.replace(xsi_ns, 'xsi:') + result += f"{indentstr} * {name} = {value!r}\n" + + indent += 1 + for child in element.iterchildren(): + result += _dump(child, indent) + if indent == 1: + return result[:-1] # strip last '\n' + else: + return result + + +################################################################################ +# Pickle support for objectified ElementTree + +def __unpickleElementTree(data): + return etree.ElementTree(fromstring(data)) + +cdef _setupPickle(elementTreeReduceFunction): + import copyreg + copyreg.pickle(etree._ElementTree, + elementTreeReduceFunction, __unpickleElementTree) + +def pickleReduceElementTree(obj): + return __unpickleElementTree, (etree.tostring(obj),) + +_setupPickle(pickleReduceElementTree) +del pickleReduceElementTree + +################################################################################ +# Element class lookup + +cdef class ObjectifyElementClassLookup(ElementClassLookup): + """ObjectifyElementClassLookup(self, tree_class=None, empty_data_class=None) + Element class lookup method that uses the objectify classes. + """ + cdef object empty_data_class + cdef object tree_class + def __init__(self, tree_class=None, empty_data_class=None): + """Lookup mechanism for objectify. + + The default Element classes can be replaced by passing subclasses of + ObjectifiedElement and ObjectifiedDataElement as keyword arguments. + 'tree_class' defines inner tree classes (defaults to + ObjectifiedElement), 'empty_data_class' defines the default class for + empty data elements (defaults to StringElement). + """ + self._lookup_function = _lookupElementClass + if tree_class is None: + tree_class = ObjectifiedElement + self.tree_class = tree_class + if empty_data_class is None: + empty_data_class = StringElement + self.empty_data_class = empty_data_class + +cdef object _lookupElementClass(state, _Document doc, tree.xmlNode* c_node): + cdef ObjectifyElementClassLookup lookup + lookup = state + # if element has children => no data class + if cetree.hasChild(c_node): + return lookup.tree_class + + # if element is defined as xsi:nil, return NoneElement class + if "true" == cetree.attributeValueFromNsName( + c_node, _XML_SCHEMA_INSTANCE_NS, "nil"): + return NoneElement + + # check for Python type hint + value = cetree.attributeValueFromNsName( + c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME) + if value is not None: + if value == TREE_PYTYPE_NAME: + return lookup.tree_class + py_type = _PYTYPE_DICT.get(value) + if py_type is not None: + return py_type._type + # unknown 'pyval' => try to figure it out ourself, just go on + + # check for XML Schema type hint + value = cetree.attributeValueFromNsName( + c_node, _XML_SCHEMA_INSTANCE_NS, "type") + + if value is not None: + schema_type = _SCHEMA_TYPE_DICT.get(value) + if schema_type is None and ':' in value: + prefix, value = value.split(':', 1) + schema_type = _SCHEMA_TYPE_DICT.get(value) + if schema_type is not None: + return schema_type._type + + # otherwise determine class based on text content type + el_class = _guessElementClass(c_node) + if el_class is not None: + return el_class + + # if element is a root node => default to tree node + if c_node.parent is NULL or not tree._isElement(c_node.parent): + return lookup.tree_class + + return lookup.empty_data_class + + +################################################################################ +# Type annotations + +cdef PyType _check_type(tree.xmlNode* c_node, PyType pytype): + if pytype is None: + return None + value = textOf(c_node) + try: + pytype.type_check(value) + return pytype + except IGNORABLE_ERRORS: + # could not be parsed as the specified type => ignore + pass + return None + +def pyannotate(element_or_tree, *, ignore_old=False, ignore_xsi=False, + empty_pytype=None): + """pyannotate(element_or_tree, ignore_old=False, ignore_xsi=False, empty_pytype=None) + + Recursively annotates the elements of an XML tree with 'pytype' + attributes. + + If the 'ignore_old' keyword argument is True (the default), current 'pytype' + attributes will be ignored and replaced. Otherwise, they will be checked + and only replaced if they no longer fit the current text value. + + Setting the keyword argument ``ignore_xsi`` to True makes the function + additionally ignore existing ``xsi:type`` annotations. The default is to + use them as a type hint. + + The default annotation of empty elements can be set with the + ``empty_pytype`` keyword argument. The default is not to annotate empty + elements. Pass 'str', for example, to make string values the default. + """ + cdef _Element element + element = cetree.rootNodeOrRaise(element_or_tree) + _annotate(element, 0, 1, ignore_xsi, ignore_old, None, empty_pytype) + +def xsiannotate(element_or_tree, *, ignore_old=False, ignore_pytype=False, + empty_type=None): + """xsiannotate(element_or_tree, ignore_old=False, ignore_pytype=False, empty_type=None) + + Recursively annotates the elements of an XML tree with 'xsi:type' + attributes. + + If the 'ignore_old' keyword argument is True (the default), current + 'xsi:type' attributes will be ignored and replaced. Otherwise, they will be + checked and only replaced if they no longer fit the current text value. + + Note that the mapping from Python types to XSI types is usually ambiguous. + Currently, only the first XSI type name in the corresponding PyType + definition will be used for annotation. Thus, you should consider naming + the widest type first if you define additional types. + + Setting the keyword argument ``ignore_pytype`` to True makes the function + additionally ignore existing ``pytype`` annotations. The default is to + use them as a type hint. + + The default annotation of empty elements can be set with the + ``empty_type`` keyword argument. The default is not to annotate empty + elements. Pass 'string', for example, to make string values the default. + """ + cdef _Element element + element = cetree.rootNodeOrRaise(element_or_tree) + _annotate(element, 1, 0, ignore_old, ignore_pytype, empty_type, None) + +def annotate(element_or_tree, *, ignore_old=True, ignore_xsi=False, + empty_pytype=None, empty_type=None, annotate_xsi=0, + annotate_pytype=1): + """annotate(element_or_tree, ignore_old=True, ignore_xsi=False, empty_pytype=None, empty_type=None, annotate_xsi=0, annotate_pytype=1) + + Recursively annotates the elements of an XML tree with 'xsi:type' + and/or 'py:pytype' attributes. + + If the 'ignore_old' keyword argument is True (the default), current + 'py:pytype' attributes will be ignored for the type annotation. Set to False + if you want reuse existing 'py:pytype' information (iff appropriate for the + element text value). + + If the 'ignore_xsi' keyword argument is False (the default), existing + 'xsi:type' attributes will be used for the type annotation, if they fit the + element text values. + + Note that the mapping from Python types to XSI types is usually ambiguous. + Currently, only the first XSI type name in the corresponding PyType + definition will be used for annotation. Thus, you should consider naming + the widest type first if you define additional types. + + The default 'py:pytype' annotation of empty elements can be set with the + ``empty_pytype`` keyword argument. Pass 'str', for example, to make + string values the default. + + The default 'xsi:type' annotation of empty elements can be set with the + ``empty_type`` keyword argument. The default is not to annotate empty + elements. Pass 'string', for example, to make string values the default. + + The keyword arguments 'annotate_xsi' (default: 0) and 'annotate_pytype' + (default: 1) control which kind(s) of annotation to use. + """ + cdef _Element element + element = cetree.rootNodeOrRaise(element_or_tree) + _annotate(element, annotate_xsi, annotate_pytype, ignore_xsi, + ignore_old, empty_type, empty_pytype) + + +cdef _annotate(_Element element, bint annotate_xsi, bint annotate_pytype, + bint ignore_xsi, bint ignore_pytype, + empty_type_name, empty_pytype_name): + cdef _Document doc + cdef tree.xmlNode* c_node + cdef PyType empty_pytype, StrType, NoneType + + if not annotate_xsi and not annotate_pytype: + return + + if empty_type_name is not None: + if isinstance(empty_type_name, bytes): + empty_type_name = (empty_type_name).decode("ascii") + empty_pytype = _SCHEMA_TYPE_DICT.get(empty_type_name) + elif empty_pytype_name is not None: + if isinstance(empty_pytype_name, bytes): + empty_pytype_name = (empty_pytype_name).decode("ascii") + empty_pytype = _PYTYPE_DICT.get(empty_pytype_name) + else: + empty_pytype = None + + StrType = _PYTYPE_DICT.get('str') + NoneType = _PYTYPE_DICT.get('NoneType') + + doc = element._doc + c_node = element._c_node + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + _annotate_element(c_node, doc, annotate_xsi, annotate_pytype, + ignore_xsi, ignore_pytype, + empty_type_name, empty_pytype, StrType, NoneType) + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + +cdef int _annotate_element(tree.xmlNode* c_node, _Document doc, + bint annotate_xsi, bint annotate_pytype, + bint ignore_xsi, bint ignore_pytype, + empty_type_name, PyType empty_pytype, + PyType StrType, PyType NoneType) except -1: + cdef tree.xmlNs* c_ns + cdef PyType pytype = None + typename = None + istree = 0 + + # if element is defined as xsi:nil, represent it as None + if cetree.attributeValueFromNsName( + c_node, _XML_SCHEMA_INSTANCE_NS, "nil") == "true": + pytype = NoneType + + if pytype is None and not ignore_xsi: + # check that old xsi type value is valid + typename = cetree.attributeValueFromNsName( + c_node, _XML_SCHEMA_INSTANCE_NS, "type") + if typename is not None: + pytype = _SCHEMA_TYPE_DICT.get(typename) + if pytype is None and ':' in typename: + prefix, typename = typename.split(':', 1) + pytype = _SCHEMA_TYPE_DICT.get(typename) + if pytype is not None and pytype is not StrType: + # StrType does not have a typecheck but is the default + # anyway, so just accept it if given as type + # information + pytype = _check_type(c_node, pytype) + if pytype is None: + typename = None + + if pytype is None and not ignore_pytype: + # check that old pytype value is valid + old_pytypename = cetree.attributeValueFromNsName( + c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME) + if old_pytypename is not None: + if old_pytypename == TREE_PYTYPE_NAME: + if not cetree.hasChild(c_node): + # only case where we should keep it, + # everything else is clear enough + pytype = TREE_PYTYPE + else: + if old_pytypename == 'none': + # transition from lxml 1.x + old_pytypename = "NoneType" + pytype = _PYTYPE_DICT.get(old_pytypename) + if pytype is not None and pytype is not StrType: + # StrType does not have a typecheck but is the + # default anyway, so just accept it if given as + # type information + pytype = _check_type(c_node, pytype) + + if pytype is None: + # try to guess type + if not cetree.hasChild(c_node): + # element has no children => data class + pytype = _guessPyType(textOf(c_node), StrType) + else: + istree = 1 + + if pytype is None: + # use default type for empty elements + if cetree.hasText(c_node): + pytype = StrType + else: + pytype = empty_pytype + if typename is None: + typename = empty_type_name + + if pytype is not None: + if typename is None: + if not istree: + if pytype._schema_types: + # pytype->xsi:type is a 1:n mapping + # simply take the first + typename = pytype._schema_types[0] + elif typename not in pytype._schema_types: + typename = pytype._schema_types[0] + + if annotate_xsi: + if typename is None or istree: + cetree.delAttributeFromNsName( + c_node, _XML_SCHEMA_INSTANCE_NS, "type") + else: + # update or create attribute + typename_utf8 = cetree.utf8(typename) + c_ns = cetree.findOrBuildNodeNsPrefix( + doc, c_node, _XML_SCHEMA_NS, 'xsd') + if c_ns is not NULL: + if b':' in typename_utf8: + prefix, name = typename_utf8.split(b':', 1) + if c_ns.prefix is NULL or c_ns.prefix[0] == c'\0': + typename_utf8 = name + elif tree.xmlStrcmp(_xcstr(prefix), c_ns.prefix) != 0: + typename_utf8 = (c_ns.prefix) + b':' + name + elif c_ns.prefix is not NULL and c_ns.prefix[0] != c'\0': + typename_utf8 = (c_ns.prefix) + b':' + typename_utf8 + c_ns = cetree.findOrBuildNodeNsPrefix( + doc, c_node, _XML_SCHEMA_INSTANCE_NS, 'xsi') + tree.xmlSetNsProp(c_node, c_ns, "type", _xcstr(typename_utf8)) + + if annotate_pytype: + if pytype is None: + # delete attribute if it exists + cetree.delAttributeFromNsName( + c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME) + else: + # update or create attribute + c_ns = cetree.findOrBuildNodeNsPrefix( + doc, c_node, _PYTYPE_NAMESPACE, 'py') + pytype_name = cetree.utf8(pytype.name) + tree.xmlSetNsProp(c_node, c_ns, _PYTYPE_ATTRIBUTE_NAME, + _xcstr(pytype_name)) + if pytype is NoneType: + c_ns = cetree.findOrBuildNodeNsPrefix( + doc, c_node, _XML_SCHEMA_INSTANCE_NS, 'xsi') + tree.xmlSetNsProp(c_node, c_ns, "nil", "true") + + return 0 + +cdef object _strip_attributes = etree.strip_attributes +cdef object _cleanup_namespaces = etree.cleanup_namespaces + +def deannotate(element_or_tree, *, bint pytype=True, bint xsi=True, + bint xsi_nil=False, bint cleanup_namespaces=False): + """deannotate(element_or_tree, pytype=True, xsi=True, xsi_nil=False, cleanup_namespaces=False) + + Recursively de-annotate the elements of an XML tree by removing 'py:pytype' + and/or 'xsi:type' attributes and/or 'xsi:nil' attributes. + + If the 'pytype' keyword argument is True (the default), 'py:pytype' + attributes will be removed. If the 'xsi' keyword argument is True (the + default), 'xsi:type' attributes will be removed. + If the 'xsi_nil' keyword argument is True (default: False), 'xsi:nil' + attributes will be removed. + + Note that this does not touch the namespace declarations by + default. If you want to remove unused namespace declarations from + the tree, pass the option ``cleanup_namespaces=True``. + """ + cdef list attribute_names = [] + + if pytype: + attribute_names.append(PYTYPE_ATTRIBUTE) + if xsi: + attribute_names.append(XML_SCHEMA_INSTANCE_TYPE_ATTR) + if xsi_nil: + attribute_names.append(XML_SCHEMA_INSTANCE_NIL_ATTR) + + _strip_attributes(element_or_tree, *attribute_names) + if cleanup_namespaces: + _cleanup_namespaces(element_or_tree) + +################################################################################ +# Module level parser setup + +cdef object __DEFAULT_PARSER +__DEFAULT_PARSER = etree.XMLParser(remove_blank_text=True) +__DEFAULT_PARSER.set_element_class_lookup( ObjectifyElementClassLookup() ) + +cdef object objectify_parser +objectify_parser = __DEFAULT_PARSER + +def set_default_parser(new_parser = None): + """set_default_parser(new_parser = None) + + Replace the default parser used by objectify's Element() and + fromstring() functions. + + The new parser must be an etree.XMLParser. + + Call without arguments to reset to the original parser. + """ + global objectify_parser + if new_parser is None: + objectify_parser = __DEFAULT_PARSER + elif isinstance(new_parser, etree.XMLParser): + objectify_parser = new_parser + else: + raise TypeError, "parser must inherit from lxml.etree.XMLParser" + +def makeparser(**kw): + """makeparser(remove_blank_text=True, **kw) + + Create a new XML parser for objectify trees. + + You can pass all keyword arguments that are supported by + ``etree.XMLParser()``. Note that this parser defaults to removing + blank text. You can disable this by passing the + ``remove_blank_text`` boolean keyword option yourself. + """ + if 'remove_blank_text' not in kw: + kw['remove_blank_text'] = True + parser = etree.XMLParser(**kw) + parser.set_element_class_lookup( ObjectifyElementClassLookup() ) + return parser + +cdef _Element _makeElement(tag, text, attrib, nsmap): + return cetree.makeElement(tag, None, objectify_parser, text, None, attrib, nsmap) + +################################################################################ +# Module level factory functions + +cdef object _fromstring +_fromstring = etree.fromstring + +SubElement = etree.SubElement + +def fromstring(xml, parser=None, *, base_url=None): + """fromstring(xml, parser=None, base_url=None) + + Objectify specific version of the lxml.etree fromstring() function + that uses the objectify parser. + + You can pass a different parser as second argument. + + The ``base_url`` keyword argument allows to set the original base URL of + the document to support relative Paths when looking up external entities + (DTD, XInclude, ...). + """ + if parser is None: + parser = objectify_parser + return _fromstring(xml, parser, base_url=base_url) + +def XML(xml, parser=None, *, base_url=None): + """XML(xml, parser=None, base_url=None) + + Objectify specific version of the lxml.etree XML() literal factory + that uses the objectify parser. + + You can pass a different parser as second argument. + + The ``base_url`` keyword argument allows to set the original base URL of + the document to support relative Paths when looking up external entities + (DTD, XInclude, ...). + """ + if parser is None: + parser = objectify_parser + return _fromstring(xml, parser, base_url=base_url) + +cdef object _parse +_parse = etree.parse + +def parse(f, parser=None, *, base_url=None): + """parse(f, parser=None, base_url=None) + + Parse a file or file-like object with the objectify parser. + + You can pass a different parser as second argument. + + The ``base_url`` keyword allows setting a URL for the document + when parsing from a file-like object. This is needed when looking + up external entities (DTD, XInclude, ...) with relative paths. + """ + if parser is None: + parser = objectify_parser + return _parse(f, parser, base_url=base_url) + +cdef dict _DEFAULT_NSMAP = { + "py" : PYTYPE_NAMESPACE, + "xsi" : XML_SCHEMA_INSTANCE_NS, + "xsd" : XML_SCHEMA_NS +} + +E = ElementMaker() + +def Element(_tag, attrib=None, nsmap=None, *, _pytype=None, **_attributes): + """Element(_tag, attrib=None, nsmap=None, _pytype=None, **_attributes) + + Objectify specific version of the lxml.etree Element() factory that + always creates a structural (tree) element. + + NOTE: requires parser based element class lookup activated in lxml.etree! + """ + if attrib is not None: + if _attributes: + attrib = dict(attrib) + attrib.update(_attributes) + _attributes = attrib + if _pytype is None: + _pytype = TREE_PYTYPE_NAME + if nsmap is None: + nsmap = _DEFAULT_NSMAP + _attributes[PYTYPE_ATTRIBUTE] = _pytype + return _makeElement(_tag, None, _attributes, nsmap) + +def DataElement(_value, attrib=None, nsmap=None, *, _pytype=None, _xsi=None, + **_attributes): + """DataElement(_value, attrib=None, nsmap=None, _pytype=None, _xsi=None, **_attributes) + + Create a new element from a Python value and XML attributes taken from + keyword arguments or a dictionary passed as second argument. + + Automatically adds a 'pytype' attribute for the Python type of the value, + if the type can be identified. If '_pytype' or '_xsi' are among the + keyword arguments, they will be used instead. + + If the _value argument is an ObjectifiedDataElement instance, its py:pytype, + xsi:type and other attributes and nsmap are reused unless they are redefined + in attrib and/or keyword arguments. + """ + if nsmap is None: + nsmap = _DEFAULT_NSMAP + if attrib is not None and attrib: + if _attributes: + attrib = dict(attrib) + attrib.update(_attributes) + _attributes = attrib + if isinstance(_value, ObjectifiedElement): + if _pytype is None: + if _xsi is None and not _attributes and nsmap is _DEFAULT_NSMAP: + # special case: no change! + return _value.__copy__() + if isinstance(_value, ObjectifiedDataElement): + # reuse existing nsmap unless redefined in nsmap parameter + temp = _value.nsmap + if temp is not None and temp: + temp = dict(temp) + temp.update(nsmap) + nsmap = temp + # reuse existing attributes unless redefined in attrib/_attributes + temp = _value.attrib + if temp is not None and temp: + temp = dict(temp) + temp.update(_attributes) + _attributes = temp + # reuse existing xsi:type or py:pytype attributes, unless provided as + # arguments + if _xsi is None and _pytype is None: + _xsi = _attributes.get(XML_SCHEMA_INSTANCE_TYPE_ATTR) + _pytype = _attributes.get(PYTYPE_ATTRIBUTE) + + if _xsi is not None: + if ':' in _xsi: + prefix, name = _xsi.split(':', 1) + ns = nsmap.get(prefix) + if ns != XML_SCHEMA_NS: + raise ValueError, "XSD types require the XSD namespace" + elif nsmap is _DEFAULT_NSMAP: + name = _xsi + _xsi = 'xsd:' + _xsi + else: + name = _xsi + for prefix, ns in nsmap.items(): + if ns == XML_SCHEMA_NS: + if prefix is not None and prefix: + _xsi = prefix + ':' + _xsi + break + else: + raise ValueError, "XSD types require the XSD namespace" + _attributes[XML_SCHEMA_INSTANCE_TYPE_ATTR] = _xsi + if _pytype is None: + # allow using unregistered or even wrong xsi:type names + py_type = _SCHEMA_TYPE_DICT.get(_xsi) + if py_type is None: + py_type = _SCHEMA_TYPE_DICT.get(name) + if py_type is not None: + _pytype = py_type.name + + if _pytype is None: + _pytype = _pytypename(_value) + + if _value is None and _pytype != "str": + _pytype = _pytype or "NoneType" + strval = None + elif python._isString(_value): + strval = _value + elif isinstance(_value, bool): + if _value: + strval = "true" + else: + strval = "false" + else: + py_type = _PYTYPE_DICT.get(_pytype) + stringify = unicode if py_type is None else py_type.stringify + strval = stringify(_value) + + if _pytype is not None: + if _pytype == "NoneType" or _pytype == "none": + strval = None + _attributes[XML_SCHEMA_INSTANCE_NIL_ATTR] = "true" + else: + # check if type information from arguments is valid + py_type = _PYTYPE_DICT.get(_pytype) + if py_type is not None: + if py_type.type_check is not None: + py_type.type_check(strval) + _attributes[PYTYPE_ATTRIBUTE] = _pytype + + return _makeElement("value", strval, _attributes, nsmap) + + +################################################################################ +# ObjectPath + +include "objectpath.pxi" diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/parser.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/parser.pxi new file mode 100644 index 0000000000000000000000000000000000000000..ff07dcdd3ebd341a8e02b7cebb9c01f3255a2edd --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/parser.pxi @@ -0,0 +1,1994 @@ +# Parsers for XML and HTML + +from lxml.includes cimport xmlparser +from lxml.includes cimport htmlparser + + +class ParseError(LxmlSyntaxError): + """Syntax error while parsing an XML document. + + For compatibility with ElementTree 1.3 and later. + """ + def __init__(self, message, code, line, column, filename=None): + super(_ParseError, self).__init__(message) + self.lineno, self.offset = (line, column - 1) + self.code = code + self.filename = filename + + @property + def position(self): + return self.lineno, self.offset + 1 + + @position.setter + def position(self, new_pos): + self.lineno, column = new_pos + self.offset = column - 1 + +cdef object _ParseError = ParseError + + +class XMLSyntaxError(ParseError): + """Syntax error while parsing an XML document. + """ + +cdef class ParserError(LxmlError): + """Internal lxml parser error. + """ + + +@cython.final +@cython.internal +cdef class _ParserDictionaryContext: + # Global parser context to share the string dictionary. + # + # This class is a delegate singleton! + # + # It creates _ParserDictionaryContext objects for each thread to keep thread state, + # but those must never be used directly. Always stick to using the static + # __GLOBAL_PARSER_CONTEXT as defined below the class. + # + + cdef tree.xmlDict* _c_dict + cdef _BaseParser _default_parser + cdef list _implied_parser_contexts + + def __cinit__(self): + self._c_dict = NULL + self._implied_parser_contexts = [] + + def __dealloc__(self): + if self._c_dict is not NULL: + xmlparser.xmlDictFree(self._c_dict) + + cdef int initMainParserContext(self) except -1: + """Put the global context into the thread dictionary of the main + thread. To be called once and only in the main thread.""" + thread_dict = python.PyThreadState_GetDict() + if thread_dict is not NULL: + (thread_dict)["_ParserDictionaryContext"] = self + + cdef _ParserDictionaryContext _findThreadParserContext(self): + "Find (or create) the _ParserDictionaryContext object for the current thread" + cdef _ParserDictionaryContext context + thread_dict = python.PyThreadState_GetDict() + if thread_dict is NULL: + return self + d = thread_dict + result = python.PyDict_GetItem(d, "_ParserDictionaryContext") + if result is not NULL: + return result + context = <_ParserDictionaryContext>_ParserDictionaryContext.__new__(_ParserDictionaryContext) + d["_ParserDictionaryContext"] = context + return context + + cdef int setDefaultParser(self, _BaseParser parser) except -1: + "Set the default parser for the current thread" + cdef _ParserDictionaryContext context + context = self._findThreadParserContext() + context._default_parser = parser + + cdef _BaseParser getDefaultParser(self): + "Return (or create) the default parser of the current thread" + cdef _ParserDictionaryContext context + context = self._findThreadParserContext() + if context._default_parser is None: + if self._default_parser is None: + self._default_parser = __DEFAULT_XML_PARSER._copy() + if context is not self: + context._default_parser = self._default_parser._copy() + return context._default_parser + + cdef tree.xmlDict* _getThreadDict(self, tree.xmlDict* default): + "Return the thread-local dict or create a new one if necessary." + cdef _ParserDictionaryContext context + context = self._findThreadParserContext() + if context._c_dict is NULL: + # thread dict not yet set up => use default or create a new one + if default is not NULL: + context._c_dict = default + xmlparser.xmlDictReference(default) + return default + if self._c_dict is NULL: + self._c_dict = xmlparser.xmlDictCreate() + if context is not self: + context._c_dict = xmlparser.xmlDictCreateSub(self._c_dict) + return context._c_dict + + cdef int initThreadDictRef(self, tree.xmlDict** c_dict_ref) except -1: + c_dict = c_dict_ref[0] + c_thread_dict = self._getThreadDict(c_dict) + if c_dict is c_thread_dict: + return 0 + if c_dict is not NULL: + xmlparser.xmlDictFree(c_dict) + c_dict_ref[0] = c_thread_dict + xmlparser.xmlDictReference(c_thread_dict) + + cdef int initParserDict(self, xmlparser.xmlParserCtxt* pctxt) except -1: + "Assure we always use the same string dictionary." + self.initThreadDictRef(&pctxt.dict) + pctxt.dictNames = 1 + + cdef int initXPathParserDict(self, xpath.xmlXPathContext* pctxt) except -1: + "Assure we always use the same string dictionary." + self.initThreadDictRef(&pctxt.dict) + + cdef int initDocDict(self, xmlDoc* result) except -1: + "Store dict of last object parsed if no shared dict yet" + # XXX We also free the result dict here if there already was one. + # This case should only occur for new documents with empty dicts, + # otherwise we'd free data that's in use => segfault + self.initThreadDictRef(&result.dict) + + cdef _ParserContext findImpliedContext(self): + """Return any current implied xml parser context for the current + thread. This is used when the resolver functions are called + with an xmlParserCtxt that was generated from within libxml2 + (i.e. without a _ParserContext) - which happens when parsing + schema and xinclude external references.""" + cdef _ParserDictionaryContext context + cdef _ParserContext implied_context + + # see if we have a current implied parser + context = self._findThreadParserContext() + if context._implied_parser_contexts: + implied_context = context._implied_parser_contexts[-1] + return implied_context + return None + + cdef int pushImpliedContextFromParser(self, _BaseParser parser) except -1: + "Push a new implied context object taken from the parser." + if parser is not None: + self.pushImpliedContext(parser._getParserContext()) + else: + self.pushImpliedContext(None) + + cdef int pushImpliedContext(self, _ParserContext parser_context) except -1: + "Push a new implied context object." + cdef _ParserDictionaryContext context + context = self._findThreadParserContext() + context._implied_parser_contexts.append(parser_context) + + cdef int popImpliedContext(self) except -1: + "Pop the current implied context object." + cdef _ParserDictionaryContext context + context = self._findThreadParserContext() + context._implied_parser_contexts.pop() + +cdef _ParserDictionaryContext __GLOBAL_PARSER_CONTEXT = _ParserDictionaryContext() +__GLOBAL_PARSER_CONTEXT.initMainParserContext() + +############################################################ +## support for Python unicode I/O +############################################################ + +# name of Python Py_UNICODE encoding as known to libxml2 +cdef const_char* _PY_UNICODE_ENCODING = NULL + +cdef int _setupPythonUnicode() except -1: + """Sets _PY_UNICODE_ENCODING to the internal encoding name of Python unicode + strings if libxml2 supports reading native Python unicode. This depends + on iconv and the local Python installation, so we simply check if we find + a matching encoding handler. + """ + cdef tree.xmlCharEncodingHandler* enchandler + cdef Py_ssize_t l + cdef const_char* enc + cdef Py_UNICODE *uchars = [c'<', c't', c'e', c's', c't', c'/', c'>'] + cdef const_xmlChar* buffer = uchars + # apparently, libxml2 can't detect UTF-16 on some systems + if (buffer[0] == c'<' and buffer[1] == c'\0' and + buffer[2] == c't' and buffer[3] == c'\0'): + enc = "UTF-16LE" + elif (buffer[0] == c'\0' and buffer[1] == c'<' and + buffer[2] == c'\0' and buffer[3] == c't'): + enc = "UTF-16BE" + else: + # let libxml2 give it a try + enc = _findEncodingName(buffer, sizeof(Py_UNICODE) * 7) + if enc is NULL: + # not my fault, it's YOUR broken system :) + return 0 + enchandler = tree.xmlFindCharEncodingHandler(enc) + if enchandler is not NULL: + global _PY_UNICODE_ENCODING + tree.xmlCharEncCloseFunc(enchandler) + _PY_UNICODE_ENCODING = enc + return 0 + +cdef const_char* _findEncodingName(const_xmlChar* buffer, int size): + "Work around bug in libxml2: find iconv name of encoding on our own." + cdef tree.xmlCharEncoding enc + enc = tree.xmlDetectCharEncoding(buffer, size) + if enc == tree.XML_CHAR_ENCODING_UTF16LE: + if size >= 4 and (buffer[0] == b'\xFF' and + buffer[1] == b'\xFE' and + buffer[2] == 0 and buffer[3] == 0): + return "UTF-32LE" # according to BOM + else: + return "UTF-16LE" + elif enc == tree.XML_CHAR_ENCODING_UTF16BE: + return "UTF-16BE" + elif enc == tree.XML_CHAR_ENCODING_UCS4LE: + return "UCS-4LE" + elif enc == tree.XML_CHAR_ENCODING_UCS4BE: + return "UCS-4BE" + elif enc == tree.XML_CHAR_ENCODING_NONE: + return NULL + else: + # returns a constant char*, no need to free it + return tree.xmlGetCharEncodingName(enc) + +# Python 3.12 removed support for "Py_UNICODE". +if python.PY_VERSION_HEX < 0x030C0000: + _setupPythonUnicode() + + +cdef unicode _find_PyUCS4EncodingName(): + """ + Find a suitable encoding for Py_UCS4 PyUnicode strings in libxml2. + """ + ustring = "\U0001F92A" + cdef const xmlChar* buffer = python.PyUnicode_DATA(ustring) + cdef Py_ssize_t py_buffer_len = python.PyUnicode_GET_LENGTH(ustring) + + encoding_name = '' + cdef tree.xmlCharEncoding enc = tree.xmlDetectCharEncoding(buffer, py_buffer_len) + enchandler = tree.xmlGetCharEncodingHandler(enc) + if enchandler is not NULL: + try: + if enchandler.name: + encoding_name = enchandler.name.decode('UTF-8') + finally: + tree.xmlCharEncCloseFunc(enchandler) + else: + c_name = tree.xmlGetCharEncodingName(enc) + if c_name: + encoding_name = c_name.decode('UTF-8') + + + if encoding_name and not encoding_name.endswith('LE') and not encoding_name.endswith('BE'): + encoding_name += 'BE' if python.PY_BIG_ENDIAN else 'LE' + return encoding_name or None + +_pyucs4_encoding_name = _find_PyUCS4EncodingName() + + +############################################################ +## support for file-like objects +############################################################ + +@cython.final +@cython.internal +cdef class _FileReaderContext: + cdef object _filelike + cdef object _encoding + cdef object _url + cdef object _bytes + cdef _ExceptionContext _exc_context + cdef Py_ssize_t _bytes_read + cdef char* _c_url + cdef bint _close_file_after_read + + def __cinit__(self, filelike, exc_context not None, url, encoding=None, bint close_file=False): + self._exc_context = exc_context + self._filelike = filelike + self._close_file_after_read = close_file + self._encoding = encoding + if url is None: + self._c_url = NULL + else: + url = _encodeFilename(url) + self._c_url = _cstr(url) + self._url = url + self._bytes = b'' + self._bytes_read = 0 + + cdef _close_file(self): + if self._filelike is None or not self._close_file_after_read: + return + try: + close = self._filelike.close + except AttributeError: + close = None + finally: + self._filelike = None + if close is not None: + close() + + cdef xmlparser.xmlParserInputBuffer* _createParserInputBuffer(self) noexcept: + cdef xmlparser.xmlParserInputBuffer* c_buffer = xmlparser.xmlAllocParserInputBuffer(0) + if c_buffer: + c_buffer.readcallback = _readFilelikeParser + c_buffer.context = self + return c_buffer + + cdef xmlparser.xmlParserInput* _createParserInput( + self, xmlparser.xmlParserCtxt* ctxt) noexcept: + cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer() + if not c_buffer: + return NULL + return xmlparser.xmlNewIOInputStream(ctxt, c_buffer, 0) + + cdef tree.xmlDtd* _readDtd(self) noexcept: + cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer() + if not c_buffer: + return NULL + with nogil: + return xmlparser.xmlIOParseDTD(NULL, c_buffer, 0) + + cdef xmlDoc* _readDoc(self, xmlparser.xmlParserCtxt* ctxt, int options) noexcept: + cdef xmlDoc* result + cdef void* c_callback_context = self + cdef char* c_encoding = _cstr(self._encoding) if self._encoding is not None else NULL + + orig_options = ctxt.options + with nogil: + if ctxt.html: + result = htmlparser.htmlCtxtReadIO( + ctxt, _readFilelikeParser, NULL, c_callback_context, + self._c_url, c_encoding, options) + if result is not NULL: + if _fixHtmlDictNames(ctxt.dict, result) < 0: + tree.xmlFreeDoc(result) + result = NULL + else: + result = xmlparser.xmlCtxtReadIO( + ctxt, _readFilelikeParser, NULL, c_callback_context, + self._c_url, c_encoding, options) + ctxt.options = orig_options # work around libxml2 problem + + try: + self._close_file() + except: + self._exc_context._store_raised() + finally: + return result # swallow any exceptions + + cdef int copyToBuffer(self, char* c_buffer, int c_requested) noexcept: + cdef int c_byte_count = 0 + cdef char* c_start + cdef Py_ssize_t byte_count, remaining + if self._bytes_read < 0: + return 0 + try: + byte_count = python.PyBytes_GET_SIZE(self._bytes) + remaining = byte_count - self._bytes_read + while c_requested > remaining: + c_start = _cstr(self._bytes) + self._bytes_read + cstring_h.memcpy(c_buffer, c_start, remaining) + c_byte_count += remaining + c_buffer += remaining + c_requested -= remaining + + self._bytes = self._filelike.read(c_requested) + if not isinstance(self._bytes, bytes): + if isinstance(self._bytes, unicode): + if self._encoding is None: + self._bytes = (self._bytes).encode('utf8') + else: + self._bytes = python.PyUnicode_AsEncodedString( + self._bytes, _cstr(self._encoding), NULL) + else: + self._close_file() + raise TypeError, \ + "reading from file-like objects must return byte strings or unicode strings" + + remaining = python.PyBytes_GET_SIZE(self._bytes) + if remaining == 0: + self._bytes_read = -1 + self._close_file() + return c_byte_count + self._bytes_read = 0 + + if c_requested > 0: + c_start = _cstr(self._bytes) + self._bytes_read + cstring_h.memcpy(c_buffer, c_start, c_requested) + c_byte_count += c_requested + self._bytes_read += c_requested + except: + c_byte_count = -1 + self._exc_context._store_raised() + try: + self._close_file() + except: + self._exc_context._store_raised() + finally: + return c_byte_count # swallow any exceptions + +cdef int _readFilelikeParser(void* ctxt, char* c_buffer, int c_size) noexcept with gil: + return (<_FileReaderContext>ctxt).copyToBuffer(c_buffer, c_size) + +cdef int _readFileParser(void* ctxt, char* c_buffer, int c_size) noexcept nogil: + return stdio.fread(c_buffer, 1, c_size, ctxt) + +############################################################ +## support for custom document loaders +############################################################ + +cdef xmlparser.xmlParserInput* _local_resolver(const_char* c_url, const_char* c_pubid, + xmlparser.xmlParserCtxt* c_context) noexcept with gil: + cdef _ResolverContext context + cdef xmlparser.xmlParserInput* c_input + cdef _InputDocument doc_ref + cdef _FileReaderContext file_context + # if there is no _ParserContext associated with the xmlParserCtxt + # passed, check to see if the thread state object has an implied + # context. + if c_context._private is not NULL: + context = <_ResolverContext>c_context._private + else: + context = __GLOBAL_PARSER_CONTEXT.findImpliedContext() + + if context is None: + if __DEFAULT_ENTITY_LOADER is NULL: + return NULL + with nogil: + # free the GIL as we might do serious I/O here (e.g. HTTP) + c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context) + return c_input + + try: + if c_url is NULL: + url = None + else: + # parsing a related document (DTD etc.) => UTF-8 encoded URL? + url = _decodeFilename(c_url) + if c_pubid is NULL: + pubid = None + else: + pubid = funicode(c_pubid) # always UTF-8 + + doc_ref = context._resolvers.resolve(url, pubid, context) + except: + context._store_raised() + return NULL + + if doc_ref is not None: + if doc_ref._type == PARSER_DATA_STRING: + data = doc_ref._data_bytes + filename = doc_ref._filename + if not filename: + filename = None + elif not isinstance(filename, bytes): + # most likely a text URL + filename = filename.encode('utf8') + if not isinstance(filename, bytes): + filename = None + + c_input = xmlparser.xmlNewInputStream(c_context) + if c_input is not NULL: + if filename is not None: + c_input.filename = tree.xmlStrdup(_xcstr(filename)) + c_input.base = _xcstr(data) + c_input.length = python.PyBytes_GET_SIZE(data) + c_input.cur = c_input.base + c_input.end = c_input.base + c_input.length + elif doc_ref._type == PARSER_DATA_FILENAME: + data = None + c_filename = _cstr(doc_ref._filename) + with nogil: + # free the GIL as we might do serious I/O here + c_input = xmlparser.xmlNewInputFromFile( + c_context, c_filename) + elif doc_ref._type == PARSER_DATA_FILE: + file_context = _FileReaderContext(doc_ref._file, context, url, + None, doc_ref._close_file) + c_input = file_context._createParserInput(c_context) + data = file_context + else: + data = None + c_input = NULL + + if data is not None: + context._storage.add(data) + if c_input is not NULL: + return c_input + + if __DEFAULT_ENTITY_LOADER is NULL: + return NULL + + with nogil: + # free the GIL as we might do serious I/O here (e.g. HTTP) + c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context) + return c_input + +cdef xmlparser.xmlExternalEntityLoader __DEFAULT_ENTITY_LOADER +__DEFAULT_ENTITY_LOADER = xmlparser.xmlGetExternalEntityLoader() + + +cdef xmlparser.xmlExternalEntityLoader _register_document_loader() noexcept nogil: + cdef xmlparser.xmlExternalEntityLoader old = xmlparser.xmlGetExternalEntityLoader() + xmlparser.xmlSetExternalEntityLoader(_local_resolver) + return old + +cdef void _reset_document_loader(xmlparser.xmlExternalEntityLoader old) noexcept nogil: + xmlparser.xmlSetExternalEntityLoader(old) + + +############################################################ +## Parsers +############################################################ + +@cython.no_gc_clear # May have to call "self._validator.disconnect()" on dealloc. +@cython.internal +cdef class _ParserContext(_ResolverContext): + cdef _ErrorLog _error_log + cdef _ParserSchemaValidationContext _validator + cdef xmlparser.xmlParserCtxt* _c_ctxt + cdef xmlparser.xmlExternalEntityLoader _orig_loader + cdef python.PyThread_type_lock _lock + cdef _Document _doc + cdef bint _collect_ids + + def __cinit__(self): + self._c_ctxt = NULL + self._collect_ids = True + if not config.ENABLE_THREADING: + self._lock = NULL + else: + self._lock = python.PyThread_allocate_lock() + self._error_log = _ErrorLog() + + def __dealloc__(self): + if config.ENABLE_THREADING and self._lock is not NULL: + python.PyThread_free_lock(self._lock) + self._lock = NULL + if self._c_ctxt is not NULL: + if self._validator is not NULL and self._validator is not None: + # If the parser was not closed correctly (e.g. interrupted iterparse()), + # and the schema validator wasn't freed and cleaned up yet, the libxml2 SAX + # validator plug might still be in place, which will make xmlFreeParserCtxt() + # crash when trying to xmlFree() a static SAX handler. + # Thus, make sure we disconnect the handler interceptor here at the latest. + self._validator.disconnect() + xmlparser.xmlFreeParserCtxt(self._c_ctxt) + + cdef _ParserContext _copy(self): + cdef _ParserContext context + context = self.__class__() + context._collect_ids = self._collect_ids + context._validator = self._validator.copy() + _initParserContext(context, self._resolvers._copy(), NULL) + return context + + cdef void _initParserContext(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept: + self._c_ctxt = c_ctxt + c_ctxt._private = self + + cdef void _resetParserContext(self) noexcept: + if self._c_ctxt is not NULL: + if self._c_ctxt.html: + htmlparser.htmlCtxtReset(self._c_ctxt) + self._c_ctxt.disableSAX = 0 # work around bug in libxml2 + else: + xmlparser.xmlClearParserCtxt(self._c_ctxt) + # work around bug in libxml2 [2.9.10 .. 2.9.14]: + # https://gitlab.gnome.org/GNOME/libxml2/-/issues/378 + self._c_ctxt.nsNr = 0 + + cdef int prepare(self, bint set_document_loader=True) except -1: + cdef int result + if config.ENABLE_THREADING and self._lock is not NULL: + with nogil: + result = python.PyThread_acquire_lock( + self._lock, python.WAIT_LOCK) + if result == 0: + raise ParserError, "parser locking failed" + self._error_log.clear() + self._doc = None + # Need a cast here because older libxml2 releases do not use 'const' in the functype. + self._c_ctxt.sax.serror = _receiveParserError + self._orig_loader = _register_document_loader() if set_document_loader else NULL + if self._validator is not None: + self._validator.connect(self._c_ctxt, self._error_log) + return 0 + + cdef int cleanup(self) except -1: + if self._orig_loader is not NULL: + _reset_document_loader(self._orig_loader) + try: + if self._validator is not None: + self._validator.disconnect() + self._resetParserContext() + self.clear() + self._doc = None + self._c_ctxt.sax.serror = NULL + finally: + if config.ENABLE_THREADING and self._lock is not NULL: + python.PyThread_release_lock(self._lock) + return 0 + + cdef object _handleParseResult(self, _BaseParser parser, + xmlDoc* result, filename): + c_doc = self._handleParseResultDoc(parser, result, filename) + if self._doc is not None and self._doc._c_doc is c_doc: + return self._doc + else: + return _documentFactory(c_doc, parser) + + cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser, + xmlDoc* result, filename) except NULL: + recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER + return _handleParseResult(self, self._c_ctxt, result, + filename, recover, + free_doc=self._doc is None) + +cdef _initParserContext(_ParserContext context, + _ResolverRegistry resolvers, + xmlparser.xmlParserCtxt* c_ctxt): + _initResolverContext(context, resolvers) + if c_ctxt is not NULL: + context._initParserContext(c_ctxt) + +cdef void _forwardParserError(xmlparser.xmlParserCtxt* _parser_context, const xmlerror.xmlError* error) noexcept with gil: + (<_ParserContext>_parser_context._private)._error_log._receive(error) + +cdef void _receiveParserError(void* c_context, const xmlerror.xmlError* error) noexcept nogil: + if __DEBUG: + if c_context is NULL or (c_context)._private is NULL: + _forwardError(NULL, error) + else: + _forwardParserError(c_context, error) + +cdef int _raiseParseError(xmlparser.xmlParserCtxt* ctxt, filename, + _ErrorLog error_log) except -1: + if filename is not None and \ + ctxt.lastError.domain == xmlerror.XML_FROM_IO: + if isinstance(filename, bytes): + filename = _decodeFilenameWithLength( + filename, len(filename)) + if ctxt.lastError.message is not NULL: + try: + message = ctxt.lastError.message.decode('utf-8') + except UnicodeDecodeError: + # the filename may be in there => play it safe + message = ctxt.lastError.message.decode('iso8859-1') + message = f"Error reading file '{filename}': {message.strip()}" + else: + message = f"Error reading '{filename}'" + raise IOError, message + elif error_log: + raise error_log._buildParseException( + XMLSyntaxError, "Document is not well formed") + elif ctxt.lastError.message is not NULL: + message = ctxt.lastError.message.strip() + code = ctxt.lastError.code + line = ctxt.lastError.line + column = ctxt.lastError.int2 + if ctxt.lastError.line > 0: + message = f"line {line}: {message}" + raise XMLSyntaxError(message, code, line, column, filename) + else: + raise XMLSyntaxError(None, xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0, + filename) + +cdef xmlDoc* _handleParseResult(_ParserContext context, + xmlparser.xmlParserCtxt* c_ctxt, + xmlDoc* result, filename, + bint recover, bint free_doc) except NULL: + cdef bint well_formed + if result is not NULL: + __GLOBAL_PARSER_CONTEXT.initDocDict(result) + + if c_ctxt.myDoc is not NULL: + if c_ctxt.myDoc is not result: + __GLOBAL_PARSER_CONTEXT.initDocDict(c_ctxt.myDoc) + tree.xmlFreeDoc(c_ctxt.myDoc) + c_ctxt.myDoc = NULL + + if result is not NULL: + if (context._validator is not None and + not context._validator.isvalid()): + well_formed = 0 # actually not 'valid', but anyway ... + elif (not c_ctxt.wellFormed and not c_ctxt.html and + c_ctxt.charset == tree.XML_CHAR_ENCODING_8859_1 and + [1 for error in context._error_log + if error.type == ErrorTypes.ERR_INVALID_CHAR]): + # An encoding error occurred and libxml2 switched from UTF-8 + # input to (undecoded) Latin-1, at some arbitrary point in the + # document. Better raise an error than allowing for a broken + # tree with mixed encodings. This is fixed in libxml2 2.12. + well_formed = 0 + elif recover or (c_ctxt.wellFormed and + c_ctxt.lastError.level < xmlerror.XML_ERR_ERROR): + well_formed = 1 + elif not c_ctxt.replaceEntities and not c_ctxt.validate \ + and context is not None: + # in this mode, we ignore errors about undefined entities + for error in context._error_log.filter_from_errors(): + if error.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \ + error.type != ErrorTypes.ERR_UNDECLARED_ENTITY: + well_formed = 0 + break + else: + well_formed = 1 + else: + well_formed = 0 + + if not well_formed: + if free_doc: + tree.xmlFreeDoc(result) + result = NULL + + if context is not None and context._has_raised(): + if result is not NULL: + if free_doc: + tree.xmlFreeDoc(result) + result = NULL + context._raise_if_stored() + + if result is NULL: + if context is not None: + _raiseParseError(c_ctxt, filename, context._error_log) + else: + _raiseParseError(c_ctxt, filename, None) + else: + if result.URL is NULL and filename is not None: + result.URL = tree.xmlStrdup(_xcstr(filename)) + if result.encoding is NULL: + result.encoding = tree.xmlStrdup("UTF-8") + + if context._validator is not None and \ + context._validator._add_default_attributes: + # we currently need to do this here as libxml2 does not + # support inserting default attributes during parse-time + # validation + context._validator.inject_default_attributes(result) + + return result + +cdef int _fixHtmlDictNames(tree.xmlDict* c_dict, xmlDoc* c_doc) noexcept nogil: + cdef xmlNode* c_node + if c_doc is NULL: + return 0 + c_node = c_doc.children + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_doc, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + if _fixHtmlDictNodeNames(c_dict, c_node) < 0: + return -1 + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + return 0 + +cdef int _fixHtmlDictSubtreeNames(tree.xmlDict* c_dict, xmlDoc* c_doc, + xmlNode* c_start_node) noexcept nogil: + """ + Move names to the dict, iterating in document order, starting at + c_start_node. This is used in incremental parsing after each chunk. + """ + cdef xmlNode* c_node + if not c_doc: + return 0 + if not c_start_node: + return _fixHtmlDictNames(c_dict, c_doc) + c_node = c_start_node + tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_doc, c_node, 1) + if c_node.type == tree.XML_ELEMENT_NODE: + if _fixHtmlDictNodeNames(c_dict, c_node) < 0: + return -1 + tree.END_FOR_EACH_ELEMENT_FROM(c_node) + return 0 + +cdef inline int _fixHtmlDictNodeNames(tree.xmlDict* c_dict, + xmlNode* c_node) noexcept nogil: + cdef xmlNode* c_attr + c_name = tree.xmlDictLookup(c_dict, c_node.name, -1) + if c_name is NULL: + return -1 + if c_name is not c_node.name: + tree.xmlFree(c_node.name) + c_node.name = c_name + c_attr = c_node.properties + while c_attr is not NULL: + c_name = tree.xmlDictLookup(c_dict, c_attr.name, -1) + if c_name is NULL: + return -1 + if c_name is not c_attr.name: + tree.xmlFree(c_attr.name) + c_attr.name = c_name + c_attr = c_attr.next + return 0 + + +@cython.internal +cdef class _BaseParser: + cdef ElementClassLookup _class_lookup + cdef _ResolverRegistry _resolvers + cdef _ParserContext _parser_context + cdef _ParserContext _push_parser_context + cdef int _parse_options + cdef bint _for_html + cdef bint _remove_comments + cdef bint _remove_pis + cdef bint _strip_cdata + cdef bint _collect_ids + cdef bint _resolve_external_entities + cdef XMLSchema _schema + cdef bytes _filename + cdef readonly object target + cdef object _default_encoding + cdef tuple _events_to_collect # (event_types, tag) + + def __init__(self, int parse_options, bint for_html, XMLSchema schema, + remove_comments, remove_pis, strip_cdata, collect_ids, + target, encoding, bint resolve_external_entities=True): + cdef tree.xmlCharEncodingHandler* enchandler + cdef int c_encoding + if not isinstance(self, (XMLParser, HTMLParser)): + raise TypeError, "This class cannot be instantiated" + + self._parse_options = parse_options + self.target = target + self._for_html = for_html + self._remove_comments = remove_comments + self._remove_pis = remove_pis + self._strip_cdata = strip_cdata + self._collect_ids = collect_ids + self._resolve_external_entities = resolve_external_entities + self._schema = schema + + self._resolvers = _ResolverRegistry() + + if encoding is None: + self._default_encoding = None + else: + encoding = _utf8(encoding) + enchandler = tree.xmlFindCharEncodingHandler(_cstr(encoding)) + if enchandler is NULL: + raise LookupError, f"unknown encoding: '{encoding}'" + tree.xmlCharEncCloseFunc(enchandler) + self._default_encoding = encoding + + cdef _setBaseURL(self, base_url): + self._filename = _encodeFilename(base_url) + + cdef _collectEvents(self, event_types, tag): + if event_types is None: + event_types = () + else: + event_types = tuple(set(event_types)) + _buildParseEventFilter(event_types) # purely for validation + self._events_to_collect = (event_types, tag) + + cdef _ParserContext _getParserContext(self): + cdef xmlparser.xmlParserCtxt* pctxt + if self._parser_context is None: + self._parser_context = self._createContext(self.target, None) + self._parser_context._collect_ids = self._collect_ids + if self._schema is not None: + self._parser_context._validator = \ + self._schema._newSaxValidator( + self._parse_options & xmlparser.XML_PARSE_DTDATTR) + pctxt = self._newParserCtxt() + _initParserContext(self._parser_context, self._resolvers, pctxt) + self._configureSaxContext(pctxt) + return self._parser_context + + cdef _ParserContext _getPushParserContext(self): + cdef xmlparser.xmlParserCtxt* pctxt + if self._push_parser_context is None: + self._push_parser_context = self._createContext( + self.target, self._events_to_collect) + self._push_parser_context._collect_ids = self._collect_ids + if self._schema is not None: + self._push_parser_context._validator = \ + self._schema._newSaxValidator( + self._parse_options & xmlparser.XML_PARSE_DTDATTR) + pctxt = self._newPushParserCtxt() + _initParserContext( + self._push_parser_context, self._resolvers, pctxt) + self._configureSaxContext(pctxt) + return self._push_parser_context + + cdef _ParserContext _createContext(self, target, events_to_collect): + cdef _SaxParserContext sax_context + if target is not None: + sax_context = _TargetParserContext(self) + (<_TargetParserContext>sax_context)._setTarget(target) + elif events_to_collect: + sax_context = _SaxParserContext(self) + else: + # nothing special to configure + return _ParserContext() + if events_to_collect: + events, tag = events_to_collect + sax_context._setEventFilter(events, tag) + return sax_context + + @cython.final + cdef int _configureSaxContext(self, xmlparser.xmlParserCtxt* pctxt) except -1: + if self._remove_comments: + pctxt.sax.comment = NULL + if self._remove_pis: + pctxt.sax.processingInstruction = NULL + if self._strip_cdata: + # hard switch-off for CDATA nodes => makes them plain text + pctxt.sax.cdataBlock = NULL + if not self._resolve_external_entities: + pctxt.sax.getEntity = _getInternalEntityOnly + + cdef int _registerHtmlErrorHandler(self, xmlparser.xmlParserCtxt* c_ctxt) except -1: + cdef xmlparser.xmlSAXHandler* sax = c_ctxt.sax + if sax is not NULL and sax.initialized and sax.initialized != xmlparser.XML_SAX2_MAGIC: + # need to extend SAX1 context to SAX2 to get proper error reports + if sax is &htmlparser.htmlDefaultSAXHandler: + sax = tree.xmlMalloc(sizeof(xmlparser.xmlSAXHandler)) + if sax is NULL: + raise MemoryError() + cstring_h.memcpy(sax, &htmlparser.htmlDefaultSAXHandler, + sizeof(htmlparser.htmlDefaultSAXHandler)) + c_ctxt.sax = sax + sax.initialized = xmlparser.XML_SAX2_MAGIC + # Need a cast here because older libxml2 releases do not use 'const' in the functype. + sax.serror = _receiveParserError + sax.startElementNs = NULL + sax.endElementNs = NULL + sax._private = NULL + return 0 + + cdef xmlparser.xmlParserCtxt* _newParserCtxt(self) except NULL: + cdef xmlparser.xmlParserCtxt* c_ctxt + if self._for_html: + c_ctxt = htmlparser.htmlCreateMemoryParserCtxt('dummy', 5) + if c_ctxt is not NULL: + self._registerHtmlErrorHandler(c_ctxt) + else: + c_ctxt = xmlparser.xmlNewParserCtxt() + if c_ctxt is NULL: + raise MemoryError + c_ctxt.sax.startDocument = _initSaxDocument + return c_ctxt + + cdef xmlparser.xmlParserCtxt* _newPushParserCtxt(self) except NULL: + cdef xmlparser.xmlParserCtxt* c_ctxt + cdef char* c_filename = _cstr(self._filename) if self._filename is not None else NULL + if self._for_html: + c_ctxt = htmlparser.htmlCreatePushParserCtxt( + NULL, NULL, NULL, 0, c_filename, tree.XML_CHAR_ENCODING_NONE) + if c_ctxt is not NULL: + self._registerHtmlErrorHandler(c_ctxt) + htmlparser.htmlCtxtUseOptions(c_ctxt, self._parse_options) + else: + c_ctxt = xmlparser.xmlCreatePushParserCtxt( + NULL, NULL, NULL, 0, c_filename) + if c_ctxt is not NULL: + xmlparser.xmlCtxtUseOptions(c_ctxt, self._parse_options) + if c_ctxt is NULL: + raise MemoryError() + c_ctxt.sax.startDocument = _initSaxDocument + return c_ctxt + + @property + def error_log(self): + """The error log of the last parser run. + """ + cdef _ParserContext context + context = self._getParserContext() + return context._error_log.copy() + + @property + def resolvers(self): + """The custom resolver registry of this parser.""" + return self._resolvers + + @property + def version(self): + """The version of the underlying XML parser.""" + return "libxml2 %d.%d.%d" % LIBXML_VERSION + + def set_element_class_lookup(self, ElementClassLookup lookup = None): + """set_element_class_lookup(self, lookup = None) + + Set a lookup scheme for element classes generated from this parser. + + Reset it by passing None or nothing. + """ + self._class_lookup = lookup + + cdef _BaseParser _copy(self): + "Create a new parser with the same configuration." + cdef _BaseParser parser + parser = self.__class__() + parser._parse_options = self._parse_options + parser._for_html = self._for_html + parser._remove_comments = self._remove_comments + parser._remove_pis = self._remove_pis + parser._strip_cdata = self._strip_cdata + parser._filename = self._filename + parser._resolvers = self._resolvers + parser.target = self.target + parser._class_lookup = self._class_lookup + parser._default_encoding = self._default_encoding + parser._schema = self._schema + parser._events_to_collect = self._events_to_collect + return parser + + def copy(self): + """copy(self) + + Create a new parser with the same configuration. + """ + return self._copy() + + def makeelement(self, _tag, attrib=None, nsmap=None, **_extra): + """makeelement(self, _tag, attrib=None, nsmap=None, **_extra) + + Creates a new element associated with this parser. + """ + return _makeElement(_tag, NULL, None, self, None, None, + attrib, nsmap, _extra) + + # internal parser methods + + cdef xmlDoc* _parseUnicodeDoc(self, utext, char* c_filename) except NULL: + """Parse unicode document, share dictionary if possible. + """ + cdef _ParserContext context + cdef xmlDoc* result + cdef xmlparser.xmlParserCtxt* pctxt + cdef Py_ssize_t py_buffer_len + cdef int buffer_len, c_kind + cdef const_char* c_text + cdef const_char* c_encoding = _PY_UNICODE_ENCODING + if python.PyUnicode_IS_READY(utext): + # PEP-393 string + c_text = python.PyUnicode_DATA(utext) + py_buffer_len = python.PyUnicode_GET_LENGTH(utext) + c_kind = python.PyUnicode_KIND(utext) + if c_kind == 1: + if python.PyUnicode_MAX_CHAR_VALUE(utext) <= 127: + c_encoding = 'UTF-8' + else: + c_encoding = 'ISO-8859-1' + elif c_kind == 2: + py_buffer_len *= 2 + if python.PY_BIG_ENDIAN: + c_encoding = 'UTF-16BE' # actually UCS-2 + else: + c_encoding = 'UTF-16LE' # actually UCS-2 + elif c_kind == 4: + py_buffer_len *= 4 + if python.PY_BIG_ENDIAN: + c_encoding = 'UTF-32BE' # actually UCS-4 + else: + c_encoding = 'UTF-32LE' # actually UCS-4 + else: + assert False, f"Illegal Unicode kind {c_kind}" + else: + # old Py_UNICODE string + py_buffer_len = python.PyUnicode_GET_DATA_SIZE(utext) + c_text = python.PyUnicode_AS_DATA(utext) + assert 0 <= py_buffer_len <= limits.INT_MAX + buffer_len = py_buffer_len + + context = self._getParserContext() + context.prepare() + try: + pctxt = context._c_ctxt + __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt) + orig_options = pctxt.options + with nogil: + if self._for_html: + result = htmlparser.htmlCtxtReadMemory( + pctxt, c_text, buffer_len, c_filename, c_encoding, + self._parse_options) + if result is not NULL: + if _fixHtmlDictNames(pctxt.dict, result) < 0: + tree.xmlFreeDoc(result) + result = NULL + else: + result = xmlparser.xmlCtxtReadMemory( + pctxt, c_text, buffer_len, c_filename, c_encoding, + self._parse_options) + pctxt.options = orig_options # work around libxml2 problem + + return context._handleParseResultDoc(self, result, None) + finally: + context.cleanup() + + cdef xmlDoc* _parseDoc(self, char* c_text, int c_len, + char* c_filename) except NULL: + """Parse document, share dictionary if possible. + """ + cdef _ParserContext context + cdef xmlDoc* result + cdef xmlparser.xmlParserCtxt* pctxt + cdef char* c_encoding + cdef tree.xmlCharEncoding enc + context = self._getParserContext() + context.prepare() + try: + pctxt = context._c_ctxt + __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt) + + if self._default_encoding is None: + c_encoding = NULL + # libxml2 (at least 2.9.3) does not recognise UTF-32 BOMs + # NOTE: limit to problematic cases because it changes character offsets + if c_len >= 4 and (c_text[0] == b'\xFF' and c_text[1] == b'\xFE' and + c_text[2] == 0 and c_text[3] == 0): + c_encoding = "UTF-32LE" + c_text += 4 + c_len -= 4 + elif c_len >= 4 and (c_text[0] == 0 and c_text[1] == 0 and + c_text[2] == b'\xFE' and c_text[3] == b'\xFF'): + c_encoding = "UTF-32BE" + c_text += 4 + c_len -= 4 + else: + # no BOM => try to determine encoding + enc = tree.xmlDetectCharEncoding(c_text, c_len) + if enc == tree.XML_CHAR_ENCODING_UCS4LE: + c_encoding = 'UTF-32LE' + elif enc == tree.XML_CHAR_ENCODING_UCS4BE: + c_encoding = 'UTF-32BE' + else: + c_encoding = _cstr(self._default_encoding) + + orig_options = pctxt.options + with nogil: + if self._for_html: + result = htmlparser.htmlCtxtReadMemory( + pctxt, c_text, c_len, c_filename, + c_encoding, self._parse_options) + if result is not NULL: + if _fixHtmlDictNames(pctxt.dict, result) < 0: + tree.xmlFreeDoc(result) + result = NULL + else: + result = xmlparser.xmlCtxtReadMemory( + pctxt, c_text, c_len, c_filename, + c_encoding, self._parse_options) + pctxt.options = orig_options # work around libxml2 problem + + return context._handleParseResultDoc(self, result, None) + finally: + context.cleanup() + + cdef xmlDoc* _parseDocFromFile(self, char* c_filename) except NULL: + cdef _ParserContext context + cdef xmlDoc* result + cdef xmlparser.xmlParserCtxt* pctxt + cdef char* c_encoding + result = NULL + + context = self._getParserContext() + context.prepare() + try: + pctxt = context._c_ctxt + __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt) + + if self._default_encoding is None: + c_encoding = NULL + else: + c_encoding = _cstr(self._default_encoding) + + orig_options = pctxt.options + with nogil: + if self._for_html: + result = htmlparser.htmlCtxtReadFile( + pctxt, c_filename, c_encoding, self._parse_options) + if result is not NULL: + if _fixHtmlDictNames(pctxt.dict, result) < 0: + tree.xmlFreeDoc(result) + result = NULL + else: + result = xmlparser.xmlCtxtReadFile( + pctxt, c_filename, c_encoding, self._parse_options) + pctxt.options = orig_options # work around libxml2 problem + + return context._handleParseResultDoc(self, result, c_filename) + finally: + context.cleanup() + + cdef xmlDoc* _parseDocFromFilelike(self, filelike, filename, + encoding) except NULL: + cdef _ParserContext context + cdef _FileReaderContext file_context + cdef xmlDoc* result + cdef xmlparser.xmlParserCtxt* pctxt + cdef char* c_filename + if not filename: + filename = None + + context = self._getParserContext() + context.prepare() + try: + pctxt = context._c_ctxt + __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt) + file_context = _FileReaderContext( + filelike, context, filename, + encoding or self._default_encoding) + result = file_context._readDoc(pctxt, self._parse_options) + + return context._handleParseResultDoc( + self, result, filename) + finally: + context.cleanup() + + +cdef tree.xmlEntity* _getInternalEntityOnly(void* ctxt, const_xmlChar* name) noexcept nogil: + """ + Callback function to intercept the entity resolution when external entity loading is disabled. + """ + cdef tree.xmlEntity* entity = xmlparser.xmlSAX2GetEntity(ctxt, name) + if not entity: + return NULL + if entity.etype not in ( + tree.xmlEntityType.XML_EXTERNAL_GENERAL_PARSED_ENTITY, + tree.xmlEntityType.XML_EXTERNAL_GENERAL_UNPARSED_ENTITY, + tree.xmlEntityType.XML_EXTERNAL_PARAMETER_ENTITY): + return entity + + # Reject all external entities and fail the parsing instead. There is currently + # no way in libxml2 to just prevent the entity resolution in this case. + cdef xmlerror.xmlError c_error + cdef xmlerror.xmlStructuredErrorFunc err_func + cdef xmlparser.xmlParserInput* parser_input + cdef void* err_context + + c_ctxt = ctxt + err_func = xmlerror.xmlStructuredError + if err_func: + parser_input = c_ctxt.input + # Copied from xmlVErrParser() in libxml2: get current input from stack. + if parser_input and parser_input.filename is NULL and c_ctxt.inputNr > 1: + parser_input = c_ctxt.inputTab[c_ctxt.inputNr - 2] + + c_error = xmlerror.xmlError( + domain=xmlerror.xmlErrorDomain.XML_FROM_PARSER, + code=xmlerror.xmlParserErrors.XML_ERR_EXT_ENTITY_STANDALONE, + level=xmlerror.xmlErrorLevel.XML_ERR_FATAL, + message=b"External entity resolution is disabled for security reasons " + b"when resolving '&%s;'. Use 'XMLParser(resolve_entities=True)' " + b"if you consider it safe to enable it.", + file=parser_input.filename, + node=entity, + str1= name, + str2=NULL, + str3=NULL, + line=parser_input.line if parser_input else 0, + int1=0, + int2=parser_input.col if parser_input else 0, + ) + err_context = xmlerror.xmlStructuredErrorContext + err_func(err_context, &c_error) + + c_ctxt.wellFormed = 0 + # The entity was looked up and does not need to be freed. + return NULL + + +cdef void _initSaxDocument(void* ctxt) noexcept with gil: + xmlparser.xmlSAX2StartDocument(ctxt) + c_ctxt = ctxt + c_doc = c_ctxt.myDoc + + # set up document dict + if c_doc and c_ctxt.dict and not c_doc.dict: + # I have no idea why libxml2 disables this - we need it + c_ctxt.dictNames = 1 + c_doc.dict = c_ctxt.dict + xmlparser.xmlDictReference(c_ctxt.dict) + + # set up XML ID hash table + if c_ctxt._private: + context = <_ParserContext>c_ctxt._private + if context._collect_ids: + # keep the global parser dict from filling up with XML IDs + if c_doc and not c_doc.ids: + # memory errors are not fatal here + c_dict = xmlparser.xmlDictCreate() + if c_dict: + c_doc.ids = tree.xmlHashCreateDict(0, c_dict) + xmlparser.xmlDictFree(c_dict) + else: + c_doc.ids = tree.xmlHashCreate(0) + else: + c_ctxt.loadsubset |= xmlparser.XML_SKIP_IDS + if c_doc and c_doc.ids and not tree.xmlHashSize(c_doc.ids): + # already initialised but empty => clear + tree.xmlHashFree(c_doc.ids, NULL) + c_doc.ids = NULL + + +############################################################ +## ET feed parser +############################################################ + +cdef class _FeedParser(_BaseParser): + cdef bint _feed_parser_running + + @property + def feed_error_log(self): + """The error log of the last (or current) run of the feed parser. + + Note that this is local to the feed parser and thus is + different from what the ``error_log`` property returns. + """ + return self._getPushParserContext()._error_log.copy() + + cpdef feed(self, data): + """feed(self, data) + + Feeds data to the parser. The argument should be an 8-bit string + buffer containing encoded data, although Unicode is supported as long + as both string types are not mixed. + + This is the main entry point to the consumer interface of a + parser. The parser will parse as much of the XML stream as it + can on each call. To finish parsing or to reset the parser, + call the ``close()`` method. Both methods may raise + ParseError if errors occur in the input data. If an error is + raised, there is no longer a need to call ``close()``. + + The feed parser interface is independent of the normal parser + usage. You can use the same parser as a feed parser and in + the ``parse()`` function concurrently. + """ + cdef _ParserContext context + cdef bytes bstring + cdef xmlparser.xmlParserCtxt* pctxt + cdef Py_ssize_t py_buffer_len, ustart + cdef const_char* char_data + cdef const_char* c_encoding + cdef int buffer_len + cdef int error + cdef bint recover = self._parse_options & xmlparser.XML_PARSE_RECOVER + + if isinstance(data, bytes): + if self._default_encoding is None: + c_encoding = NULL + else: + c_encoding = self._default_encoding + char_data = _cstr(data) + py_buffer_len = python.PyBytes_GET_SIZE(data) + ustart = 0 + elif isinstance(data, unicode): + c_encoding = b"UTF-8" + char_data = NULL + py_buffer_len = len( data) + ustart = 0 + else: + raise TypeError, "Parsing requires string data" + + context = self._getPushParserContext() + pctxt = context._c_ctxt + error = 0 + if not self._feed_parser_running: + context.prepare(set_document_loader=False) + self._feed_parser_running = 1 + c_filename = (_cstr(self._filename) + if self._filename is not None else NULL) + + # We have to give *mlCtxtResetPush() enough input to figure + # out the character encoding (at least four bytes), + # however if we give it all we got, we'll have nothing for + # *mlParseChunk() and things go wrong. + buffer_len = 0 + if char_data is not NULL: + buffer_len = 4 if py_buffer_len > 4 else py_buffer_len + orig_loader = _register_document_loader() + if self._for_html: + error = _htmlCtxtResetPush( + pctxt, char_data, buffer_len, c_filename, c_encoding, + self._parse_options) + else: + xmlparser.xmlCtxtUseOptions(pctxt, self._parse_options) + error = xmlparser.xmlCtxtResetPush( + pctxt, char_data, buffer_len, c_filename, c_encoding) + _reset_document_loader(orig_loader) + py_buffer_len -= buffer_len + char_data += buffer_len + if error: + raise MemoryError() + __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt) + + #print pctxt.charset, 'NONE' if c_encoding is NULL else c_encoding + + fixup_error = 0 + while py_buffer_len > 0 and (error == 0 or recover): + if char_data is NULL: + # Unicode parsing by converting chunks to UTF-8 + buffer_len = 2**19 # len(bytes) <= 4 * (2**19) == 2 MiB + bstring = ( data)[ustart : ustart+buffer_len].encode('UTF-8') + ustart += buffer_len + py_buffer_len -= buffer_len # may end up < 0 + error, fixup_error = _parse_data_chunk(pctxt, bstring, len(bstring)) + else: + # Direct byte string parsing. + buffer_len = py_buffer_len if py_buffer_len <= limits.INT_MAX else limits.INT_MAX + error, fixup_error = _parse_data_chunk(pctxt, char_data, buffer_len) + py_buffer_len -= buffer_len + char_data += buffer_len + + if fixup_error: + context.store_exception(MemoryError()) + + if context._has_raised(): + # propagate Python exceptions immediately + recover = 0 + error = 1 + break + + if error and not pctxt.replaceEntities and not pctxt.validate: + # in this mode, we ignore errors about undefined entities + for entry in context._error_log.filter_from_errors(): + if entry.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \ + entry.type != ErrorTypes.ERR_UNDECLARED_ENTITY: + break + else: + error = 0 + + if not pctxt.wellFormed and pctxt.disableSAX and context._has_raised(): + # propagate Python exceptions immediately + recover = 0 + error = 1 + + if fixup_error or not recover and (error or not pctxt.wellFormed): + self._feed_parser_running = 0 + try: + context._handleParseResult(self, pctxt.myDoc, None) + finally: + context.cleanup() + + cpdef close(self): + """close(self) + + Terminates feeding data to this parser. This tells the parser to + process any remaining data in the feed buffer, and then returns the + root Element of the tree that was parsed. + + This method must be called after passing the last chunk of data into + the ``feed()`` method. It should only be called when using the feed + parser interface, all other usage is undefined. + """ + if not self._feed_parser_running: + raise XMLSyntaxError("no element found", + xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0, + self._filename) + + context = self._getPushParserContext() + pctxt = context._c_ctxt + + self._feed_parser_running = 0 + if self._for_html: + htmlparser.htmlParseChunk(pctxt, NULL, 0, 1) + else: + xmlparser.xmlParseChunk(pctxt, NULL, 0, 1) + + if (pctxt.recovery and not pctxt.disableSAX and + isinstance(context, _SaxParserContext)): + # apply any left-over 'end' events + (<_SaxParserContext>context).flushEvents() + + try: + result = context._handleParseResult(self, pctxt.myDoc, None) + finally: + context.cleanup() + + if isinstance(result, _Document): + return (<_Document>result).getroot() + else: + return result + + +cdef (int, int) _parse_data_chunk(xmlparser.xmlParserCtxt* c_ctxt, + const char* char_data, int buffer_len): + fixup_error = 0 + with nogil: + if c_ctxt.html: + c_node = c_ctxt.node # last node where the parser stopped + orig_loader = _register_document_loader() + error = htmlparser.htmlParseChunk(c_ctxt, char_data, buffer_len, 0) + _reset_document_loader(orig_loader) + # and now for the fun part: move node names to the dict + if c_ctxt.myDoc: + fixup_error = _fixHtmlDictSubtreeNames( + c_ctxt.dict, c_ctxt.myDoc, c_node) + if c_ctxt.myDoc.dict and c_ctxt.myDoc.dict is not c_ctxt.dict: + xmlparser.xmlDictFree(c_ctxt.myDoc.dict) + c_ctxt.myDoc.dict = c_ctxt.dict + xmlparser.xmlDictReference(c_ctxt.dict) + else: + orig_loader = _register_document_loader() + error = xmlparser.xmlParseChunk(c_ctxt, char_data, buffer_len, 0) + _reset_document_loader(orig_loader) + return (error, fixup_error) + + +cdef int _htmlCtxtResetPush(xmlparser.xmlParserCtxt* c_ctxt, + const_char* c_data, int buffer_len, + const_char* c_filename, const_char* c_encoding, + int parse_options) except -1: + cdef xmlparser.xmlParserInput* c_input_stream + # libxml2 lacks an HTML push parser setup function + error = xmlparser.xmlCtxtResetPush( + c_ctxt, c_data, buffer_len, c_filename, c_encoding) + if error: + return error + + # fix libxml2 setup for HTML + c_ctxt.progressive = 1 + c_ctxt.html = 1 + htmlparser.htmlCtxtUseOptions(c_ctxt, parse_options) + + return 0 + + +############################################################ +## XML parser +############################################################ + +cdef int _XML_DEFAULT_PARSE_OPTIONS +_XML_DEFAULT_PARSE_OPTIONS = ( + xmlparser.XML_PARSE_NOENT | + xmlparser.XML_PARSE_NOCDATA | + xmlparser.XML_PARSE_NONET | + xmlparser.XML_PARSE_COMPACT | + xmlparser.XML_PARSE_BIG_LINES + ) + +cdef class XMLParser(_FeedParser): + """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) + + The XML parser. + + Parsers can be supplied as additional argument to various parse + functions of the lxml API. A default parser is always available + and can be replaced by a call to the global function + 'set_default_parser'. New parsers can be created at any time + without a major run-time overhead. + + The keyword arguments in the constructor are mainly based on the + libxml2 parser configuration. A DTD will also be loaded if DTD + validation or attribute default values are requested (unless you + additionally provide an XMLSchema from which the default + attributes can be read). + + Available boolean keyword arguments: + + - attribute_defaults - inject default attributes from DTD or XMLSchema + - dtd_validation - validate against a DTD referenced by the document + - load_dtd - use DTD for parsing + - no_network - prevent network access for related files (default: True) + - ns_clean - clean up redundant namespace declarations + - recover - try hard to parse through broken XML + - remove_blank_text - discard blank text nodes that appear ignorable + - remove_comments - discard comments + - remove_pis - discard processing instructions + - strip_cdata - replace CDATA sections by normal text content (default: True) + - compact - save memory for short text content (default: True) + - collect_ids - use a hash table of XML IDs for fast access (default: True, always True with DTD validation) + - huge_tree - disable security restrictions and support very deep trees + and very long text content (only affects libxml2 2.7+) + + Other keyword arguments: + + - resolve_entities - replace entities by their text value: False for keeping the + entity references, True for resolving them, and 'internal' for resolving + internal definitions only (no external file/URL access). + The default used to be True and was changed to 'internal' in lxml 5.0. + - encoding - override the document encoding (note: libiconv encoding name) + - target - a parser target object that will receive the parse events + - schema - an XMLSchema to validate against + + Note that you should avoid sharing parsers between threads. While this is + not harmful, it is more efficient to use separate parsers. This does not + apply to the default parser. + """ + def __init__(self, *, encoding=None, attribute_defaults=False, + dtd_validation=False, load_dtd=False, no_network=True, + ns_clean=False, recover=False, XMLSchema schema=None, + huge_tree=False, remove_blank_text=False, resolve_entities='internal', + remove_comments=False, remove_pis=False, strip_cdata=True, + collect_ids=True, target=None, compact=True): + cdef int parse_options + cdef bint resolve_external = True + parse_options = _XML_DEFAULT_PARSE_OPTIONS + if load_dtd: + parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD + if dtd_validation: + parse_options = parse_options | xmlparser.XML_PARSE_DTDVALID | \ + xmlparser.XML_PARSE_DTDLOAD + if attribute_defaults: + parse_options = parse_options | xmlparser.XML_PARSE_DTDATTR + if schema is None: + parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD + if ns_clean: + parse_options = parse_options | xmlparser.XML_PARSE_NSCLEAN + if recover: + parse_options = parse_options | xmlparser.XML_PARSE_RECOVER + if remove_blank_text: + parse_options = parse_options | xmlparser.XML_PARSE_NOBLANKS + if huge_tree: + parse_options = parse_options | xmlparser.XML_PARSE_HUGE + if not no_network: + parse_options = parse_options ^ xmlparser.XML_PARSE_NONET + if not compact: + parse_options = parse_options ^ xmlparser.XML_PARSE_COMPACT + if not resolve_entities: + parse_options = parse_options ^ xmlparser.XML_PARSE_NOENT + elif resolve_entities == 'internal': + resolve_external = False + if not strip_cdata: + parse_options = parse_options ^ xmlparser.XML_PARSE_NOCDATA + + _BaseParser.__init__(self, parse_options, False, schema, + remove_comments, remove_pis, strip_cdata, + collect_ids, target, encoding, resolve_external) + + +cdef class XMLPullParser(XMLParser): + """XMLPullParser(self, events=None, *, tag=None, **kwargs) + + XML parser that collects parse events in an iterator. + + The collected events are the same as for iterparse(), but the + parser itself is non-blocking in the sense that it receives + data chunks incrementally through its .feed() method, instead + of reading them directly from a file(-like) object all by itself. + + By default, it collects Element end events. To change that, + pass any subset of the available events into the ``events`` + argument: ``'start'``, ``'end'``, ``'start-ns'``, + ``'end-ns'``, ``'comment'``, ``'pi'``. + + To support loading external dependencies relative to the input + source, you can pass the ``base_url``. + """ + def __init__(self, events=None, *, tag=None, base_url=None, **kwargs): + XMLParser.__init__(self, **kwargs) + if events is None: + events = ('end',) + self._setBaseURL(base_url) + self._collectEvents(events, tag) + + def read_events(self): + return (<_SaxParserContext?>self._getPushParserContext()).events_iterator + + +cdef class ETCompatXMLParser(XMLParser): + """ETCompatXMLParser(self, encoding=None, attribute_defaults=False, \ + dtd_validation=False, load_dtd=False, no_network=True, \ + ns_clean=False, recover=False, schema=None, \ + huge_tree=False, remove_blank_text=False, resolve_entities=True, \ + remove_comments=True, remove_pis=True, strip_cdata=True, \ + target=None, compact=True) + + An XML parser with an ElementTree compatible default setup. + + See the XMLParser class for details. + + This parser has ``remove_comments`` and ``remove_pis`` enabled by default + and thus ignores comments and processing instructions. + """ + def __init__(self, *, encoding=None, attribute_defaults=False, + dtd_validation=False, load_dtd=False, no_network=True, + ns_clean=False, recover=False, schema=None, + huge_tree=False, remove_blank_text=False, resolve_entities=True, + remove_comments=True, remove_pis=True, strip_cdata=True, + target=None, compact=True): + XMLParser.__init__(self, + attribute_defaults=attribute_defaults, + dtd_validation=dtd_validation, + load_dtd=load_dtd, + no_network=no_network, + ns_clean=ns_clean, + recover=recover, + remove_blank_text=remove_blank_text, + huge_tree=huge_tree, + compact=compact, + resolve_entities=resolve_entities, + remove_comments=remove_comments, + remove_pis=remove_pis, + strip_cdata=strip_cdata, + target=target, + encoding=encoding, + schema=schema) + +# ET 1.2 compatible name +XMLTreeBuilder = ETCompatXMLParser + + +cdef XMLParser __DEFAULT_XML_PARSER +__DEFAULT_XML_PARSER = XMLParser() + +__GLOBAL_PARSER_CONTEXT.setDefaultParser(__DEFAULT_XML_PARSER) + +def set_default_parser(_BaseParser parser=None): + """set_default_parser(parser=None) + + Set a default parser for the current thread. This parser is used + globally whenever no parser is supplied to the various parse functions of + the lxml API. If this function is called without a parser (or if it is + None), the default parser is reset to the original configuration. + + Note that the pre-installed default parser is not thread-safe. Avoid the + default parser in multi-threaded environments. You can create a separate + parser for each thread explicitly or use a parser pool. + """ + if parser is None: + parser = __DEFAULT_XML_PARSER + __GLOBAL_PARSER_CONTEXT.setDefaultParser(parser) + +def get_default_parser(): + "get_default_parser()" + return __GLOBAL_PARSER_CONTEXT.getDefaultParser() + +############################################################ +## HTML parser +############################################################ + +cdef int _HTML_DEFAULT_PARSE_OPTIONS +_HTML_DEFAULT_PARSE_OPTIONS = ( + htmlparser.HTML_PARSE_RECOVER | + htmlparser.HTML_PARSE_NONET | + htmlparser.HTML_PARSE_COMPACT + ) + +cdef class HTMLParser(_FeedParser): + """HTMLParser(self, encoding=None, remove_blank_text=False, \ + remove_comments=False, remove_pis=False, strip_cdata=True, \ + no_network=True, target=None, schema: XMLSchema =None, \ + recover=True, compact=True, collect_ids=True, huge_tree=False) + + The HTML parser. + + This parser allows reading HTML into a normal XML tree. By + default, it can read broken (non well-formed) HTML, depending on + the capabilities of libxml2. Use the 'recover' option to switch + this off. + + Available boolean keyword arguments: + + - recover - try hard to parse through broken HTML (default: True) + - no_network - prevent network access for related files (default: True) + - remove_blank_text - discard empty text nodes that are ignorable (i.e. not actual text content) + - remove_comments - discard comments + - remove_pis - discard processing instructions + - strip_cdata - replace CDATA sections by normal text content (default: True) + - compact - save memory for short text content (default: True) + - default_doctype - add a default doctype even if it is not found in the HTML (default: True) + - collect_ids - use a hash table of XML IDs for fast access (default: True) + - huge_tree - disable security restrictions and support very deep trees + and very long text content (only affects libxml2 2.7+) + + Other keyword arguments: + + - encoding - override the document encoding (note: libiconv encoding name) + - target - a parser target object that will receive the parse events + - schema - an XMLSchema to validate against + + Note that you should avoid sharing parsers between threads for performance + reasons. + """ + def __init__(self, *, encoding=None, remove_blank_text=False, + remove_comments=False, remove_pis=False, strip_cdata=True, + no_network=True, target=None, XMLSchema schema=None, + recover=True, compact=True, default_doctype=True, + collect_ids=True, huge_tree=False): + cdef int parse_options + parse_options = _HTML_DEFAULT_PARSE_OPTIONS + if remove_blank_text: + parse_options = parse_options | htmlparser.HTML_PARSE_NOBLANKS + if not recover: + parse_options = parse_options ^ htmlparser.HTML_PARSE_RECOVER + if not no_network: + parse_options = parse_options ^ htmlparser.HTML_PARSE_NONET + if not compact: + parse_options = parse_options ^ htmlparser.HTML_PARSE_COMPACT + if not default_doctype: + parse_options = parse_options ^ htmlparser.HTML_PARSE_NODEFDTD + if huge_tree: + parse_options = parse_options | xmlparser.XML_PARSE_HUGE + + _BaseParser.__init__(self, parse_options, True, schema, + remove_comments, remove_pis, strip_cdata, + collect_ids, target, encoding) + + +cdef HTMLParser __DEFAULT_HTML_PARSER +__DEFAULT_HTML_PARSER = HTMLParser() + + +cdef class HTMLPullParser(HTMLParser): + """HTMLPullParser(self, events=None, *, tag=None, base_url=None, **kwargs) + + HTML parser that collects parse events in an iterator. + + The collected events are the same as for iterparse(), but the + parser itself is non-blocking in the sense that it receives + data chunks incrementally through its .feed() method, instead + of reading them directly from a file(-like) object all by itself. + + By default, it collects Element end events. To change that, + pass any subset of the available events into the ``events`` + argument: ``'start'``, ``'end'``, ``'start-ns'``, + ``'end-ns'``, ``'comment'``, ``'pi'``. + + To support loading external dependencies relative to the input + source, you can pass the ``base_url``. + """ + def __init__(self, events=None, *, tag=None, base_url=None, **kwargs): + HTMLParser.__init__(self, **kwargs) + if events is None: + events = ('end',) + self._setBaseURL(base_url) + self._collectEvents(events, tag) + + def read_events(self): + return (<_SaxParserContext?>self._getPushParserContext()).events_iterator + + +############################################################ +## helper functions for document creation +############################################################ + +cdef xmlDoc* _parseDoc(text, filename, _BaseParser parser) except NULL: + cdef char* c_filename + cdef char* c_text + cdef Py_ssize_t c_len + if parser is None: + parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser() + if not filename: + c_filename = NULL + else: + filename_utf = _encodeFilenameUTF8(filename) + c_filename = _cstr(filename_utf) + if isinstance(text, unicode): + if python.PyUnicode_IS_READY(text): + # PEP-393 Unicode string + c_len = python.PyUnicode_GET_LENGTH(text) * python.PyUnicode_KIND(text) + else: + # old Py_UNICODE string + c_len = python.PyUnicode_GET_DATA_SIZE(text) + if c_len > limits.INT_MAX: + return (<_BaseParser>parser)._parseDocFromFilelike( + StringIO(text), filename, None) + return (<_BaseParser>parser)._parseUnicodeDoc(text, c_filename) + else: + c_len = python.PyBytes_GET_SIZE(text) + if c_len > limits.INT_MAX: + return (<_BaseParser>parser)._parseDocFromFilelike( + BytesIO(text), filename, None) + c_text = _cstr(text) + return (<_BaseParser>parser)._parseDoc(c_text, c_len, c_filename) + +cdef xmlDoc* _parseDocFromFile(filename8, _BaseParser parser) except NULL: + if parser is None: + parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser() + return (<_BaseParser>parser)._parseDocFromFile(_cstr(filename8)) + +cdef xmlDoc* _parseDocFromFilelike(source, filename, + _BaseParser parser) except NULL: + if parser is None: + parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser() + return (<_BaseParser>parser)._parseDocFromFilelike(source, filename, None) + +cdef xmlDoc* _newXMLDoc() except NULL: + cdef xmlDoc* result + result = tree.xmlNewDoc(NULL) + if result is NULL: + raise MemoryError() + if result.encoding is NULL: + result.encoding = tree.xmlStrdup("UTF-8") + __GLOBAL_PARSER_CONTEXT.initDocDict(result) + return result + +cdef xmlDoc* _newHTMLDoc() except NULL: + cdef xmlDoc* result + result = tree.htmlNewDoc(NULL, NULL) + if result is NULL: + raise MemoryError() + __GLOBAL_PARSER_CONTEXT.initDocDict(result) + return result + +cdef xmlDoc* _copyDoc(xmlDoc* c_doc, int recursive) except NULL: + cdef xmlDoc* result + if recursive: + with nogil: + result = tree.xmlCopyDoc(c_doc, recursive) + else: + result = tree.xmlCopyDoc(c_doc, 0) + if result is NULL: + raise MemoryError() + __GLOBAL_PARSER_CONTEXT.initDocDict(result) + return result + +cdef xmlDoc* _copyDocRoot(xmlDoc* c_doc, xmlNode* c_new_root) except NULL: + "Recursively copy the document and make c_new_root the new root node." + cdef xmlDoc* result + cdef xmlNode* c_node + result = tree.xmlCopyDoc(c_doc, 0) # non recursive + __GLOBAL_PARSER_CONTEXT.initDocDict(result) + with nogil: + c_node = tree.xmlDocCopyNode(c_new_root, result, 1) # recursive + if c_node is NULL: + raise MemoryError() + tree.xmlDocSetRootElement(result, c_node) + _copyTail(c_new_root.next, c_node) + return result + +cdef xmlNode* _copyNodeToDoc(xmlNode* c_node, xmlDoc* c_doc) except NULL: + "Recursively copy the element into the document. c_doc is not modified." + cdef xmlNode* c_root + c_root = tree.xmlDocCopyNode(c_node, c_doc, 1) # recursive + if c_root is NULL: + raise MemoryError() + _copyTail(c_node.next, c_root) + return c_root + + +############################################################ +## API level helper functions for _Document creation +############################################################ + +cdef _Document _parseDocument(source, _BaseParser parser, base_url): + cdef _Document doc + source = _getFSPathOrObject(source) + if _isString(source): + # parse the file directly from the filesystem + doc = _parseDocumentFromURL(_encodeFilename(source), parser) + # fix base URL if requested + if base_url is not None: + base_url = _encodeFilenameUTF8(base_url) + if doc._c_doc.URL is not NULL: + tree.xmlFree(doc._c_doc.URL) + doc._c_doc.URL = tree.xmlStrdup(_xcstr(base_url)) + return doc + + if base_url is not None: + url = base_url + else: + url = _getFilenameForFile(source) + + if hasattr(source, 'getvalue') and hasattr(source, 'tell'): + # StringIO - reading from start? + if source.tell() == 0: + return _parseMemoryDocument(source.getvalue(), url, parser) + + # Support for file-like objects (urlgrabber.urlopen, ...) + if hasattr(source, 'read'): + return _parseFilelikeDocument(source, url, parser) + + raise TypeError, f"cannot parse from '{python._fqtypename(source).decode('UTF-8')}'" + +cdef _Document _parseDocumentFromURL(url, _BaseParser parser): + c_doc = _parseDocFromFile(url, parser) + return _documentFactory(c_doc, parser) + +cdef _Document _parseMemoryDocument(text, url, _BaseParser parser): + if isinstance(text, unicode): + if _hasEncodingDeclaration(text): + raise ValueError( + "Unicode strings with encoding declaration are not supported. " + "Please use bytes input or XML fragments without declaration.") + elif not isinstance(text, bytes): + raise ValueError, "can only parse strings" + c_doc = _parseDoc(text, url, parser) + return _documentFactory(c_doc, parser) + +cdef _Document _parseFilelikeDocument(source, url, _BaseParser parser): + c_doc = _parseDocFromFilelike(source, url, parser) + return _documentFactory(c_doc, parser) diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/public-api.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/public-api.pxi new file mode 100644 index 0000000000000000000000000000000000000000..fb8b2a2ced120b69c311270adba08924d65980a6 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/public-api.pxi @@ -0,0 +1,178 @@ +# Public C API for lxml.etree + +cdef public api _Element deepcopyNodeToDocument(_Document doc, xmlNode* c_root): + "Recursively copy the element into the document. doc is not modified." + cdef xmlNode* c_node + c_node = _copyNodeToDoc(c_root, doc._c_doc) + return _elementFactory(doc, c_node) + +cdef public api _ElementTree elementTreeFactory(_Element context_node): + _assertValidNode(context_node) + return newElementTree(context_node, _ElementTree) + +cdef public api _ElementTree newElementTree(_Element context_node, + object subclass): + if context_node is NULL or context_node is None: + raise TypeError + _assertValidNode(context_node) + return _newElementTree(context_node._doc, context_node, subclass) + +cdef public api _ElementTree adoptExternalDocument(xmlDoc* c_doc, parser, bint is_owned): + if c_doc is NULL: + raise TypeError + doc = _adoptForeignDoc(c_doc, parser, is_owned) + return _elementTreeFactory(doc, None) + +cdef public api _Element elementFactory(_Document doc, xmlNode* c_node): + if c_node is NULL or doc is None: + raise TypeError + return _elementFactory(doc, c_node) + +cdef public api _Element makeElement(tag, _Document doc, parser, + text, tail, attrib, nsmap): + return _makeElement(tag, NULL, doc, parser, text, tail, attrib, nsmap, None) + +cdef public api _Element makeSubElement(_Element parent, tag, text, tail, + attrib, nsmap): + _assertValidNode(parent) + return _makeSubElement(parent, tag, text, tail, attrib, nsmap, None) + +cdef public api void setElementClassLookupFunction( + _element_class_lookup_function function, state): + _setElementClassLookupFunction(function, state) + +cdef public api object lookupDefaultElementClass(state, doc, xmlNode* c_node): + return _lookupDefaultElementClass(state, doc, c_node) + +cdef public api object lookupNamespaceElementClass(state, doc, xmlNode* c_node): + return _find_nselement_class(state, doc, c_node) + +cdef public api object callLookupFallback(FallbackElementClassLookup lookup, + _Document doc, xmlNode* c_node): + return _callLookupFallback(lookup, doc, c_node) + +cdef public api int tagMatches(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name): + if c_node is NULL: + return -1 + return _tagMatches(c_node, c_href, c_name) + +cdef public api _Document documentOrRaise(object input): + return _documentOrRaise(input) + +cdef public api _Element rootNodeOrRaise(object input): + return _rootNodeOrRaise(input) + +cdef public api bint hasText(xmlNode* c_node): + return _hasText(c_node) + +cdef public api bint hasTail(xmlNode* c_node): + return _hasTail(c_node) + +cdef public api unicode textOf(xmlNode* c_node): + if c_node is NULL: + return None + return _collectText(c_node.children) + +cdef public api unicode tailOf(xmlNode* c_node): + if c_node is NULL: + return None + return _collectText(c_node.next) + +cdef public api int setNodeText(xmlNode* c_node, text) except -1: + if c_node is NULL: + raise ValueError + return _setNodeText(c_node, text) + +cdef public api int setTailText(xmlNode* c_node, text) except -1: + if c_node is NULL: + raise ValueError + return _setTailText(c_node, text) + +cdef public api unicode attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node): + return _attributeValue(c_element, c_attrib_node) + +cdef public api unicode attributeValueFromNsName(xmlNode* c_element, + const_xmlChar* ns, const_xmlChar* name): + return _attributeValueFromNsName(c_element, ns, name) + +cdef public api object getAttributeValue(_Element element, key, default): + _assertValidNode(element) + return _getAttributeValue(element, key, default) + +cdef public api object iterattributes(_Element element, int keysvalues): + _assertValidNode(element) + return _attributeIteratorFactory(element, keysvalues) + +cdef public api list collectAttributes(xmlNode* c_element, int keysvalues): + return _collectAttributes(c_element, keysvalues) + +cdef public api int setAttributeValue(_Element element, key, value) except -1: + _assertValidNode(element) + return _setAttributeValue(element, key, value) + +cdef public api int delAttribute(_Element element, key) except -1: + _assertValidNode(element) + return _delAttribute(element, key) + +cdef public api int delAttributeFromNsName(tree.xmlNode* c_element, + const_xmlChar* c_href, const_xmlChar* c_name): + return _delAttributeFromNsName(c_element, c_href, c_name) + +cdef public api bint hasChild(xmlNode* c_node): + return _hasChild(c_node) + +cdef public api xmlNode* findChild(xmlNode* c_node, Py_ssize_t index): + return _findChild(c_node, index) + +cdef public api xmlNode* findChildForwards(xmlNode* c_node, Py_ssize_t index): + return _findChildForwards(c_node, index) + +cdef public api xmlNode* findChildBackwards(xmlNode* c_node, Py_ssize_t index): + return _findChildBackwards(c_node, index) + +cdef public api xmlNode* nextElement(xmlNode* c_node): + return _nextElement(c_node) + +cdef public api xmlNode* previousElement(xmlNode* c_node): + return _previousElement(c_node) + +cdef public api void appendChild(_Element parent, _Element child): + # deprecated, use appendChildToElement() instead! + _appendChild(parent, child) + +cdef public api int appendChildToElement(_Element parent, _Element child) except -1: + return _appendChild(parent, child) + +cdef public api unicode pyunicode(const_xmlChar* s): + if s is NULL: + raise TypeError + return funicode(s) + +cdef public api bytes utf8(object s): + return _utf8(s) + +cdef public api tuple getNsTag(object tag): + return _getNsTag(tag) + +cdef public api tuple getNsTagWithEmptyNs(object tag): + return _getNsTagWithEmptyNs(tag) + +cdef public api unicode namespacedName(xmlNode* c_node): + return _namespacedName(c_node) + +cdef public api unicode namespacedNameFromNsName(const_xmlChar* href, const_xmlChar* name): + return _namespacedNameFromNsName(href, name) + +cdef public api void iteratorStoreNext(_ElementIterator iterator, _Element node): + # deprecated! + iterator._storeNext(node) + +cdef public api void initTagMatch(_ElementTagMatcher matcher, tag): + # deprecated! + matcher._initTagMatch(tag) + +cdef public api tree.xmlNs* findOrBuildNodeNsPrefix( + _Document doc, xmlNode* c_node, const_xmlChar* href, const_xmlChar* prefix) except NULL: + if doc is None: + raise TypeError + return doc._findOrBuildNodeNs(c_node, href, prefix, 0) diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/readonlytree.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/readonlytree.pxi new file mode 100644 index 0000000000000000000000000000000000000000..9bc9a660731b8562a3d16609bc6aceebaf5f5eff --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/readonlytree.pxi @@ -0,0 +1,565 @@ +# read-only tree implementation + +@cython.internal +cdef class _ReadOnlyProxy: + "A read-only proxy class suitable for PIs/Comments (for internal use only!)." + cdef bint _free_after_use + cdef xmlNode* _c_node + cdef _ReadOnlyProxy _source_proxy + cdef list _dependent_proxies + def __cinit__(self): + self._c_node = NULL + self._free_after_use = 0 + + cdef int _assertNode(self) except -1: + """This is our way of saying: this proxy is invalid! + """ + if not self._c_node: + raise ReferenceError("Proxy invalidated!") + return 0 + + cdef int _raise_unsupported_type(self) except -1: + raise TypeError(f"Unsupported node type: {self._c_node.type}") + + cdef void free_after_use(self) noexcept: + """Should the xmlNode* be freed when releasing the proxy? + """ + self._free_after_use = 1 + + @property + def tag(self): + """Element tag + """ + self._assertNode() + if self._c_node.type == tree.XML_ELEMENT_NODE: + return _namespacedName(self._c_node) + elif self._c_node.type == tree.XML_PI_NODE: + return ProcessingInstruction + elif self._c_node.type == tree.XML_COMMENT_NODE: + return Comment + elif self._c_node.type == tree.XML_ENTITY_REF_NODE: + return Entity + else: + self._raise_unsupported_type() + + @property + def text(self): + """Text before the first subelement. This is either a string or + the value None, if there was no text. + """ + self._assertNode() + if self._c_node.type == tree.XML_ELEMENT_NODE: + return _collectText(self._c_node.children) + elif self._c_node.type in (tree.XML_PI_NODE, + tree.XML_COMMENT_NODE): + if self._c_node.content is NULL: + return '' + else: + return funicode(self._c_node.content) + elif self._c_node.type == tree.XML_ENTITY_REF_NODE: + return f'&{funicode(self._c_node.name)};' + else: + self._raise_unsupported_type() + + @property + def tail(self): + """Text after this element's end tag, but before the next sibling + element's start tag. This is either a string or the value None, if + there was no text. + """ + self._assertNode() + return _collectText(self._c_node.next) + + @property + def sourceline(self): + """Original line number as found by the parser or None if unknown. + """ + cdef long line + self._assertNode() + line = tree.xmlGetLineNo(self._c_node) + if line > 0: + return line + else: + return None + + def __repr__(self): + self._assertNode() + if self._c_node.type == tree.XML_ELEMENT_NODE: + return "" % (self.tag, id(self)) + elif self._c_node.type == tree.XML_COMMENT_NODE: + return "" % self.text + elif self._c_node.type == tree.XML_ENTITY_NODE: + return "&%s;" % funicode(self._c_node.name) + elif self._c_node.type == tree.XML_PI_NODE: + text = self.text + if text: + return "" % (self.target, text) + else: + return "" % self.target + else: + self._raise_unsupported_type() + + def __getitem__(self, x): + """Returns the subelement at the given position or the requested + slice. + """ + cdef xmlNode* c_node = NULL + cdef Py_ssize_t step = 0, slicelength = 0 + cdef Py_ssize_t c, i + cdef _node_to_node_function next_element + cdef list result + self._assertNode() + if isinstance(x, slice): + # slicing + if _isFullSlice(x): + return _collectChildren(self) + _findChildSlice(x, self._c_node, &c_node, &step, &slicelength) + if c_node is NULL: + return [] + if step > 0: + next_element = _nextElement + else: + step = -step + next_element = _previousElement + result = [] + c = 0 + while c_node is not NULL and c < slicelength: + result.append(_newReadOnlyProxy(self._source_proxy, c_node)) + result.append(_elementFactory(self._doc, c_node)) + c = c + 1 + for i from 0 <= i < step: + c_node = next_element(c_node) + return result + else: + # indexing + c_node = _findChild(self._c_node, x) + if c_node is NULL: + raise IndexError, "list index out of range" + return _newReadOnlyProxy(self._source_proxy, c_node) + + def __len__(self): + """Returns the number of subelements. + """ + cdef Py_ssize_t c + cdef xmlNode* c_node + self._assertNode() + c = 0 + c_node = self._c_node.children + while c_node is not NULL: + if tree._isElement(c_node): + c = c + 1 + c_node = c_node.next + return c + + def __bool__(self): + cdef xmlNode* c_node + self._assertNode() + c_node = _findChildBackwards(self._c_node, 0) + return c_node != NULL + + def __deepcopy__(self, memo): + "__deepcopy__(self, memo)" + return self.__copy__() + + cpdef __copy__(self): + "__copy__(self)" + cdef xmlDoc* c_doc + cdef xmlNode* c_node + cdef _Document new_doc + if self._c_node is NULL: + return self + c_doc = _copyDocRoot(self._c_node.doc, self._c_node) # recursive + new_doc = _documentFactory(c_doc, None) + root = new_doc.getroot() + if root is not None: + return root + # Comment/PI + c_node = c_doc.children + while c_node is not NULL and c_node.type != self._c_node.type: + c_node = c_node.next + if c_node is NULL: + return None + return _elementFactory(new_doc, c_node) + + def __iter__(self): + return iter(self.getchildren()) + + def iterchildren(self, tag=None, *, reversed=False): + """iterchildren(self, tag=None, reversed=False) + + Iterate over the children of this element. + """ + children = self.getchildren() + if tag is not None and tag != '*': + children = [ el for el in children if el.tag == tag ] + if reversed: + children = children[::-1] + return iter(children) + + cpdef getchildren(self): + """Returns all subelements. The elements are returned in document + order. + """ + cdef xmlNode* c_node + cdef list result + self._assertNode() + result = [] + c_node = self._c_node.children + while c_node is not NULL: + if tree._isElement(c_node): + result.append(_newReadOnlyProxy(self._source_proxy, c_node)) + c_node = c_node.next + return result + + def getparent(self): + """Returns the parent of this element or None for the root element. + """ + cdef xmlNode* c_parent + self._assertNode() + c_parent = self._c_node.parent + if c_parent is NULL or not tree._isElement(c_parent): + return None + else: + return _newReadOnlyProxy(self._source_proxy, c_parent) + + def getnext(self): + """Returns the following sibling of this element or None. + """ + cdef xmlNode* c_node + self._assertNode() + c_node = _nextElement(self._c_node) + if c_node is not NULL: + return _newReadOnlyProxy(self._source_proxy, c_node) + return None + + def getprevious(self): + """Returns the preceding sibling of this element or None. + """ + cdef xmlNode* c_node + self._assertNode() + c_node = _previousElement(self._c_node) + if c_node is not NULL: + return _newReadOnlyProxy(self._source_proxy, c_node) + return None + + +@cython.final +@cython.internal +cdef class _ReadOnlyPIProxy(_ReadOnlyProxy): + """A read-only proxy for processing instructions (for internal use only!)""" + @property + def target(self): + self._assertNode() + return funicode(self._c_node.name) + +@cython.final +@cython.internal +cdef class _ReadOnlyEntityProxy(_ReadOnlyProxy): + """A read-only proxy for entity references (for internal use only!)""" + property name: + def __get__(self): + return funicode(self._c_node.name) + + def __set__(self, value): + value_utf = _utf8(value) + if '&' in value or ';' in value: + raise ValueError(f"Invalid entity name '{value}'") + tree.xmlNodeSetName(self._c_node, _xcstr(value_utf)) + + @property + def text(self): + return f'&{funicode(self._c_node.name)};' + + +@cython.internal +cdef class _ReadOnlyElementProxy(_ReadOnlyProxy): + """The main read-only Element proxy class (for internal use only!).""" + + @property + def attrib(self): + self._assertNode() + return dict(_collectAttributes(self._c_node, 3)) + + @property + def prefix(self): + """Namespace prefix or None. + """ + self._assertNode() + if self._c_node.ns is not NULL: + if self._c_node.ns.prefix is not NULL: + return funicode(self._c_node.ns.prefix) + return None + + @property + def nsmap(self): + """Namespace prefix->URI mapping known in the context of this + Element. This includes all namespace declarations of the + parents. + + Note that changing the returned dict has no effect on the Element. + """ + self._assertNode() + return _build_nsmap(self._c_node) + + def get(self, key, default=None): + """Gets an element attribute. + """ + self._assertNode() + return _getNodeAttributeValue(self._c_node, key, default) + + def keys(self): + """Gets a list of attribute names. The names are returned in an + arbitrary order (just like for an ordinary Python dictionary). + """ + self._assertNode() + return _collectAttributes(self._c_node, 1) + + def values(self): + """Gets element attributes, as a sequence. The attributes are returned + in an arbitrary order. + """ + self._assertNode() + return _collectAttributes(self._c_node, 2) + + def items(self): + """Gets element attributes, as a sequence. The attributes are returned + in an arbitrary order. + """ + self._assertNode() + return _collectAttributes(self._c_node, 3) + +cdef _ReadOnlyProxy _newReadOnlyProxy( + _ReadOnlyProxy source_proxy, xmlNode* c_node): + cdef _ReadOnlyProxy el + if c_node.type == tree.XML_ELEMENT_NODE: + el = _ReadOnlyElementProxy.__new__(_ReadOnlyElementProxy) + elif c_node.type == tree.XML_PI_NODE: + el = _ReadOnlyPIProxy.__new__(_ReadOnlyPIProxy) + elif c_node.type in (tree.XML_COMMENT_NODE, + tree.XML_ENTITY_REF_NODE): + el = _ReadOnlyProxy.__new__(_ReadOnlyProxy) + else: + raise TypeError(f"Unsupported element type: {c_node.type}") + el._c_node = c_node + _initReadOnlyProxy(el, source_proxy) + return el + +cdef inline _initReadOnlyProxy(_ReadOnlyProxy el, + _ReadOnlyProxy source_proxy): + if source_proxy is None: + el._source_proxy = el + el._dependent_proxies = [el] + else: + el._source_proxy = source_proxy + source_proxy._dependent_proxies.append(el) + +cdef _freeReadOnlyProxies(_ReadOnlyProxy sourceProxy): + cdef xmlNode* c_node + cdef _ReadOnlyProxy el + if sourceProxy is None: + return + if sourceProxy._dependent_proxies is None: + return + for el in sourceProxy._dependent_proxies: + c_node = el._c_node + el._c_node = NULL + if el._free_after_use: + tree.xmlFreeNode(c_node) + del sourceProxy._dependent_proxies[:] + +# opaque wrapper around non-element nodes, e.g. the document node +# +# This class does not imply any restrictions on modifiability or +# read-only status of the node, so use with caution. + +@cython.internal +cdef class _OpaqueNodeWrapper: + cdef tree.xmlNode* _c_node + def __init__(self): + raise TypeError, "This type cannot be instantiated from Python" + +@cython.final +@cython.internal +cdef class _OpaqueDocumentWrapper(_OpaqueNodeWrapper): + cdef int _assertNode(self) except -1: + """This is our way of saying: this proxy is invalid! + """ + assert self._c_node is not NULL, "Proxy invalidated!" + return 0 + + cpdef append(self, other_element): + """Append a copy of an Element to the list of children. + """ + cdef xmlNode* c_next + cdef xmlNode* c_node + self._assertNode() + c_node = _roNodeOf(other_element) + if c_node.type == tree.XML_ELEMENT_NODE: + if tree.xmlDocGetRootElement(self._c_node) is not NULL: + raise ValueError, "cannot append, document already has a root element" + elif c_node.type not in (tree.XML_PI_NODE, tree.XML_COMMENT_NODE): + raise TypeError, f"unsupported element type for top-level node: {c_node.type}" + c_node = _copyNodeToDoc(c_node, self._c_node) + c_next = c_node.next + tree.xmlAddChild(self._c_node, c_node) + _moveTail(c_next, c_node) + + def extend(self, elements): + """Append a copy of all Elements from a sequence to the list of + children. + """ + self._assertNode() + for element in elements: + self.append(element) + +cdef _OpaqueNodeWrapper _newOpaqueAppendOnlyNodeWrapper(xmlNode* c_node): + cdef _OpaqueNodeWrapper node + if c_node.type in (tree.XML_DOCUMENT_NODE, tree.XML_HTML_DOCUMENT_NODE): + node = _OpaqueDocumentWrapper.__new__(_OpaqueDocumentWrapper) + else: + node = _OpaqueNodeWrapper.__new__(_OpaqueNodeWrapper) + node._c_node = c_node + return node + +# element proxies that allow restricted modification + +@cython.internal +cdef class _ModifyContentOnlyProxy(_ReadOnlyProxy): + """A read-only proxy that allows changing the text content. + """ + property text: + def __get__(self): + self._assertNode() + if self._c_node.content is NULL: + return '' + else: + return funicode(self._c_node.content) + + def __set__(self, value): + cdef tree.xmlDict* c_dict + self._assertNode() + if value is None: + c_text = NULL + else: + value = _utf8(value) + c_text = _xcstr(value) + tree.xmlNodeSetContent(self._c_node, c_text) + +@cython.final +@cython.internal +cdef class _ModifyContentOnlyPIProxy(_ModifyContentOnlyProxy): + """A read-only proxy that allows changing the text/target content of a + processing instruction. + """ + property target: + def __get__(self): + self._assertNode() + return funicode(self._c_node.name) + + def __set__(self, value): + self._assertNode() + value = _utf8(value) + c_text = _xcstr(value) + tree.xmlNodeSetName(self._c_node, c_text) + +@cython.final +@cython.internal +cdef class _ModifyContentOnlyEntityProxy(_ModifyContentOnlyProxy): + "A read-only proxy for entity references (for internal use only!)" + property name: + def __get__(self): + return funicode(self._c_node.name) + + def __set__(self, value): + value = _utf8(value) + assert '&' not in value and ';' not in value, \ + f"Invalid entity name '{value}'" + c_text = _xcstr(value) + tree.xmlNodeSetName(self._c_node, c_text) + + +@cython.final +@cython.internal +cdef class _AppendOnlyElementProxy(_ReadOnlyElementProxy): + """A read-only element that allows adding children and changing the + text content (i.e. everything that adds to the subtree). + """ + cpdef append(self, other_element): + """Append a copy of an Element to the list of children. + """ + cdef xmlNode* c_next + cdef xmlNode* c_node + self._assertNode() + c_node = _roNodeOf(other_element) + c_node = _copyNodeToDoc(c_node, self._c_node.doc) + c_next = c_node.next + tree.xmlAddChild(self._c_node, c_node) + _moveTail(c_next, c_node) + + def extend(self, elements): + """Append a copy of all Elements from a sequence to the list of + children. + """ + self._assertNode() + for element in elements: + self.append(element) + + property text: + """Text before the first subelement. This is either a string or the + value None, if there was no text. + """ + def __get__(self): + self._assertNode() + return _collectText(self._c_node.children) + + def __set__(self, value): + self._assertNode() + if isinstance(value, QName): + value = _resolveQNameText(self, value).decode('utf8') + _setNodeText(self._c_node, value) + + +cdef _ReadOnlyProxy _newAppendOnlyProxy( + _ReadOnlyProxy source_proxy, xmlNode* c_node): + cdef _ReadOnlyProxy el + if c_node.type == tree.XML_ELEMENT_NODE: + el = _AppendOnlyElementProxy.__new__(_AppendOnlyElementProxy) + elif c_node.type == tree.XML_PI_NODE: + el = _ModifyContentOnlyPIProxy.__new__(_ModifyContentOnlyPIProxy) + elif c_node.type == tree.XML_COMMENT_NODE: + el = _ModifyContentOnlyProxy.__new__(_ModifyContentOnlyProxy) + else: + raise TypeError(f"Unsupported element type: {c_node.type}") + el._c_node = c_node + _initReadOnlyProxy(el, source_proxy) + return el + +cdef xmlNode* _roNodeOf(element) except NULL: + cdef xmlNode* c_node + if isinstance(element, _Element): + c_node = (<_Element>element)._c_node + elif isinstance(element, _ReadOnlyProxy): + c_node = (<_ReadOnlyProxy>element)._c_node + elif isinstance(element, _OpaqueNodeWrapper): + c_node = (<_OpaqueNodeWrapper>element)._c_node + else: + raise TypeError, f"invalid argument type {type(element)}" + + if c_node is NULL: + raise TypeError, "invalid element" + return c_node + +cdef xmlNode* _nonRoNodeOf(element) except NULL: + cdef xmlNode* c_node + if isinstance(element, _Element): + c_node = (<_Element>element)._c_node + elif isinstance(element, _AppendOnlyElementProxy): + c_node = (<_AppendOnlyElementProxy>element)._c_node + elif isinstance(element, _OpaqueNodeWrapper): + c_node = (<_OpaqueNodeWrapper>element)._c_node + else: + raise TypeError, f"invalid argument type {type(element)}" + + if c_node is NULL: + raise TypeError, "invalid element" + return c_node diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/relaxng.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/relaxng.pxi new file mode 100644 index 0000000000000000000000000000000000000000..35f875891f7e59a785518b8b70bd19ef3f0f6099 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/relaxng.pxi @@ -0,0 +1,165 @@ +# support for RelaxNG validation +from lxml.includes cimport relaxng + +cdef object _rnc2rng +try: + import rnc2rng as _rnc2rng +except ImportError: + _rnc2rng = None + + +cdef int _require_rnc2rng() except -1: + if _rnc2rng is None: + raise RelaxNGParseError( + 'compact syntax not supported (please install rnc2rng)') + return 0 + + +cdef class RelaxNGError(LxmlError): + """Base class for RelaxNG errors. + """ + +cdef class RelaxNGParseError(RelaxNGError): + """Error while parsing an XML document as RelaxNG. + """ + +cdef class RelaxNGValidateError(RelaxNGError): + """Error while validating an XML document with a RelaxNG schema. + """ + + +################################################################################ +# RelaxNG + +cdef class RelaxNG(_Validator): + """RelaxNG(self, etree=None, file=None) + Turn a document into a Relax NG validator. + + Either pass a schema as Element or ElementTree, or pass a file or + filename through the ``file`` keyword argument. + """ + cdef relaxng.xmlRelaxNG* _c_schema + def __cinit__(self): + self._c_schema = NULL + + def __init__(self, etree=None, *, file=None): + cdef _Document doc + cdef _Element root_node + cdef xmlDoc* fake_c_doc = NULL + cdef relaxng.xmlRelaxNGParserCtxt* parser_ctxt = NULL + _Validator.__init__(self) + if etree is not None: + doc = _documentOrRaise(etree) + root_node = _rootNodeOrRaise(etree) + fake_c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node) + parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(fake_c_doc) + elif file is not None: + if _isString(file): + if file[-4:].lower() == '.rnc': + _require_rnc2rng() + rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file))) + doc = _parseMemoryDocument(rng_data_utf8, parser=None, url=file) + parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc) + else: + doc = None + filename = _encodeFilename(file) + with self._error_log: + orig_loader = _register_document_loader() + parser_ctxt = relaxng.xmlRelaxNGNewParserCtxt(_cstr(filename)) + _reset_document_loader(orig_loader) + elif (_getFilenameForFile(file) or '')[-4:].lower() == '.rnc': + _require_rnc2rng() + rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file))) + doc = _parseMemoryDocument( + rng_data_utf8, parser=None, url=_getFilenameForFile(file)) + parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc) + else: + doc = _parseDocument(file, parser=None, base_url=None) + parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc) + else: + raise RelaxNGParseError, "No tree or file given" + + if parser_ctxt is NULL: + if fake_c_doc is not NULL: + _destroyFakeDoc(doc._c_doc, fake_c_doc) + raise RelaxNGParseError( + self._error_log._buildExceptionMessage( + "Document is not parsable as Relax NG"), + self._error_log) + + # Need a cast here because older libxml2 releases do not use 'const' in the functype. + relaxng.xmlRelaxNGSetParserStructuredErrors( + parser_ctxt, _receiveError, self._error_log) + _connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGP) + self._c_schema = relaxng.xmlRelaxNGParse(parser_ctxt) + _connectGenericErrorLog(None) + + relaxng.xmlRelaxNGFreeParserCtxt(parser_ctxt) + if self._c_schema is NULL: + if fake_c_doc is not NULL: + _destroyFakeDoc(doc._c_doc, fake_c_doc) + raise RelaxNGParseError( + self._error_log._buildExceptionMessage( + "Document is not valid Relax NG"), + self._error_log) + if fake_c_doc is not NULL: + _destroyFakeDoc(doc._c_doc, fake_c_doc) + + def __dealloc__(self): + relaxng.xmlRelaxNGFree(self._c_schema) + + def __call__(self, etree): + """__call__(self, etree) + + Validate doc using Relax NG. + + Returns true if document is valid, false if not.""" + cdef _Document doc + cdef _Element root_node + cdef xmlDoc* c_doc + cdef relaxng.xmlRelaxNGValidCtxt* valid_ctxt + cdef int ret + + assert self._c_schema is not NULL, "RelaxNG instance not initialised" + doc = _documentOrRaise(etree) + root_node = _rootNodeOrRaise(etree) + + valid_ctxt = relaxng.xmlRelaxNGNewValidCtxt(self._c_schema) + if valid_ctxt is NULL: + raise MemoryError() + + try: + self._error_log.clear() + # Need a cast here because older libxml2 releases do not use 'const' in the functype. + relaxng.xmlRelaxNGSetValidStructuredErrors( + valid_ctxt, _receiveError, self._error_log) + _connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGV) + c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node) + with nogil: + ret = relaxng.xmlRelaxNGValidateDoc(valid_ctxt, c_doc) + _destroyFakeDoc(doc._c_doc, c_doc) + finally: + _connectGenericErrorLog(None) + relaxng.xmlRelaxNGFreeValidCtxt(valid_ctxt) + + if ret == -1: + raise RelaxNGValidateError( + "Internal error in Relax NG validation", + self._error_log) + if ret == 0: + return True + else: + return False + + @classmethod + def from_rnc_string(cls, src, base_url=None): + """Parse a RelaxNG schema in compact syntax from a text string + + Requires the rnc2rng package to be installed. + + Passing the source URL or file path of the source as 'base_url' + will enable resolving resource references relative to the source. + """ + _require_rnc2rng() + rng_str = utf8(_rnc2rng.dumps(_rnc2rng.loads(src))) + return cls(_parseMemoryDocument(rng_str, parser=None, url=base_url)) diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/sax.py b/llmeval-env/lib/python3.10/site-packages/lxml/sax.py new file mode 100644 index 0000000000000000000000000000000000000000..eee44226703c6c61f45807916b0a11984a3886ff --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/sax.py @@ -0,0 +1,275 @@ +# cython: language_level=2 + +""" +SAX-based adapter to copy trees from/to the Python standard library. + +Use the `ElementTreeContentHandler` class to build an ElementTree from +SAX events. + +Use the `ElementTreeProducer` class or the `saxify()` function to fire +the SAX events of an ElementTree against a SAX ContentHandler. + +See https://lxml.de/sax.html +""" + + +from xml.sax.handler import ContentHandler +from lxml import etree +from lxml.etree import ElementTree, SubElement +from lxml.etree import Comment, ProcessingInstruction + + +class SaxError(etree.LxmlError): + """General SAX error. + """ + + +def _getNsTag(tag): + if tag[0] == '{': + return tuple(tag[1:].split('}', 1)) + else: + return None, tag + + +class ElementTreeContentHandler(ContentHandler): + """Build an lxml ElementTree from SAX events. + """ + def __init__(self, makeelement=None): + ContentHandler.__init__(self) + self._root = None + self._root_siblings = [] + self._element_stack = [] + self._default_ns = None + self._ns_mapping = { None : [None] } + self._new_mappings = {} + if makeelement is None: + makeelement = etree.Element + self._makeelement = makeelement + + def _get_etree(self): + "Contains the generated ElementTree after parsing is finished." + return ElementTree(self._root) + + etree = property(_get_etree, doc=_get_etree.__doc__) + + def setDocumentLocator(self, locator): + pass + + def startDocument(self): + pass + + def endDocument(self): + pass + + def startPrefixMapping(self, prefix, uri): + self._new_mappings[prefix] = uri + try: + self._ns_mapping[prefix].append(uri) + except KeyError: + self._ns_mapping[prefix] = [uri] + if prefix is None: + self._default_ns = uri + + def endPrefixMapping(self, prefix): + ns_uri_list = self._ns_mapping[prefix] + ns_uri_list.pop() + if prefix is None: + self._default_ns = ns_uri_list[-1] + + def _buildTag(self, ns_name_tuple): + ns_uri, local_name = ns_name_tuple + if ns_uri: + el_tag = "{%s}%s" % ns_name_tuple + elif self._default_ns: + el_tag = "{%s}%s" % (self._default_ns, local_name) + else: + el_tag = local_name + return el_tag + + def startElementNS(self, ns_name, qname, attributes=None): + el_name = self._buildTag(ns_name) + if attributes: + attrs = {} + try: + iter_attributes = attributes.iteritems() + except AttributeError: + iter_attributes = attributes.items() + + for name_tuple, value in iter_attributes: + if name_tuple[0]: + attr_name = "{%s}%s" % name_tuple + else: + attr_name = name_tuple[1] + attrs[attr_name] = value + else: + attrs = None + + element_stack = self._element_stack + if self._root is None: + element = self._root = \ + self._makeelement(el_name, attrs, self._new_mappings) + if self._root_siblings and hasattr(element, 'addprevious'): + for sibling in self._root_siblings: + element.addprevious(sibling) + del self._root_siblings[:] + else: + element = SubElement(element_stack[-1], el_name, + attrs, self._new_mappings) + element_stack.append(element) + + self._new_mappings.clear() + + def processingInstruction(self, target, data): + pi = ProcessingInstruction(target, data) + if self._root is None: + self._root_siblings.append(pi) + else: + self._element_stack[-1].append(pi) + + def endElementNS(self, ns_name, qname): + element = self._element_stack.pop() + el_tag = self._buildTag(ns_name) + if el_tag != element.tag: + raise SaxError("Unexpected element closed: " + el_tag) + + def startElement(self, name, attributes=None): + if attributes: + attributes = {(None, k): v for k, v in attributes.items()} + self.startElementNS((None, name), name, attributes) + + def endElement(self, name): + self.endElementNS((None, name), name) + + def characters(self, data): + last_element = self._element_stack[-1] + try: + # if there already is a child element, we must append to its tail + last_element = last_element[-1] + last_element.tail = (last_element.tail or '') + data + except IndexError: + # otherwise: append to the text + last_element.text = (last_element.text or '') + data + + ignorableWhitespace = characters + + +class ElementTreeProducer: + """Produces SAX events for an element and children. + """ + def __init__(self, element_or_tree, content_handler): + try: + element = element_or_tree.getroot() + except AttributeError: + element = element_or_tree + self._element = element + self._content_handler = content_handler + from xml.sax.xmlreader import AttributesNSImpl as attr_class + self._attr_class = attr_class + self._empty_attributes = attr_class({}, {}) + + def saxify(self): + self._content_handler.startDocument() + + element = self._element + if hasattr(element, 'getprevious'): + siblings = [] + sibling = element.getprevious() + while getattr(sibling, 'tag', None) is ProcessingInstruction: + siblings.append(sibling) + sibling = sibling.getprevious() + for sibling in siblings[::-1]: + self._recursive_saxify(sibling, {}) + + self._recursive_saxify(element, {}) + + if hasattr(element, 'getnext'): + sibling = element.getnext() + while getattr(sibling, 'tag', None) is ProcessingInstruction: + self._recursive_saxify(sibling, {}) + sibling = sibling.getnext() + + self._content_handler.endDocument() + + def _recursive_saxify(self, element, parent_nsmap): + content_handler = self._content_handler + tag = element.tag + if tag is Comment or tag is ProcessingInstruction: + if tag is ProcessingInstruction: + content_handler.processingInstruction( + element.target, element.text) + tail = element.tail + if tail: + content_handler.characters(tail) + return + + element_nsmap = element.nsmap + new_prefixes = [] + if element_nsmap != parent_nsmap: + # There have been updates to the namespace + for prefix, ns_uri in element_nsmap.items(): + if parent_nsmap.get(prefix) != ns_uri: + new_prefixes.append( (prefix, ns_uri) ) + + attribs = element.items() + if attribs: + attr_values = {} + attr_qnames = {} + for attr_ns_name, value in attribs: + attr_ns_tuple = _getNsTag(attr_ns_name) + attr_values[attr_ns_tuple] = value + attr_qnames[attr_ns_tuple] = self._build_qname( + attr_ns_tuple[0], attr_ns_tuple[1], element_nsmap, + preferred_prefix=None, is_attribute=True) + sax_attributes = self._attr_class(attr_values, attr_qnames) + else: + sax_attributes = self._empty_attributes + + ns_uri, local_name = _getNsTag(tag) + qname = self._build_qname( + ns_uri, local_name, element_nsmap, element.prefix, is_attribute=False) + + for prefix, uri in new_prefixes: + content_handler.startPrefixMapping(prefix, uri) + content_handler.startElementNS( + (ns_uri, local_name), qname, sax_attributes) + text = element.text + if text: + content_handler.characters(text) + for child in element: + self._recursive_saxify(child, element_nsmap) + content_handler.endElementNS((ns_uri, local_name), qname) + for prefix, uri in new_prefixes: + content_handler.endPrefixMapping(prefix) + tail = element.tail + if tail: + content_handler.characters(tail) + + def _build_qname(self, ns_uri, local_name, nsmap, preferred_prefix, is_attribute): + if ns_uri is None: + return local_name + + if not is_attribute and nsmap.get(preferred_prefix) == ns_uri: + prefix = preferred_prefix + else: + # Pick the first matching prefix, in alphabetical order. + candidates = [ + pfx for (pfx, uri) in nsmap.items() + if pfx is not None and uri == ns_uri + ] + prefix = ( + candidates[0] if len(candidates) == 1 + else min(candidates) if candidates + else None + ) + + if prefix is None: + # Default namespace + return local_name + return prefix + ':' + local_name + + +def saxify(element_or_tree, content_handler): + """One-shot helper to generate SAX events from an XML tree and fire + them against a SAX ContentHandler. + """ + return ElementTreeProducer(element_or_tree, content_handler).saxify() diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/schematron.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/schematron.pxi new file mode 100644 index 0000000000000000000000000000000000000000..ea0881fdf846b0c05f974292b30a4f7307e6848b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/schematron.pxi @@ -0,0 +1,168 @@ +# support for Schematron validation +from lxml.includes cimport schematron + + +cdef class SchematronError(LxmlError): + """Base class of all Schematron errors. + """ + +cdef class SchematronParseError(SchematronError): + """Error while parsing an XML document as Schematron schema. + """ + +cdef class SchematronValidateError(SchematronError): + """Error while validating an XML document with a Schematron schema. + """ + + +################################################################################ +# Schematron + +cdef class Schematron(_Validator): + """Schematron(self, etree=None, file=None) + A Schematron validator. + + Pass a root Element or an ElementTree to turn it into a validator. + Alternatively, pass a filename as keyword argument 'file' to parse from + the file system. + + Schematron is a less well known, but very powerful schema language. The main + idea is to use the capabilities of XPath to put restrictions on the structure + and the content of XML documents. Here is a simple example:: + + >>> schematron = Schematron(XML(''' + ... + ... + ... + ... Attribute + ... is forbidden + ... + ... + ... + ... + ... ''')) + + >>> xml = XML(''' + ... + ... + ... + ... + ... ''') + + >>> schematron.validate(xml) + 0 + + >>> xml = XML(''' + ... + ... + ... + ... + ... ''') + + >>> schematron.validate(xml) + 1 + + Schematron was added to libxml2 in version 2.6.21. Before version 2.6.32, + however, Schematron lacked support for error reporting other than to stderr. + This version is therefore required to retrieve validation warnings and + errors in lxml. + """ + cdef schematron.xmlSchematron* _c_schema + cdef xmlDoc* _c_schema_doc + def __cinit__(self): + self._c_schema = NULL + self._c_schema_doc = NULL + + def __init__(self, etree=None, *, file=None): + cdef _Document doc + cdef _Element root_node + cdef xmlNode* c_node + cdef char* c_href + cdef schematron.xmlSchematronParserCtxt* parser_ctxt = NULL + _Validator.__init__(self) + if not config.ENABLE_SCHEMATRON: + raise SchematronError, \ + "lxml.etree was compiled without Schematron support." + if etree is not None: + doc = _documentOrRaise(etree) + root_node = _rootNodeOrRaise(etree) + self._c_schema_doc = _copyDocRoot(doc._c_doc, root_node._c_node) + parser_ctxt = schematron.xmlSchematronNewDocParserCtxt(self._c_schema_doc) + elif file is not None: + filename = _getFilenameForFile(file) + if filename is None: + # XXX assume a string object + filename = file + filename = _encodeFilename(filename) + with self._error_log: + orig_loader = _register_document_loader() + parser_ctxt = schematron.xmlSchematronNewParserCtxt(_cstr(filename)) + _reset_document_loader(orig_loader) + else: + raise SchematronParseError, "No tree or file given" + + if parser_ctxt is NULL: + if self._c_schema_doc is not NULL: + tree.xmlFreeDoc(self._c_schema_doc) + self._c_schema_doc = NULL + raise MemoryError() + + try: + with self._error_log: + orig_loader = _register_document_loader() + self._c_schema = schematron.xmlSchematronParse(parser_ctxt) + _reset_document_loader(orig_loader) + finally: + schematron.xmlSchematronFreeParserCtxt(parser_ctxt) + + if self._c_schema is NULL: + raise SchematronParseError( + "Document is not a valid Schematron schema", + self._error_log) + + def __dealloc__(self): + schematron.xmlSchematronFree(self._c_schema) + if self._c_schema_doc is not NULL: + tree.xmlFreeDoc(self._c_schema_doc) + + def __call__(self, etree): + """__call__(self, etree) + + Validate doc using Schematron. + + Returns true if document is valid, false if not.""" + cdef _Document doc + cdef _Element root_node + cdef xmlDoc* c_doc + cdef schematron.xmlSchematronValidCtxt* valid_ctxt + cdef int ret + + assert self._c_schema is not NULL, "Schematron instance not initialised" + doc = _documentOrRaise(etree) + root_node = _rootNodeOrRaise(etree) + + valid_ctxt = schematron.xmlSchematronNewValidCtxt( + self._c_schema, schematron.XML_SCHEMATRON_OUT_ERROR) + if valid_ctxt is NULL: + raise MemoryError() + + try: + self._error_log.clear() + # Need a cast here because older libxml2 releases do not use 'const' in the functype. + schematron.xmlSchematronSetValidStructuredErrors( + valid_ctxt, _receiveError, self._error_log) + c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node) + with nogil: + ret = schematron.xmlSchematronValidateDoc(valid_ctxt, c_doc) + _destroyFakeDoc(doc._c_doc, c_doc) + finally: + schematron.xmlSchematronFreeValidCtxt(valid_ctxt) + + if ret == -1: + raise SchematronValidateError( + "Internal error in Schematron validation", + self._error_log) + if ret == 0: + return True + else: + return False diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/xinclude.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/xinclude.pxi new file mode 100644 index 0000000000000000000000000000000000000000..5c9ac45096efb2250e268dd2eed9ade07c2ca998 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/xinclude.pxi @@ -0,0 +1,67 @@ +# XInclude processing + +from lxml.includes cimport xinclude + + +cdef class XIncludeError(LxmlError): + """Error during XInclude processing. + """ + + +cdef class XInclude: + """XInclude(self) + XInclude processor. + + Create an instance and call it on an Element to run XInclude + processing. + """ + cdef _ErrorLog _error_log + def __init__(self): + self._error_log = _ErrorLog() + + @property + def error_log(self): + assert self._error_log is not None, "XInclude instance not initialised" + return self._error_log.copy() + + def __call__(self, _Element node not None): + "__call__(self, node)" + # We cannot pass the XML_PARSE_NOXINCNODE option as this would free + # the XInclude nodes - there may still be Python references to them! + # Therefore, we allow XInclude nodes to be converted to + # XML_XINCLUDE_START nodes. XML_XINCLUDE_END nodes are added as + # siblings. Tree traversal will simply ignore them as they are not + # typed as elements. The included fragment is added between the two, + # i.e. as a sibling, which does not conflict with traversal. + cdef int result + _assertValidNode(node) + assert self._error_log is not None, "XInclude processor not initialised" + if node._doc._parser is not None: + parse_options = node._doc._parser._parse_options + context = node._doc._parser._getParserContext() + c_context = context + else: + parse_options = 0 + context = None + c_context = NULL + + self._error_log.connect() + if tree.LIBXML_VERSION < 20704 or not c_context: + __GLOBAL_PARSER_CONTEXT.pushImpliedContext(context) + with nogil: + orig_loader = _register_document_loader() + if c_context: + result = xinclude.xmlXIncludeProcessTreeFlagsData( + node._c_node, parse_options, c_context) + else: + result = xinclude.xmlXIncludeProcessTree(node._c_node) + _reset_document_loader(orig_loader) + if tree.LIBXML_VERSION < 20704 or not c_context: + __GLOBAL_PARSER_CONTEXT.popImpliedContext() + self._error_log.disconnect() + + if result == -1: + raise XIncludeError( + self._error_log._buildExceptionMessage( + "XInclude processing failed"), + self._error_log) diff --git a/llmeval-env/lib/python3.10/site-packages/lxml/xmlerror.pxi b/llmeval-env/lib/python3.10/site-packages/lxml/xmlerror.pxi new file mode 100644 index 0000000000000000000000000000000000000000..79442a8b40deb52d60cdeb0c168ee17809e239f0 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/lxml/xmlerror.pxi @@ -0,0 +1,1654 @@ +# DEBUG and error logging + +from lxml.includes cimport xmlerror +from lxml cimport cvarargs + +DEF GLOBAL_ERROR_LOG = "_GlobalErrorLog" +DEF XSLT_ERROR_LOG = "_XSLTErrorLog" + +# module level API functions + +def clear_error_log(): + """clear_error_log() + + Clear the global error log. Note that this log is already bound to a + fixed size. + + Note: since lxml 2.2, the global error log is local to a thread + and this function will only clear the global error log of the + current thread. + """ + _getThreadErrorLog(GLOBAL_ERROR_LOG).clear() + + +# setup for global log: + +cdef void _initThreadLogging() noexcept: + # Disable generic error lines from libxml2. + _connectGenericErrorLog(None) + + # Divert XSLT error messages to the global XSLT error log instead of stderr. + xslt.xsltSetGenericErrorFunc(NULL, _receiveXSLTError) + + +# Logging classes + +@cython.final +@cython.freelist(16) +cdef class _LogEntry: + """A log message entry from an error log. + + Attributes: + + - message: the message text + - domain: the domain ID (see lxml.etree.ErrorDomains) + - type: the message type ID (see lxml.etree.ErrorTypes) + - level: the log level ID (see lxml.etree.ErrorLevels) + - line: the line at which the message originated (if applicable) + - column: the character column at which the message originated (if applicable) + - filename: the name of the file in which the message originated (if applicable) + - path: the location in which the error was found (if available) + """ + cdef readonly int domain + cdef readonly int type + cdef readonly int level + cdef readonly long line + cdef readonly int column + cdef basestring _message + cdef basestring _filename + cdef char* _c_message + cdef xmlChar* _c_filename + cdef xmlChar* _c_path + + def __dealloc__(self): + tree.xmlFree(self._c_message) + tree.xmlFree(self._c_filename) + tree.xmlFree(self._c_path) + + @cython.final + cdef int _setError(self, const xmlerror.xmlError* error) except -1: + self.domain = error.domain + self.type = error.code + self.level = error.level + self.line = error.line + self.column = error.int2 + self._c_message = NULL + self._c_filename = NULL + self._c_path = NULL + if (error.message is NULL or + error.message[0] == b'\0' or + error.message[0] == b'\n' and error.message[1] == b'\0'): + self._message = "unknown error" + else: + self._message = None + self._c_message = tree.xmlStrdup( + error.message) + if not self._c_message: + raise MemoryError() + if error.file is NULL: + self._filename = '' + else: + self._filename = None + self._c_filename = tree.xmlStrdup( error.file) + if not self._c_filename: + raise MemoryError() + if error.node is not NULL: + self._c_path = tree.xmlGetNodePath( error.node) + c_line = tree.xmlGetLineNo( error.node) + if c_line > limits.INT_MAX: + self.line = c_line + + @cython.final + cdef _setGeneric(self, int domain, int type, int level, long line, + message, filename): + self.domain = domain + self.type = type + self.level = level + self.line = line + self.column = 0 + self._message = message + self._filename = filename + self._c_path = NULL + + def __repr__(self): + return "%s:%d:%d:%s:%s:%s: %s" % ( + self.filename, self.line, self.column, self.level_name, + self.domain_name, self.type_name, self.message) + + @property + def domain_name(self): + """The name of the error domain. See lxml.etree.ErrorDomains + """ + return ErrorDomains._getName(self.domain, "unknown") + + @property + def type_name(self): + """The name of the error type. See lxml.etree.ErrorTypes + """ + if self.domain == ErrorDomains.RELAXNGV: + getName = RelaxNGErrorTypes._getName + else: + getName = ErrorTypes._getName + return getName(self.type, "unknown") + + @property + def level_name(self): + """The name of the error level. See lxml.etree.ErrorLevels + """ + return ErrorLevels._getName(self.level, "unknown") + + @property + def message(self): + """The log message string. + """ + cdef size_t size + if self._message is not None: + return self._message + if self._c_message is NULL: + return None + size = cstring_h.strlen(self._c_message) + if size > 0 and self._c_message[size-1] == b'\n': + size -= 1 # strip EOL + # cannot use funicode() here because the message may contain + # byte encoded file paths etc. + try: + self._message = self._c_message[:size].decode('utf8') + except UnicodeDecodeError: + try: + self._message = self._c_message[:size].decode( + 'ascii', 'backslashreplace') + except UnicodeDecodeError: + self._message = '' + if self._c_message: + # clean up early + tree.xmlFree(self._c_message) + self._c_message = NULL + return self._message + + @property + def filename(self): + """The file path where the report originated, if any. + """ + if self._filename is None: + if self._c_filename is not NULL: + self._filename = _decodeFilename(self._c_filename) + # clean up early + tree.xmlFree(self._c_filename) + self._c_filename = NULL + return self._filename + + @property + def path(self): + """The XPath for the node where the error was detected. + """ + return funicode(self._c_path) if self._c_path is not NULL else None + + +cdef class _BaseErrorLog: + cdef _LogEntry _first_error + cdef readonly object last_error + def __init__(self, first_error, last_error): + self._first_error = first_error + self.last_error = last_error + + cpdef copy(self): + return _BaseErrorLog(self._first_error, self.last_error) + + def __repr__(self): + return '' + + cpdef receive(self, _LogEntry entry): + pass + + @cython.final + cdef int _receive(self, const xmlerror.xmlError* error) except -1: + cdef bint is_error + cdef _LogEntry entry + cdef _BaseErrorLog global_log + entry = _LogEntry.__new__(_LogEntry) + entry._setError(error) + is_error = error.level == xmlerror.XML_ERR_ERROR or \ + error.level == xmlerror.XML_ERR_FATAL + global_log = _getThreadErrorLog(GLOBAL_ERROR_LOG) + if global_log is not self: + global_log.receive(entry) + if is_error: + global_log.last_error = entry + self.receive(entry) + if is_error: + self.last_error = entry + + @cython.final + cdef int _receiveGeneric(self, int domain, int type, int level, long line, + message, filename) except -1: + cdef bint is_error + cdef _LogEntry entry + cdef _BaseErrorLog global_log + entry = _LogEntry.__new__(_LogEntry) + entry._setGeneric(domain, type, level, line, message, filename) + is_error = level == xmlerror.XML_ERR_ERROR or \ + level == xmlerror.XML_ERR_FATAL + global_log = _getThreadErrorLog(GLOBAL_ERROR_LOG) + if global_log is not self: + global_log.receive(entry) + if is_error: + global_log.last_error = entry + self.receive(entry) + if is_error: + self.last_error = entry + + @cython.final + cdef _buildParseException(self, exctype, default_message): + code = xmlerror.XML_ERR_INTERNAL_ERROR + if self._first_error is None: + return exctype(default_message, code, 0, 0) + message = self._first_error.message + if message: + code = self._first_error.type + else: + message = default_message + line = self._first_error.line + column = self._first_error.column + filename = self._first_error.filename + if line > 0: + if column > 0: + message = f"{message}, line {line}, column {column}" + else: + message = f"{message}, line {line}" + return exctype(message, code, line, column, filename) + + @cython.final + cdef _buildExceptionMessage(self, default_message): + if self._first_error is None: + return default_message + if self._first_error.message: + message = self._first_error.message + elif default_message is None: + return None + else: + message = default_message + if self._first_error.line > 0: + if self._first_error.column > 0: + message = f"{message}, line {self._first_error.line}, column {self._first_error.column}" + else: + message = f"{message}, line {self._first_error.line}" + return message + +cdef class _ListErrorLog(_BaseErrorLog): + "Immutable base version of a list based error log." + cdef list _entries + cdef int _offset + def __init__(self, entries, first_error, last_error): + if entries: + if first_error is None: + first_error = entries[0] + if last_error is None: + last_error = entries[-1] + _BaseErrorLog.__init__(self, first_error, last_error) + self._entries = entries + + cpdef copy(self): + """Creates a shallow copy of this error log. Reuses the list of + entries. + """ + cdef _ListErrorLog log = _ListErrorLog( + self._entries, self._first_error, self.last_error) + log._offset = self._offset + return log + + def __iter__(self): + entries = self._entries + if self._offset: + entries = islice(entries, self._offset) + return iter(entries) + + def __repr__(self): + return '\n'.join([repr(entry) for entry in self]) + + def __getitem__(self, index): + if self._offset: + index += self._offset + return self._entries[index] + + def __len__(self): + return len(self._entries) - self._offset + + def __contains__(self, error_type): + cdef Py_ssize_t i + for i, entry in enumerate(self._entries): + if i < self._offset: + continue + if entry.type == error_type: + return True + return False + + def __bool__(self): + return len(self._entries) > self._offset + + def filter_domains(self, domains): + """Filter the errors by the given domains and return a new error log + containing the matches. + """ + cdef _LogEntry entry + if isinstance(domains, int): + domains = (domains,) + filtered = [entry for entry in self if entry.domain in domains] + return _ListErrorLog(filtered, None, None) + + def filter_types(self, types): + """filter_types(self, types) + + Filter the errors by the given types and return a new error + log containing the matches. + """ + cdef _LogEntry entry + if isinstance(types, int): + types = (types,) + filtered = [entry for entry in self if entry.type in types] + return _ListErrorLog(filtered, None, None) + + def filter_levels(self, levels): + """filter_levels(self, levels) + + Filter the errors by the given error levels and return a new + error log containing the matches. + """ + cdef _LogEntry entry + if isinstance(levels, int): + levels = (levels,) + filtered = [entry for entry in self if entry.level in levels] + return _ListErrorLog(filtered, None, None) + + def filter_from_level(self, level): + """filter_from_level(self, level) + + Return a log with all messages of the requested level of worse. + """ + cdef _LogEntry entry + filtered = [entry for entry in self if entry.level >= level] + return _ListErrorLog(filtered, None, None) + + def filter_from_fatals(self): + """filter_from_fatals(self) + + Convenience method to get all fatal error messages. + """ + return self.filter_from_level(ErrorLevels.FATAL) + + def filter_from_errors(self): + """filter_from_errors(self) + + Convenience method to get all error messages or worse. + """ + return self.filter_from_level(ErrorLevels.ERROR) + + def filter_from_warnings(self): + """filter_from_warnings(self) + + Convenience method to get all warnings or worse. + """ + return self.filter_from_level(ErrorLevels.WARNING) + + +@cython.final +@cython.internal +cdef class _ErrorLogContext: + """ + Error log context for the 'with' statement. + Stores a reference to the current callbacks to allow for + recursively stacked log contexts. + """ + cdef xmlerror.xmlStructuredErrorFunc old_error_func + cdef void* old_error_context + cdef xmlerror.xmlGenericErrorFunc old_xslt_error_func + cdef void* old_xslt_error_context + cdef _BaseErrorLog old_xslt_error_log + + cdef int push_error_log(self, _BaseErrorLog log) except -1: + self.old_error_func = xmlerror.xmlStructuredError + self.old_error_context = xmlerror.xmlStructuredErrorContext + xmlerror.xmlSetStructuredErrorFunc( + log, _receiveError) + + # xslt.xsltSetGenericErrorFunc() is not thread-local => keep error log in TLS + self.old_xslt_error_func = xslt.xsltGenericError + self.old_xslt_error_context = xslt.xsltGenericErrorContext + self.old_xslt_error_log = _getThreadErrorLog(XSLT_ERROR_LOG) + _setThreadErrorLog(XSLT_ERROR_LOG, log) + xslt.xsltSetGenericErrorFunc( + NULL, _receiveXSLTError) + return 0 + + cdef int pop_error_log(self) except -1: + xmlerror.xmlSetStructuredErrorFunc( + self.old_error_context, self.old_error_func) + xslt.xsltSetGenericErrorFunc( + self.old_xslt_error_context, self.old_xslt_error_func) + _setThreadErrorLog(XSLT_ERROR_LOG, self.old_xslt_error_log) + self.old_xslt_error_log= None + return 0 + + +cdef class _ErrorLog(_ListErrorLog): + cdef list _logContexts + def __cinit__(self): + self._logContexts = [] + + def __init__(self): + _ListErrorLog.__init__(self, [], None, None) + + @cython.final + cdef int __enter__(self) except -1: + return self.connect() + + def __exit__(self, *args): + # TODO: make this a cdef function when Cython supports it + self.disconnect() + + @cython.final + cdef int connect(self) except -1: + self._first_error = None + del self._entries[:] + + cdef _ErrorLogContext context = _ErrorLogContext.__new__(_ErrorLogContext) + context.push_error_log(self) + self._logContexts.append(context) + return 0 + + @cython.final + cdef int disconnect(self) except -1: + cdef _ErrorLogContext context = self._logContexts.pop() + context.pop_error_log() + return 0 + + cpdef clear(self): + self._first_error = None + self.last_error = None + self._offset = 0 + del self._entries[:] + + cpdef copy(self): + """Creates a shallow copy of this error log and the list of entries. + """ + return _ListErrorLog( + self._entries[self._offset:], + self._first_error, self.last_error) + + def __iter__(self): + return iter(self._entries[self._offset:]) + + cpdef receive(self, _LogEntry entry): + if self._first_error is None and entry.level >= xmlerror.XML_ERR_ERROR: + self._first_error = entry + self._entries.append(entry) + +cdef class _DomainErrorLog(_ErrorLog): + def __init__(self, domains): + _ErrorLog.__init__(self) + self._accepted_domains = tuple(domains) + + cpdef receive(self, _LogEntry entry): + if entry.domain in self._accepted_domains: + _ErrorLog.receive(self, entry) + +cdef class _RotatingErrorLog(_ErrorLog): + cdef int _max_len + def __init__(self, max_len): + _ErrorLog.__init__(self) + self._max_len = max_len + + cpdef receive(self, _LogEntry entry): + if self._first_error is None and entry.level >= xmlerror.XML_ERR_ERROR: + self._first_error = entry + self._entries.append(entry) + + if len(self._entries) > self._max_len: + self._offset += 1 + if self._offset > self._max_len // 3: + offset = self._offset + self._offset = 0 + del self._entries[:offset] + +cdef class PyErrorLog(_BaseErrorLog): + """PyErrorLog(self, logger_name=None, logger=None) + A global error log that connects to the Python stdlib logging package. + + The constructor accepts an optional logger name or a readily + instantiated logger instance. + + If you want to change the mapping between libxml2's ErrorLevels and Python + logging levels, you can modify the level_map dictionary from a subclass. + + The default mapping is:: + + ErrorLevels.WARNING = logging.WARNING + ErrorLevels.ERROR = logging.ERROR + ErrorLevels.FATAL = logging.CRITICAL + + You can also override the method ``receive()`` that takes a LogEntry + object and calls ``self.log(log_entry, format_string, arg1, arg2, ...)`` + with appropriate data. + """ + cdef readonly dict level_map + cdef object _map_level + cdef object _log + def __init__(self, logger_name=None, logger=None): + _BaseErrorLog.__init__(self, None, None) + import logging + self.level_map = { + ErrorLevels.WARNING : logging.WARNING, + ErrorLevels.ERROR : logging.ERROR, + ErrorLevels.FATAL : logging.CRITICAL + } + self._map_level = self.level_map.get + if logger is None: + if logger_name: + logger = logging.getLogger(logger_name) + else: + logger = logging.getLogger() + self._log = logger.log + + cpdef copy(self): + """Dummy method that returns an empty error log. + """ + return _ListErrorLog([], None, None) + + def log(self, log_entry, message, *args): + """log(self, log_entry, message, *args) + + Called by the .receive() method to log a _LogEntry instance to + the Python logging system. This handles the error level + mapping. + + In the default implementation, the ``message`` argument + receives a complete log line, and there are no further + ``args``. To change the message format, it is best to + override the .receive() method instead of this one. + """ + self._log( + self._map_level(log_entry.level, 0), + message, *args + ) + + cpdef receive(self, _LogEntry log_entry): + """receive(self, log_entry) + + Receive a _LogEntry instance from the logging system. Calls + the .log() method with appropriate parameters:: + + self.log(log_entry, repr(log_entry)) + + You can override this method to provide your own log output + format. + """ + self.log(log_entry, repr(log_entry)) + +# thread-local, global list log to collect error output messages from +# libxml2/libxslt + +cdef _BaseErrorLog __GLOBAL_ERROR_LOG = _RotatingErrorLog(__MAX_LOG_SIZE) + + +cdef _BaseErrorLog _getThreadErrorLog(name): + """Retrieve the current error log with name 'name' of this thread.""" + cdef python.PyObject* thread_dict + thread_dict = python.PyThreadState_GetDict() + if thread_dict is NULL: + return __GLOBAL_ERROR_LOG + try: + return (thread_dict)[name] + except KeyError: + log = (thread_dict)[name] = \ + _RotatingErrorLog(__MAX_LOG_SIZE) + return log + + +cdef _setThreadErrorLog(name, _BaseErrorLog log): + """Set the global error log of this thread.""" + cdef python.PyObject* thread_dict + thread_dict = python.PyThreadState_GetDict() + if thread_dict is NULL: + if name == GLOBAL_ERROR_LOG: + global __GLOBAL_ERROR_LOG + __GLOBAL_ERROR_LOG = log + else: + (thread_dict)[name] = log + + +cdef __copyGlobalErrorLog(): + "Helper function for properties in exceptions." + return _getThreadErrorLog(GLOBAL_ERROR_LOG).copy() + + +def use_global_python_log(PyErrorLog log not None): + """use_global_python_log(log) + + Replace the global error log by an etree.PyErrorLog that uses the + standard Python logging package. + + Note that this disables access to the global error log from exceptions. + Parsers, XSLT etc. will continue to provide their normal local error log. + + Note: prior to lxml 2.2, this changed the error log globally. + Since lxml 2.2, the global error log is local to a thread and this + function will only set the global error log of the current thread. + """ + _setThreadErrorLog(GLOBAL_ERROR_LOG, log) + + +# local log functions: forward error to logger object +cdef void _forwardError(void* c_log_handler, const xmlerror.xmlError* error) noexcept with gil: + cdef _BaseErrorLog log_handler + if c_log_handler is not NULL: + log_handler = <_BaseErrorLog>c_log_handler + elif error.domain == xmlerror.XML_FROM_XSLT: + log_handler = _getThreadErrorLog(XSLT_ERROR_LOG) + else: + log_handler = _getThreadErrorLog(GLOBAL_ERROR_LOG) + log_handler._receive(error) + + +cdef void _receiveError(void* c_log_handler, const xmlerror.xmlError* error) noexcept nogil: + # no Python objects here, may be called without thread context ! + if __DEBUG: + _forwardError(c_log_handler, error) + + +cdef void _receiveXSLTError(void* c_log_handler, char* msg, ...) noexcept nogil: + # no Python objects here, may be called without thread context ! + cdef cvarargs.va_list args + cvarargs.va_start(args, msg) + _receiveGenericError(c_log_handler, xmlerror.XML_FROM_XSLT, msg, args) + cvarargs.va_end(args) + +cdef void _receiveRelaxNGParseError(void* c_log_handler, char* msg, ...) noexcept nogil: + # no Python objects here, may be called without thread context ! + cdef cvarargs.va_list args + cvarargs.va_start(args, msg) + _receiveGenericError(c_log_handler, xmlerror.XML_FROM_RELAXNGP, msg, args) + cvarargs.va_end(args) + +cdef void _receiveRelaxNGValidationError(void* c_log_handler, char* msg, ...) noexcept nogil: + # no Python objects here, may be called without thread context ! + cdef cvarargs.va_list args + cvarargs.va_start(args, msg) + _receiveGenericError(c_log_handler, xmlerror.XML_FROM_RELAXNGV, msg, args) + cvarargs.va_end(args) + +# dummy function: no log output at all +cdef void _nullGenericErrorFunc(void* ctxt, char* msg, ...) noexcept nogil: + pass + + +cdef void _connectGenericErrorLog(log, int c_domain=-1) noexcept: + cdef xmlerror.xmlGenericErrorFunc error_func = NULL + c_log = log + if c_domain == xmlerror.XML_FROM_XSLT: + error_func = _receiveXSLTError + elif c_domain == xmlerror.XML_FROM_RELAXNGP: + error_func = _receiveRelaxNGParseError + elif c_domain == xmlerror.XML_FROM_RELAXNGV: + error_func = _receiveRelaxNGValidationError + + if log is None or error_func is NULL: + c_log = NULL + error_func = _nullGenericErrorFunc + xmlerror.xmlSetGenericErrorFunc(c_log, error_func) + + +cdef void _receiveGenericError(void* c_log_handler, int c_domain, + char* msg, cvarargs.va_list args) noexcept nogil: + # no Python objects here, may be called without thread context ! + cdef xmlerror.xmlError c_error + cdef char* c_text + cdef char* c_message + cdef char* c_element + cdef char* c_pos + cdef char* c_name_pos + cdef char* c_str + cdef int text_size, element_size, format_count, c_int + if not __DEBUG or msg is NULL: + return + if msg[0] in b'\n\0': + return + + c_text = c_element = c_error.file = c_error.node = NULL + c_error.line = 0 + + # parse "NAME %s" chunks from the format string + c_name_pos = c_pos = msg + format_count = 0 + while c_pos[0]: + if c_pos[0] == b'%': + c_pos += 1 + if c_pos[0] == b's': # "%s" + format_count += 1 + c_str = cvarargs.va_charptr(args) + if c_pos == msg + 1: + c_text = c_str # msg == "%s..." + elif c_name_pos[0] == b'e': + if cstring_h.strncmp(c_name_pos, 'element %s', 10) == 0: + c_element = c_str + elif c_name_pos[0] == b'f': + if cstring_h.strncmp(c_name_pos, 'file %s', 7) == 0: + if cstring_h.strncmp('string://__STRING__XSLT', + c_str, 23) == 0: + c_str = '' + c_error.file = c_str + elif c_pos[0] == b'd': # "%d" + format_count += 1 + c_int = cvarargs.va_int(args) + if cstring_h.strncmp(c_name_pos, 'line %d', 7) == 0: + c_error.line = c_int + elif c_pos[0] != b'%': # "%%" == "%" + format_count += 1 + break # unexpected format or end of string => abort + elif c_pos[0] == b' ': + if c_pos[1] != b'%': + c_name_pos = c_pos + 1 + c_pos += 1 + + c_message = NULL + if c_text is NULL: + if c_element is not NULL and format_count == 1: + # special case: a single occurrence of 'element %s' + text_size = cstring_h.strlen(msg) + element_size = cstring_h.strlen(c_element) + c_message = stdlib.malloc( + (text_size + element_size + 1) * sizeof(char)) + stdio.sprintf(c_message, msg, c_element) + c_error.message = c_message + else: + c_error.message = '' + elif c_element is NULL: + c_error.message = c_text + else: + text_size = cstring_h.strlen(c_text) + element_size = cstring_h.strlen(c_element) + c_message = stdlib.malloc( + (text_size + 12 + element_size + 1) * sizeof(char)) + if c_message is NULL: + c_error.message = c_text + else: + stdio.sprintf(c_message, "%s, element '%s'", c_text, c_element) + c_error.message = c_message + + c_error.domain = c_domain + c_error.code = xmlerror.XML_ERR_OK # what else? + c_error.level = xmlerror.XML_ERR_ERROR # what else? + c_error.int2 = 0 + + _forwardError(c_log_handler, &c_error) + + if c_message is not NULL: + stdlib.free(c_message) + +################################################################################ +## CONSTANTS FROM "xmlerror.h" (or rather libxml-xmlerror.html) +################################################################################ + +cdef __initErrorConstants(): + "Called at setup time to parse the constants and build the classes below." + global __ERROR_LEVELS, __ERROR_DOMAINS, __PARSER_ERROR_TYPES, __RELAXNG_ERROR_TYPES + const_defs = ((ErrorLevels, __ERROR_LEVELS), + (ErrorDomains, __ERROR_DOMAINS), + (ErrorTypes, __PARSER_ERROR_TYPES), + (RelaxNGErrorTypes, __RELAXNG_ERROR_TYPES)) + + for cls, constants in const_defs: + reverse_dict = {} + cls._names = reverse_dict + cls._getName = reverse_dict.get + for line in constants.splitlines(): + if not line: + continue + name, value = line.split('=') + value = int(value) + setattr(cls, name, value) + reverse_dict[value] = name + + # discard the global string references after use + __ERROR_LEVELS = __ERROR_DOMAINS = __PARSER_ERROR_TYPES = __RELAXNG_ERROR_TYPES = None + + +class ErrorLevels(object): + """Libxml2 error levels""" + +class ErrorDomains(object): + """Libxml2 error domains""" + +class ErrorTypes(object): + """Libxml2 error types""" + +class RelaxNGErrorTypes(object): + """Libxml2 RelaxNG error types""" + + +# --- BEGIN: GENERATED CONSTANTS --- + +# This section is generated by the script 'update-error-constants.py'. + +cdef object __ERROR_LEVELS = """\ +NONE=0 +WARNING=1 +ERROR=2 +FATAL=3 +""" + +cdef object __ERROR_DOMAINS = """\ +NONE=0 +PARSER=1 +TREE=2 +NAMESPACE=3 +DTD=4 +HTML=5 +MEMORY=6 +OUTPUT=7 +IO=8 +FTP=9 +HTTP=10 +XINCLUDE=11 +XPATH=12 +XPOINTER=13 +REGEXP=14 +DATATYPE=15 +SCHEMASP=16 +SCHEMASV=17 +RELAXNGP=18 +RELAXNGV=19 +CATALOG=20 +C14N=21 +XSLT=22 +VALID=23 +CHECK=24 +WRITER=25 +MODULE=26 +I18N=27 +SCHEMATRONV=28 +BUFFER=29 +URI=30 +""" + +cdef object __PARSER_ERROR_TYPES = """\ +ERR_OK=0 +ERR_INTERNAL_ERROR=1 +ERR_NO_MEMORY=2 +ERR_DOCUMENT_START=3 +ERR_DOCUMENT_EMPTY=4 +ERR_DOCUMENT_END=5 +ERR_INVALID_HEX_CHARREF=6 +ERR_INVALID_DEC_CHARREF=7 +ERR_INVALID_CHARREF=8 +ERR_INVALID_CHAR=9 +ERR_CHARREF_AT_EOF=10 +ERR_CHARREF_IN_PROLOG=11 +ERR_CHARREF_IN_EPILOG=12 +ERR_CHARREF_IN_DTD=13 +ERR_ENTITYREF_AT_EOF=14 +ERR_ENTITYREF_IN_PROLOG=15 +ERR_ENTITYREF_IN_EPILOG=16 +ERR_ENTITYREF_IN_DTD=17 +ERR_PEREF_AT_EOF=18 +ERR_PEREF_IN_PROLOG=19 +ERR_PEREF_IN_EPILOG=20 +ERR_PEREF_IN_INT_SUBSET=21 +ERR_ENTITYREF_NO_NAME=22 +ERR_ENTITYREF_SEMICOL_MISSING=23 +ERR_PEREF_NO_NAME=24 +ERR_PEREF_SEMICOL_MISSING=25 +ERR_UNDECLARED_ENTITY=26 +WAR_UNDECLARED_ENTITY=27 +ERR_UNPARSED_ENTITY=28 +ERR_ENTITY_IS_EXTERNAL=29 +ERR_ENTITY_IS_PARAMETER=30 +ERR_UNKNOWN_ENCODING=31 +ERR_UNSUPPORTED_ENCODING=32 +ERR_STRING_NOT_STARTED=33 +ERR_STRING_NOT_CLOSED=34 +ERR_NS_DECL_ERROR=35 +ERR_ENTITY_NOT_STARTED=36 +ERR_ENTITY_NOT_FINISHED=37 +ERR_LT_IN_ATTRIBUTE=38 +ERR_ATTRIBUTE_NOT_STARTED=39 +ERR_ATTRIBUTE_NOT_FINISHED=40 +ERR_ATTRIBUTE_WITHOUT_VALUE=41 +ERR_ATTRIBUTE_REDEFINED=42 +ERR_LITERAL_NOT_STARTED=43 +ERR_LITERAL_NOT_FINISHED=44 +ERR_COMMENT_NOT_FINISHED=45 +ERR_PI_NOT_STARTED=46 +ERR_PI_NOT_FINISHED=47 +ERR_NOTATION_NOT_STARTED=48 +ERR_NOTATION_NOT_FINISHED=49 +ERR_ATTLIST_NOT_STARTED=50 +ERR_ATTLIST_NOT_FINISHED=51 +ERR_MIXED_NOT_STARTED=52 +ERR_MIXED_NOT_FINISHED=53 +ERR_ELEMCONTENT_NOT_STARTED=54 +ERR_ELEMCONTENT_NOT_FINISHED=55 +ERR_XMLDECL_NOT_STARTED=56 +ERR_XMLDECL_NOT_FINISHED=57 +ERR_CONDSEC_NOT_STARTED=58 +ERR_CONDSEC_NOT_FINISHED=59 +ERR_EXT_SUBSET_NOT_FINISHED=60 +ERR_DOCTYPE_NOT_FINISHED=61 +ERR_MISPLACED_CDATA_END=62 +ERR_CDATA_NOT_FINISHED=63 +ERR_RESERVED_XML_NAME=64 +ERR_SPACE_REQUIRED=65 +ERR_SEPARATOR_REQUIRED=66 +ERR_NMTOKEN_REQUIRED=67 +ERR_NAME_REQUIRED=68 +ERR_PCDATA_REQUIRED=69 +ERR_URI_REQUIRED=70 +ERR_PUBID_REQUIRED=71 +ERR_LT_REQUIRED=72 +ERR_GT_REQUIRED=73 +ERR_LTSLASH_REQUIRED=74 +ERR_EQUAL_REQUIRED=75 +ERR_TAG_NAME_MISMATCH=76 +ERR_TAG_NOT_FINISHED=77 +ERR_STANDALONE_VALUE=78 +ERR_ENCODING_NAME=79 +ERR_HYPHEN_IN_COMMENT=80 +ERR_INVALID_ENCODING=81 +ERR_EXT_ENTITY_STANDALONE=82 +ERR_CONDSEC_INVALID=83 +ERR_VALUE_REQUIRED=84 +ERR_NOT_WELL_BALANCED=85 +ERR_EXTRA_CONTENT=86 +ERR_ENTITY_CHAR_ERROR=87 +ERR_ENTITY_PE_INTERNAL=88 +ERR_ENTITY_LOOP=89 +ERR_ENTITY_BOUNDARY=90 +ERR_INVALID_URI=91 +ERR_URI_FRAGMENT=92 +WAR_CATALOG_PI=93 +ERR_NO_DTD=94 +ERR_CONDSEC_INVALID_KEYWORD=95 +ERR_VERSION_MISSING=96 +WAR_UNKNOWN_VERSION=97 +WAR_LANG_VALUE=98 +WAR_NS_URI=99 +WAR_NS_URI_RELATIVE=100 +ERR_MISSING_ENCODING=101 +WAR_SPACE_VALUE=102 +ERR_NOT_STANDALONE=103 +ERR_ENTITY_PROCESSING=104 +ERR_NOTATION_PROCESSING=105 +WAR_NS_COLUMN=106 +WAR_ENTITY_REDEFINED=107 +ERR_UNKNOWN_VERSION=108 +ERR_VERSION_MISMATCH=109 +ERR_NAME_TOO_LONG=110 +ERR_USER_STOP=111 +ERR_COMMENT_ABRUPTLY_ENDED=112 +NS_ERR_XML_NAMESPACE=200 +NS_ERR_UNDEFINED_NAMESPACE=201 +NS_ERR_QNAME=202 +NS_ERR_ATTRIBUTE_REDEFINED=203 +NS_ERR_EMPTY=204 +NS_ERR_COLON=205 +DTD_ATTRIBUTE_DEFAULT=500 +DTD_ATTRIBUTE_REDEFINED=501 +DTD_ATTRIBUTE_VALUE=502 +DTD_CONTENT_ERROR=503 +DTD_CONTENT_MODEL=504 +DTD_CONTENT_NOT_DETERMINIST=505 +DTD_DIFFERENT_PREFIX=506 +DTD_ELEM_DEFAULT_NAMESPACE=507 +DTD_ELEM_NAMESPACE=508 +DTD_ELEM_REDEFINED=509 +DTD_EMPTY_NOTATION=510 +DTD_ENTITY_TYPE=511 +DTD_ID_FIXED=512 +DTD_ID_REDEFINED=513 +DTD_ID_SUBSET=514 +DTD_INVALID_CHILD=515 +DTD_INVALID_DEFAULT=516 +DTD_LOAD_ERROR=517 +DTD_MISSING_ATTRIBUTE=518 +DTD_MIXED_CORRUPT=519 +DTD_MULTIPLE_ID=520 +DTD_NO_DOC=521 +DTD_NO_DTD=522 +DTD_NO_ELEM_NAME=523 +DTD_NO_PREFIX=524 +DTD_NO_ROOT=525 +DTD_NOTATION_REDEFINED=526 +DTD_NOTATION_VALUE=527 +DTD_NOT_EMPTY=528 +DTD_NOT_PCDATA=529 +DTD_NOT_STANDALONE=530 +DTD_ROOT_NAME=531 +DTD_STANDALONE_WHITE_SPACE=532 +DTD_UNKNOWN_ATTRIBUTE=533 +DTD_UNKNOWN_ELEM=534 +DTD_UNKNOWN_ENTITY=535 +DTD_UNKNOWN_ID=536 +DTD_UNKNOWN_NOTATION=537 +DTD_STANDALONE_DEFAULTED=538 +DTD_XMLID_VALUE=539 +DTD_XMLID_TYPE=540 +DTD_DUP_TOKEN=541 +HTML_STRUCURE_ERROR=800 +HTML_UNKNOWN_TAG=801 +RNGP_ANYNAME_ATTR_ANCESTOR=1000 +RNGP_ATTR_CONFLICT=1001 +RNGP_ATTRIBUTE_CHILDREN=1002 +RNGP_ATTRIBUTE_CONTENT=1003 +RNGP_ATTRIBUTE_EMPTY=1004 +RNGP_ATTRIBUTE_NOOP=1005 +RNGP_CHOICE_CONTENT=1006 +RNGP_CHOICE_EMPTY=1007 +RNGP_CREATE_FAILURE=1008 +RNGP_DATA_CONTENT=1009 +RNGP_DEF_CHOICE_AND_INTERLEAVE=1010 +RNGP_DEFINE_CREATE_FAILED=1011 +RNGP_DEFINE_EMPTY=1012 +RNGP_DEFINE_MISSING=1013 +RNGP_DEFINE_NAME_MISSING=1014 +RNGP_ELEM_CONTENT_EMPTY=1015 +RNGP_ELEM_CONTENT_ERROR=1016 +RNGP_ELEMENT_EMPTY=1017 +RNGP_ELEMENT_CONTENT=1018 +RNGP_ELEMENT_NAME=1019 +RNGP_ELEMENT_NO_CONTENT=1020 +RNGP_ELEM_TEXT_CONFLICT=1021 +RNGP_EMPTY=1022 +RNGP_EMPTY_CONSTRUCT=1023 +RNGP_EMPTY_CONTENT=1024 +RNGP_EMPTY_NOT_EMPTY=1025 +RNGP_ERROR_TYPE_LIB=1026 +RNGP_EXCEPT_EMPTY=1027 +RNGP_EXCEPT_MISSING=1028 +RNGP_EXCEPT_MULTIPLE=1029 +RNGP_EXCEPT_NO_CONTENT=1030 +RNGP_EXTERNALREF_EMTPY=1031 +RNGP_EXTERNAL_REF_FAILURE=1032 +RNGP_EXTERNALREF_RECURSE=1033 +RNGP_FORBIDDEN_ATTRIBUTE=1034 +RNGP_FOREIGN_ELEMENT=1035 +RNGP_GRAMMAR_CONTENT=1036 +RNGP_GRAMMAR_EMPTY=1037 +RNGP_GRAMMAR_MISSING=1038 +RNGP_GRAMMAR_NO_START=1039 +RNGP_GROUP_ATTR_CONFLICT=1040 +RNGP_HREF_ERROR=1041 +RNGP_INCLUDE_EMPTY=1042 +RNGP_INCLUDE_FAILURE=1043 +RNGP_INCLUDE_RECURSE=1044 +RNGP_INTERLEAVE_ADD=1045 +RNGP_INTERLEAVE_CREATE_FAILED=1046 +RNGP_INTERLEAVE_EMPTY=1047 +RNGP_INTERLEAVE_NO_CONTENT=1048 +RNGP_INVALID_DEFINE_NAME=1049 +RNGP_INVALID_URI=1050 +RNGP_INVALID_VALUE=1051 +RNGP_MISSING_HREF=1052 +RNGP_NAME_MISSING=1053 +RNGP_NEED_COMBINE=1054 +RNGP_NOTALLOWED_NOT_EMPTY=1055 +RNGP_NSNAME_ATTR_ANCESTOR=1056 +RNGP_NSNAME_NO_NS=1057 +RNGP_PARAM_FORBIDDEN=1058 +RNGP_PARAM_NAME_MISSING=1059 +RNGP_PARENTREF_CREATE_FAILED=1060 +RNGP_PARENTREF_NAME_INVALID=1061 +RNGP_PARENTREF_NO_NAME=1062 +RNGP_PARENTREF_NO_PARENT=1063 +RNGP_PARENTREF_NOT_EMPTY=1064 +RNGP_PARSE_ERROR=1065 +RNGP_PAT_ANYNAME_EXCEPT_ANYNAME=1066 +RNGP_PAT_ATTR_ATTR=1067 +RNGP_PAT_ATTR_ELEM=1068 +RNGP_PAT_DATA_EXCEPT_ATTR=1069 +RNGP_PAT_DATA_EXCEPT_ELEM=1070 +RNGP_PAT_DATA_EXCEPT_EMPTY=1071 +RNGP_PAT_DATA_EXCEPT_GROUP=1072 +RNGP_PAT_DATA_EXCEPT_INTERLEAVE=1073 +RNGP_PAT_DATA_EXCEPT_LIST=1074 +RNGP_PAT_DATA_EXCEPT_ONEMORE=1075 +RNGP_PAT_DATA_EXCEPT_REF=1076 +RNGP_PAT_DATA_EXCEPT_TEXT=1077 +RNGP_PAT_LIST_ATTR=1078 +RNGP_PAT_LIST_ELEM=1079 +RNGP_PAT_LIST_INTERLEAVE=1080 +RNGP_PAT_LIST_LIST=1081 +RNGP_PAT_LIST_REF=1082 +RNGP_PAT_LIST_TEXT=1083 +RNGP_PAT_NSNAME_EXCEPT_ANYNAME=1084 +RNGP_PAT_NSNAME_EXCEPT_NSNAME=1085 +RNGP_PAT_ONEMORE_GROUP_ATTR=1086 +RNGP_PAT_ONEMORE_INTERLEAVE_ATTR=1087 +RNGP_PAT_START_ATTR=1088 +RNGP_PAT_START_DATA=1089 +RNGP_PAT_START_EMPTY=1090 +RNGP_PAT_START_GROUP=1091 +RNGP_PAT_START_INTERLEAVE=1092 +RNGP_PAT_START_LIST=1093 +RNGP_PAT_START_ONEMORE=1094 +RNGP_PAT_START_TEXT=1095 +RNGP_PAT_START_VALUE=1096 +RNGP_PREFIX_UNDEFINED=1097 +RNGP_REF_CREATE_FAILED=1098 +RNGP_REF_CYCLE=1099 +RNGP_REF_NAME_INVALID=1100 +RNGP_REF_NO_DEF=1101 +RNGP_REF_NO_NAME=1102 +RNGP_REF_NOT_EMPTY=1103 +RNGP_START_CHOICE_AND_INTERLEAVE=1104 +RNGP_START_CONTENT=1105 +RNGP_START_EMPTY=1106 +RNGP_START_MISSING=1107 +RNGP_TEXT_EXPECTED=1108 +RNGP_TEXT_HAS_CHILD=1109 +RNGP_TYPE_MISSING=1110 +RNGP_TYPE_NOT_FOUND=1111 +RNGP_TYPE_VALUE=1112 +RNGP_UNKNOWN_ATTRIBUTE=1113 +RNGP_UNKNOWN_COMBINE=1114 +RNGP_UNKNOWN_CONSTRUCT=1115 +RNGP_UNKNOWN_TYPE_LIB=1116 +RNGP_URI_FRAGMENT=1117 +RNGP_URI_NOT_ABSOLUTE=1118 +RNGP_VALUE_EMPTY=1119 +RNGP_VALUE_NO_CONTENT=1120 +RNGP_XMLNS_NAME=1121 +RNGP_XML_NS=1122 +XPATH_EXPRESSION_OK=1200 +XPATH_NUMBER_ERROR=1201 +XPATH_UNFINISHED_LITERAL_ERROR=1202 +XPATH_START_LITERAL_ERROR=1203 +XPATH_VARIABLE_REF_ERROR=1204 +XPATH_UNDEF_VARIABLE_ERROR=1205 +XPATH_INVALID_PREDICATE_ERROR=1206 +XPATH_EXPR_ERROR=1207 +XPATH_UNCLOSED_ERROR=1208 +XPATH_UNKNOWN_FUNC_ERROR=1209 +XPATH_INVALID_OPERAND=1210 +XPATH_INVALID_TYPE=1211 +XPATH_INVALID_ARITY=1212 +XPATH_INVALID_CTXT_SIZE=1213 +XPATH_INVALID_CTXT_POSITION=1214 +XPATH_MEMORY_ERROR=1215 +XPTR_SYNTAX_ERROR=1216 +XPTR_RESOURCE_ERROR=1217 +XPTR_SUB_RESOURCE_ERROR=1218 +XPATH_UNDEF_PREFIX_ERROR=1219 +XPATH_ENCODING_ERROR=1220 +XPATH_INVALID_CHAR_ERROR=1221 +TREE_INVALID_HEX=1300 +TREE_INVALID_DEC=1301 +TREE_UNTERMINATED_ENTITY=1302 +TREE_NOT_UTF8=1303 +SAVE_NOT_UTF8=1400 +SAVE_CHAR_INVALID=1401 +SAVE_NO_DOCTYPE=1402 +SAVE_UNKNOWN_ENCODING=1403 +REGEXP_COMPILE_ERROR=1450 +IO_UNKNOWN=1500 +IO_EACCES=1501 +IO_EAGAIN=1502 +IO_EBADF=1503 +IO_EBADMSG=1504 +IO_EBUSY=1505 +IO_ECANCELED=1506 +IO_ECHILD=1507 +IO_EDEADLK=1508 +IO_EDOM=1509 +IO_EEXIST=1510 +IO_EFAULT=1511 +IO_EFBIG=1512 +IO_EINPROGRESS=1513 +IO_EINTR=1514 +IO_EINVAL=1515 +IO_EIO=1516 +IO_EISDIR=1517 +IO_EMFILE=1518 +IO_EMLINK=1519 +IO_EMSGSIZE=1520 +IO_ENAMETOOLONG=1521 +IO_ENFILE=1522 +IO_ENODEV=1523 +IO_ENOENT=1524 +IO_ENOEXEC=1525 +IO_ENOLCK=1526 +IO_ENOMEM=1527 +IO_ENOSPC=1528 +IO_ENOSYS=1529 +IO_ENOTDIR=1530 +IO_ENOTEMPTY=1531 +IO_ENOTSUP=1532 +IO_ENOTTY=1533 +IO_ENXIO=1534 +IO_EPERM=1535 +IO_EPIPE=1536 +IO_ERANGE=1537 +IO_EROFS=1538 +IO_ESPIPE=1539 +IO_ESRCH=1540 +IO_ETIMEDOUT=1541 +IO_EXDEV=1542 +IO_NETWORK_ATTEMPT=1543 +IO_ENCODER=1544 +IO_FLUSH=1545 +IO_WRITE=1546 +IO_NO_INPUT=1547 +IO_BUFFER_FULL=1548 +IO_LOAD_ERROR=1549 +IO_ENOTSOCK=1550 +IO_EISCONN=1551 +IO_ECONNREFUSED=1552 +IO_ENETUNREACH=1553 +IO_EADDRINUSE=1554 +IO_EALREADY=1555 +IO_EAFNOSUPPORT=1556 +XINCLUDE_RECURSION=1600 +XINCLUDE_PARSE_VALUE=1601 +XINCLUDE_ENTITY_DEF_MISMATCH=1602 +XINCLUDE_NO_HREF=1603 +XINCLUDE_NO_FALLBACK=1604 +XINCLUDE_HREF_URI=1605 +XINCLUDE_TEXT_FRAGMENT=1606 +XINCLUDE_TEXT_DOCUMENT=1607 +XINCLUDE_INVALID_CHAR=1608 +XINCLUDE_BUILD_FAILED=1609 +XINCLUDE_UNKNOWN_ENCODING=1610 +XINCLUDE_MULTIPLE_ROOT=1611 +XINCLUDE_XPTR_FAILED=1612 +XINCLUDE_XPTR_RESULT=1613 +XINCLUDE_INCLUDE_IN_INCLUDE=1614 +XINCLUDE_FALLBACKS_IN_INCLUDE=1615 +XINCLUDE_FALLBACK_NOT_IN_INCLUDE=1616 +XINCLUDE_DEPRECATED_NS=1617 +XINCLUDE_FRAGMENT_ID=1618 +CATALOG_MISSING_ATTR=1650 +CATALOG_ENTRY_BROKEN=1651 +CATALOG_PREFER_VALUE=1652 +CATALOG_NOT_CATALOG=1653 +CATALOG_RECURSION=1654 +SCHEMAP_PREFIX_UNDEFINED=1700 +SCHEMAP_ATTRFORMDEFAULT_VALUE=1701 +SCHEMAP_ATTRGRP_NONAME_NOREF=1702 +SCHEMAP_ATTR_NONAME_NOREF=1703 +SCHEMAP_COMPLEXTYPE_NONAME_NOREF=1704 +SCHEMAP_ELEMFORMDEFAULT_VALUE=1705 +SCHEMAP_ELEM_NONAME_NOREF=1706 +SCHEMAP_EXTENSION_NO_BASE=1707 +SCHEMAP_FACET_NO_VALUE=1708 +SCHEMAP_FAILED_BUILD_IMPORT=1709 +SCHEMAP_GROUP_NONAME_NOREF=1710 +SCHEMAP_IMPORT_NAMESPACE_NOT_URI=1711 +SCHEMAP_IMPORT_REDEFINE_NSNAME=1712 +SCHEMAP_IMPORT_SCHEMA_NOT_URI=1713 +SCHEMAP_INVALID_BOOLEAN=1714 +SCHEMAP_INVALID_ENUM=1715 +SCHEMAP_INVALID_FACET=1716 +SCHEMAP_INVALID_FACET_VALUE=1717 +SCHEMAP_INVALID_MAXOCCURS=1718 +SCHEMAP_INVALID_MINOCCURS=1719 +SCHEMAP_INVALID_REF_AND_SUBTYPE=1720 +SCHEMAP_INVALID_WHITE_SPACE=1721 +SCHEMAP_NOATTR_NOREF=1722 +SCHEMAP_NOTATION_NO_NAME=1723 +SCHEMAP_NOTYPE_NOREF=1724 +SCHEMAP_REF_AND_SUBTYPE=1725 +SCHEMAP_RESTRICTION_NONAME_NOREF=1726 +SCHEMAP_SIMPLETYPE_NONAME=1727 +SCHEMAP_TYPE_AND_SUBTYPE=1728 +SCHEMAP_UNKNOWN_ALL_CHILD=1729 +SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD=1730 +SCHEMAP_UNKNOWN_ATTR_CHILD=1731 +SCHEMAP_UNKNOWN_ATTRGRP_CHILD=1732 +SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP=1733 +SCHEMAP_UNKNOWN_BASE_TYPE=1734 +SCHEMAP_UNKNOWN_CHOICE_CHILD=1735 +SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD=1736 +SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD=1737 +SCHEMAP_UNKNOWN_ELEM_CHILD=1738 +SCHEMAP_UNKNOWN_EXTENSION_CHILD=1739 +SCHEMAP_UNKNOWN_FACET_CHILD=1740 +SCHEMAP_UNKNOWN_FACET_TYPE=1741 +SCHEMAP_UNKNOWN_GROUP_CHILD=1742 +SCHEMAP_UNKNOWN_IMPORT_CHILD=1743 +SCHEMAP_UNKNOWN_LIST_CHILD=1744 +SCHEMAP_UNKNOWN_NOTATION_CHILD=1745 +SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD=1746 +SCHEMAP_UNKNOWN_REF=1747 +SCHEMAP_UNKNOWN_RESTRICTION_CHILD=1748 +SCHEMAP_UNKNOWN_SCHEMAS_CHILD=1749 +SCHEMAP_UNKNOWN_SEQUENCE_CHILD=1750 +SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD=1751 +SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD=1752 +SCHEMAP_UNKNOWN_TYPE=1753 +SCHEMAP_UNKNOWN_UNION_CHILD=1754 +SCHEMAP_ELEM_DEFAULT_FIXED=1755 +SCHEMAP_REGEXP_INVALID=1756 +SCHEMAP_FAILED_LOAD=1757 +SCHEMAP_NOTHING_TO_PARSE=1758 +SCHEMAP_NOROOT=1759 +SCHEMAP_REDEFINED_GROUP=1760 +SCHEMAP_REDEFINED_TYPE=1761 +SCHEMAP_REDEFINED_ELEMENT=1762 +SCHEMAP_REDEFINED_ATTRGROUP=1763 +SCHEMAP_REDEFINED_ATTR=1764 +SCHEMAP_REDEFINED_NOTATION=1765 +SCHEMAP_FAILED_PARSE=1766 +SCHEMAP_UNKNOWN_PREFIX=1767 +SCHEMAP_DEF_AND_PREFIX=1768 +SCHEMAP_UNKNOWN_INCLUDE_CHILD=1769 +SCHEMAP_INCLUDE_SCHEMA_NOT_URI=1770 +SCHEMAP_INCLUDE_SCHEMA_NO_URI=1771 +SCHEMAP_NOT_SCHEMA=1772 +SCHEMAP_UNKNOWN_MEMBER_TYPE=1773 +SCHEMAP_INVALID_ATTR_USE=1774 +SCHEMAP_RECURSIVE=1775 +SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE=1776 +SCHEMAP_INVALID_ATTR_COMBINATION=1777 +SCHEMAP_INVALID_ATTR_INLINE_COMBINATION=1778 +SCHEMAP_MISSING_SIMPLETYPE_CHILD=1779 +SCHEMAP_INVALID_ATTR_NAME=1780 +SCHEMAP_REF_AND_CONTENT=1781 +SCHEMAP_CT_PROPS_CORRECT_1=1782 +SCHEMAP_CT_PROPS_CORRECT_2=1783 +SCHEMAP_CT_PROPS_CORRECT_3=1784 +SCHEMAP_CT_PROPS_CORRECT_4=1785 +SCHEMAP_CT_PROPS_CORRECT_5=1786 +SCHEMAP_DERIVATION_OK_RESTRICTION_1=1787 +SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1=1788 +SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2=1789 +SCHEMAP_DERIVATION_OK_RESTRICTION_2_2=1790 +SCHEMAP_DERIVATION_OK_RESTRICTION_3=1791 +SCHEMAP_WILDCARD_INVALID_NS_MEMBER=1792 +SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE=1793 +SCHEMAP_UNION_NOT_EXPRESSIBLE=1794 +SCHEMAP_SRC_IMPORT_3_1=1795 +SCHEMAP_SRC_IMPORT_3_2=1796 +SCHEMAP_DERIVATION_OK_RESTRICTION_4_1=1797 +SCHEMAP_DERIVATION_OK_RESTRICTION_4_2=1798 +SCHEMAP_DERIVATION_OK_RESTRICTION_4_3=1799 +SCHEMAP_COS_CT_EXTENDS_1_3=1800 +SCHEMAV_NOROOT=1801 +SCHEMAV_UNDECLAREDELEM=1802 +SCHEMAV_NOTTOPLEVEL=1803 +SCHEMAV_MISSING=1804 +SCHEMAV_WRONGELEM=1805 +SCHEMAV_NOTYPE=1806 +SCHEMAV_NOROLLBACK=1807 +SCHEMAV_ISABSTRACT=1808 +SCHEMAV_NOTEMPTY=1809 +SCHEMAV_ELEMCONT=1810 +SCHEMAV_HAVEDEFAULT=1811 +SCHEMAV_NOTNILLABLE=1812 +SCHEMAV_EXTRACONTENT=1813 +SCHEMAV_INVALIDATTR=1814 +SCHEMAV_INVALIDELEM=1815 +SCHEMAV_NOTDETERMINIST=1816 +SCHEMAV_CONSTRUCT=1817 +SCHEMAV_INTERNAL=1818 +SCHEMAV_NOTSIMPLE=1819 +SCHEMAV_ATTRUNKNOWN=1820 +SCHEMAV_ATTRINVALID=1821 +SCHEMAV_VALUE=1822 +SCHEMAV_FACET=1823 +SCHEMAV_CVC_DATATYPE_VALID_1_2_1=1824 +SCHEMAV_CVC_DATATYPE_VALID_1_2_2=1825 +SCHEMAV_CVC_DATATYPE_VALID_1_2_3=1826 +SCHEMAV_CVC_TYPE_3_1_1=1827 +SCHEMAV_CVC_TYPE_3_1_2=1828 +SCHEMAV_CVC_FACET_VALID=1829 +SCHEMAV_CVC_LENGTH_VALID=1830 +SCHEMAV_CVC_MINLENGTH_VALID=1831 +SCHEMAV_CVC_MAXLENGTH_VALID=1832 +SCHEMAV_CVC_MININCLUSIVE_VALID=1833 +SCHEMAV_CVC_MAXINCLUSIVE_VALID=1834 +SCHEMAV_CVC_MINEXCLUSIVE_VALID=1835 +SCHEMAV_CVC_MAXEXCLUSIVE_VALID=1836 +SCHEMAV_CVC_TOTALDIGITS_VALID=1837 +SCHEMAV_CVC_FRACTIONDIGITS_VALID=1838 +SCHEMAV_CVC_PATTERN_VALID=1839 +SCHEMAV_CVC_ENUMERATION_VALID=1840 +SCHEMAV_CVC_COMPLEX_TYPE_2_1=1841 +SCHEMAV_CVC_COMPLEX_TYPE_2_2=1842 +SCHEMAV_CVC_COMPLEX_TYPE_2_3=1843 +SCHEMAV_CVC_COMPLEX_TYPE_2_4=1844 +SCHEMAV_CVC_ELT_1=1845 +SCHEMAV_CVC_ELT_2=1846 +SCHEMAV_CVC_ELT_3_1=1847 +SCHEMAV_CVC_ELT_3_2_1=1848 +SCHEMAV_CVC_ELT_3_2_2=1849 +SCHEMAV_CVC_ELT_4_1=1850 +SCHEMAV_CVC_ELT_4_2=1851 +SCHEMAV_CVC_ELT_4_3=1852 +SCHEMAV_CVC_ELT_5_1_1=1853 +SCHEMAV_CVC_ELT_5_1_2=1854 +SCHEMAV_CVC_ELT_5_2_1=1855 +SCHEMAV_CVC_ELT_5_2_2_1=1856 +SCHEMAV_CVC_ELT_5_2_2_2_1=1857 +SCHEMAV_CVC_ELT_5_2_2_2_2=1858 +SCHEMAV_CVC_ELT_6=1859 +SCHEMAV_CVC_ELT_7=1860 +SCHEMAV_CVC_ATTRIBUTE_1=1861 +SCHEMAV_CVC_ATTRIBUTE_2=1862 +SCHEMAV_CVC_ATTRIBUTE_3=1863 +SCHEMAV_CVC_ATTRIBUTE_4=1864 +SCHEMAV_CVC_COMPLEX_TYPE_3_1=1865 +SCHEMAV_CVC_COMPLEX_TYPE_3_2_1=1866 +SCHEMAV_CVC_COMPLEX_TYPE_3_2_2=1867 +SCHEMAV_CVC_COMPLEX_TYPE_4=1868 +SCHEMAV_CVC_COMPLEX_TYPE_5_1=1869 +SCHEMAV_CVC_COMPLEX_TYPE_5_2=1870 +SCHEMAV_ELEMENT_CONTENT=1871 +SCHEMAV_DOCUMENT_ELEMENT_MISSING=1872 +SCHEMAV_CVC_COMPLEX_TYPE_1=1873 +SCHEMAV_CVC_AU=1874 +SCHEMAV_CVC_TYPE_1=1875 +SCHEMAV_CVC_TYPE_2=1876 +SCHEMAV_CVC_IDC=1877 +SCHEMAV_CVC_WILDCARD=1878 +SCHEMAV_MISC=1879 +XPTR_UNKNOWN_SCHEME=1900 +XPTR_CHILDSEQ_START=1901 +XPTR_EVAL_FAILED=1902 +XPTR_EXTRA_OBJECTS=1903 +C14N_CREATE_CTXT=1950 +C14N_REQUIRES_UTF8=1951 +C14N_CREATE_STACK=1952 +C14N_INVALID_NODE=1953 +C14N_UNKNOW_NODE=1954 +C14N_RELATIVE_NAMESPACE=1955 +FTP_PASV_ANSWER=2000 +FTP_EPSV_ANSWER=2001 +FTP_ACCNT=2002 +FTP_URL_SYNTAX=2003 +HTTP_URL_SYNTAX=2020 +HTTP_USE_IP=2021 +HTTP_UNKNOWN_HOST=2022 +SCHEMAP_SRC_SIMPLE_TYPE_1=3000 +SCHEMAP_SRC_SIMPLE_TYPE_2=3001 +SCHEMAP_SRC_SIMPLE_TYPE_3=3002 +SCHEMAP_SRC_SIMPLE_TYPE_4=3003 +SCHEMAP_SRC_RESOLVE=3004 +SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE=3005 +SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE=3006 +SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES=3007 +SCHEMAP_ST_PROPS_CORRECT_1=3008 +SCHEMAP_ST_PROPS_CORRECT_2=3009 +SCHEMAP_ST_PROPS_CORRECT_3=3010 +SCHEMAP_COS_ST_RESTRICTS_1_1=3011 +SCHEMAP_COS_ST_RESTRICTS_1_2=3012 +SCHEMAP_COS_ST_RESTRICTS_1_3_1=3013 +SCHEMAP_COS_ST_RESTRICTS_1_3_2=3014 +SCHEMAP_COS_ST_RESTRICTS_2_1=3015 +SCHEMAP_COS_ST_RESTRICTS_2_3_1_1=3016 +SCHEMAP_COS_ST_RESTRICTS_2_3_1_2=3017 +SCHEMAP_COS_ST_RESTRICTS_2_3_2_1=3018 +SCHEMAP_COS_ST_RESTRICTS_2_3_2_2=3019 +SCHEMAP_COS_ST_RESTRICTS_2_3_2_3=3020 +SCHEMAP_COS_ST_RESTRICTS_2_3_2_4=3021 +SCHEMAP_COS_ST_RESTRICTS_2_3_2_5=3022 +SCHEMAP_COS_ST_RESTRICTS_3_1=3023 +SCHEMAP_COS_ST_RESTRICTS_3_3_1=3024 +SCHEMAP_COS_ST_RESTRICTS_3_3_1_2=3025 +SCHEMAP_COS_ST_RESTRICTS_3_3_2_2=3026 +SCHEMAP_COS_ST_RESTRICTS_3_3_2_1=3027 +SCHEMAP_COS_ST_RESTRICTS_3_3_2_3=3028 +SCHEMAP_COS_ST_RESTRICTS_3_3_2_4=3029 +SCHEMAP_COS_ST_RESTRICTS_3_3_2_5=3030 +SCHEMAP_COS_ST_DERIVED_OK_2_1=3031 +SCHEMAP_COS_ST_DERIVED_OK_2_2=3032 +SCHEMAP_S4S_ELEM_NOT_ALLOWED=3033 +SCHEMAP_S4S_ELEM_MISSING=3034 +SCHEMAP_S4S_ATTR_NOT_ALLOWED=3035 +SCHEMAP_S4S_ATTR_MISSING=3036 +SCHEMAP_S4S_ATTR_INVALID_VALUE=3037 +SCHEMAP_SRC_ELEMENT_1=3038 +SCHEMAP_SRC_ELEMENT_2_1=3039 +SCHEMAP_SRC_ELEMENT_2_2=3040 +SCHEMAP_SRC_ELEMENT_3=3041 +SCHEMAP_P_PROPS_CORRECT_1=3042 +SCHEMAP_P_PROPS_CORRECT_2_1=3043 +SCHEMAP_P_PROPS_CORRECT_2_2=3044 +SCHEMAP_E_PROPS_CORRECT_2=3045 +SCHEMAP_E_PROPS_CORRECT_3=3046 +SCHEMAP_E_PROPS_CORRECT_4=3047 +SCHEMAP_E_PROPS_CORRECT_5=3048 +SCHEMAP_E_PROPS_CORRECT_6=3049 +SCHEMAP_SRC_INCLUDE=3050 +SCHEMAP_SRC_ATTRIBUTE_1=3051 +SCHEMAP_SRC_ATTRIBUTE_2=3052 +SCHEMAP_SRC_ATTRIBUTE_3_1=3053 +SCHEMAP_SRC_ATTRIBUTE_3_2=3054 +SCHEMAP_SRC_ATTRIBUTE_4=3055 +SCHEMAP_NO_XMLNS=3056 +SCHEMAP_NO_XSI=3057 +SCHEMAP_COS_VALID_DEFAULT_1=3058 +SCHEMAP_COS_VALID_DEFAULT_2_1=3059 +SCHEMAP_COS_VALID_DEFAULT_2_2_1=3060 +SCHEMAP_COS_VALID_DEFAULT_2_2_2=3061 +SCHEMAP_CVC_SIMPLE_TYPE=3062 +SCHEMAP_COS_CT_EXTENDS_1_1=3063 +SCHEMAP_SRC_IMPORT_1_1=3064 +SCHEMAP_SRC_IMPORT_1_2=3065 +SCHEMAP_SRC_IMPORT_2=3066 +SCHEMAP_SRC_IMPORT_2_1=3067 +SCHEMAP_SRC_IMPORT_2_2=3068 +SCHEMAP_INTERNAL=3069 +SCHEMAP_NOT_DETERMINISTIC=3070 +SCHEMAP_SRC_ATTRIBUTE_GROUP_1=3071 +SCHEMAP_SRC_ATTRIBUTE_GROUP_2=3072 +SCHEMAP_SRC_ATTRIBUTE_GROUP_3=3073 +SCHEMAP_MG_PROPS_CORRECT_1=3074 +SCHEMAP_MG_PROPS_CORRECT_2=3075 +SCHEMAP_SRC_CT_1=3076 +SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3=3077 +SCHEMAP_AU_PROPS_CORRECT_2=3078 +SCHEMAP_A_PROPS_CORRECT_2=3079 +SCHEMAP_C_PROPS_CORRECT=3080 +SCHEMAP_SRC_REDEFINE=3081 +SCHEMAP_SRC_IMPORT=3082 +SCHEMAP_WARN_SKIP_SCHEMA=3083 +SCHEMAP_WARN_UNLOCATED_SCHEMA=3084 +SCHEMAP_WARN_ATTR_REDECL_PROH=3085 +SCHEMAP_WARN_ATTR_POINTLESS_PROH=3086 +SCHEMAP_AG_PROPS_CORRECT=3087 +SCHEMAP_COS_CT_EXTENDS_1_2=3088 +SCHEMAP_AU_PROPS_CORRECT=3089 +SCHEMAP_A_PROPS_CORRECT_3=3090 +SCHEMAP_COS_ALL_LIMITED=3091 +SCHEMATRONV_ASSERT=4000 +SCHEMATRONV_REPORT=4001 +MODULE_OPEN=4900 +MODULE_CLOSE=4901 +CHECK_FOUND_ELEMENT=5000 +CHECK_FOUND_ATTRIBUTE=5001 +CHECK_FOUND_TEXT=5002 +CHECK_FOUND_CDATA=5003 +CHECK_FOUND_ENTITYREF=5004 +CHECK_FOUND_ENTITY=5005 +CHECK_FOUND_PI=5006 +CHECK_FOUND_COMMENT=5007 +CHECK_FOUND_DOCTYPE=5008 +CHECK_FOUND_FRAGMENT=5009 +CHECK_FOUND_NOTATION=5010 +CHECK_UNKNOWN_NODE=5011 +CHECK_ENTITY_TYPE=5012 +CHECK_NO_PARENT=5013 +CHECK_NO_DOC=5014 +CHECK_NO_NAME=5015 +CHECK_NO_ELEM=5016 +CHECK_WRONG_DOC=5017 +CHECK_NO_PREV=5018 +CHECK_WRONG_PREV=5019 +CHECK_NO_NEXT=5020 +CHECK_WRONG_NEXT=5021 +CHECK_NOT_DTD=5022 +CHECK_NOT_ATTR=5023 +CHECK_NOT_ATTR_DECL=5024 +CHECK_NOT_ELEM_DECL=5025 +CHECK_NOT_ENTITY_DECL=5026 +CHECK_NOT_NS_DECL=5027 +CHECK_NO_HREF=5028 +CHECK_WRONG_PARENT=5029 +CHECK_NS_SCOPE=5030 +CHECK_NS_ANCESTOR=5031 +CHECK_NOT_UTF8=5032 +CHECK_NO_DICT=5033 +CHECK_NOT_NCNAME=5034 +CHECK_OUTSIDE_DICT=5035 +CHECK_WRONG_NAME=5036 +CHECK_NAME_NOT_NULL=5037 +I18N_NO_NAME=6000 +I18N_NO_HANDLER=6001 +I18N_EXCESS_HANDLER=6002 +I18N_CONV_FAILED=6003 +I18N_NO_OUTPUT=6004 +BUF_OVERFLOW=7000 +""" + +cdef object __RELAXNG_ERROR_TYPES = """\ +RELAXNG_OK=0 +RELAXNG_ERR_MEMORY=1 +RELAXNG_ERR_TYPE=2 +RELAXNG_ERR_TYPEVAL=3 +RELAXNG_ERR_DUPID=4 +RELAXNG_ERR_TYPECMP=5 +RELAXNG_ERR_NOSTATE=6 +RELAXNG_ERR_NODEFINE=7 +RELAXNG_ERR_LISTEXTRA=8 +RELAXNG_ERR_LISTEMPTY=9 +RELAXNG_ERR_INTERNODATA=10 +RELAXNG_ERR_INTERSEQ=11 +RELAXNG_ERR_INTEREXTRA=12 +RELAXNG_ERR_ELEMNAME=13 +RELAXNG_ERR_ATTRNAME=14 +RELAXNG_ERR_ELEMNONS=15 +RELAXNG_ERR_ATTRNONS=16 +RELAXNG_ERR_ELEMWRONGNS=17 +RELAXNG_ERR_ATTRWRONGNS=18 +RELAXNG_ERR_ELEMEXTRANS=19 +RELAXNG_ERR_ATTREXTRANS=20 +RELAXNG_ERR_ELEMNOTEMPTY=21 +RELAXNG_ERR_NOELEM=22 +RELAXNG_ERR_NOTELEM=23 +RELAXNG_ERR_ATTRVALID=24 +RELAXNG_ERR_CONTENTVALID=25 +RELAXNG_ERR_EXTRACONTENT=26 +RELAXNG_ERR_INVALIDATTR=27 +RELAXNG_ERR_DATAELEM=28 +RELAXNG_ERR_VALELEM=29 +RELAXNG_ERR_LISTELEM=30 +RELAXNG_ERR_DATATYPE=31 +RELAXNG_ERR_VALUE=32 +RELAXNG_ERR_LIST=33 +RELAXNG_ERR_NOGRAMMAR=34 +RELAXNG_ERR_EXTRADATA=35 +RELAXNG_ERR_LACKDATA=36 +RELAXNG_ERR_INTERNAL=37 +RELAXNG_ERR_ELEMWRONG=38 +RELAXNG_ERR_TEXTWRONG=39 +""" +# --- END: GENERATED CONSTANTS --- + +__initErrorConstants() diff --git a/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/INSTALLER b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/LICENSE b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b638bda0d3b793bf3c52b37c9ea1f5b6dc0ce98b --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/LICENSE @@ -0,0 +1,11 @@ +Copyright 2022 Rick van Hattem + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/METADATA b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fceba3792594bc05da6d653c11e89d80f4ec1d59 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/METADATA @@ -0,0 +1,255 @@ +Metadata-Version: 2.1 +Name: portalocker +Version: 2.8.2 +Summary: Wraps the portalocker recipe for easy usage +Author-email: Rick van Hattem +License: BSD-3-Clause +Project-URL: bugs, https://github.com/wolph/portalocker/issues +Project-URL: documentation, https://portalocker.readthedocs.io/en/latest/ +Project-URL: repository, https://github.com/wolph/portalocker/ +Keywords: locking,locks,with,statement,windows,linux,unix +Platform: any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Development Status :: 6 - Mature +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Natural Language :: English +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: MacOS +Classifier: Operating System :: Microsoft :: MS-DOS +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: Microsoft +Classifier: Operating System :: POSIX :: BSD :: FreeBSD +Classifier: Operating System :: POSIX :: BSD +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: POSIX :: SunOS/Solaris +Classifier: Operating System :: POSIX +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: IronPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: Implementation +Classifier: Programming Language :: Python +Classifier: Topic :: Education :: Testing +Classifier: Topic :: Office/Business +Classifier: Topic :: Other/Nonlisted Topic +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: System :: Monitoring +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: pywin32 >=226 ; platform_system == "Windows" +Provides-Extra: docs +Requires-Dist: sphinx >=1.7.1 ; extra == 'docs' +Provides-Extra: redis +Requires-Dist: redis ; extra == 'redis' +Provides-Extra: tests +Requires-Dist: pytest >=5.4.1 ; extra == 'tests' +Requires-Dist: pytest-cov >=2.8.1 ; extra == 'tests' +Requires-Dist: pytest-timeout >=2.1.0 ; extra == 'tests' +Requires-Dist: sphinx >=6.0.0 ; extra == 'tests' +Requires-Dist: pytest-mypy >=0.8.0 ; extra == 'tests' +Requires-Dist: types-redis ; extra == 'tests' +Requires-Dist: redis ; extra == 'tests' + +############################################ +portalocker - Cross-platform locking library +############################################ + +.. image:: https://github.com/WoLpH/portalocker/actions/workflows/python-package.yml/badge.svg?branch=master + :alt: Linux Test Status + :target: https://github.com/WoLpH/portalocker/actions/ + +.. image:: https://ci.appveyor.com/api/projects/status/mgqry98hgpy4prhh?svg=true + :alt: Windows Tests Status + :target: https://ci.appveyor.com/project/WoLpH/portalocker + +.. image:: https://coveralls.io/repos/WoLpH/portalocker/badge.svg?branch=master + :alt: Coverage Status + :target: https://coveralls.io/r/WoLpH/portalocker?branch=master + +Overview +-------- + +Portalocker is a library to provide an easy API to file locking. + +An important detail to note is that on Linux and Unix systems the locks are +advisory by default. By specifying the `-o mand` option to the mount command it +is possible to enable mandatory file locking on Linux. This is generally not +recommended however. For more information about the subject: + + - https://en.wikipedia.org/wiki/File_locking + - http://stackoverflow.com/questions/39292051/portalocker-does-not-seem-to-lock + - https://stackoverflow.com/questions/12062466/mandatory-file-lock-on-linux + +The module is currently maintained by Rick van Hattem . +The project resides at https://github.com/WoLpH/portalocker . Bugs and feature +requests can be submitted there. Patches are also very welcome. + +Security contact information +------------------------------------------------------------------------------ + +To report a security vulnerability, please use the +`Tidelift security contact `_. +Tidelift will coordinate the fix and disclosure. + +Redis Locks +----------- + +This library now features a lock based on Redis which allows for locks across +multiple threads, processes and even distributed locks across multiple +computers. + +It is an extremely reliable Redis lock that is based on pubsub. + +As opposed to most Redis locking systems based on key/value pairs, +this locking method is based on the pubsub system. The big advantage is +that if the connection gets killed due to network issues, crashing +processes or otherwise, it will still immediately unlock instead of +waiting for a lock timeout. + +First make sure you have everything installed correctly: + +:: + + pip install "portalocker[redis]" + +Usage is really easy: + +:: + + import portalocker + + lock = portalocker.RedisLock('some_lock_channel_name') + + with lock: + print('do something here') + +The API is essentially identical to the other ``Lock`` classes so in addition +to the ``with`` statement you can also use ``lock.acquire(...)``. + +Python 2 +-------- + +Python 2 was supported in versions before Portalocker 2.0. If you are still +using +Python 2, +you can run this to install: + +:: + + pip install "portalocker<2" + +Tips +---- + +On some networked filesystems it might be needed to force a `os.fsync()` before +closing the file so it's actually written before another client reads the file. +Effectively this comes down to: + +:: + + with portalocker.Lock('some_file', 'rb+', timeout=60) as fh: + # do what you need to do + ... + + # flush and sync to filesystem + fh.flush() + os.fsync(fh.fileno()) + +Links +----- + +* Documentation + - http://portalocker.readthedocs.org/en/latest/ +* Source + - https://github.com/WoLpH/portalocker +* Bug reports + - https://github.com/WoLpH/portalocker/issues +* Package homepage + - https://pypi.python.org/pypi/portalocker +* My blog + - http://w.wol.ph/ + +Examples +-------- + +To make sure your cache generation scripts don't race, use the `Lock` class: + +>>> import portalocker +>>> with portalocker.Lock('somefile', timeout=1) as fh: +... print('writing some stuff to my cache...', file=fh) + +To customize the opening and locking a manual approach is also possible: + +>>> import portalocker +>>> file = open('somefile', 'r+') +>>> portalocker.lock(file, portalocker.LockFlags.EXCLUSIVE) +>>> file.seek(12) +>>> file.write('foo') +>>> file.close() + +Explicitly unlocking is not needed in most cases but omitting it has been known +to cause issues: +https://github.com/AzureAD/microsoft-authentication-extensions-for-python/issues/42#issuecomment-601108266 + +If needed, it can be done through: + +>>> portalocker.unlock(file) + +Do note that your data might still be in a buffer so it is possible that your +data is not available until you `flush()` or `close()`. + +To create a cross platform bounded semaphore across multiple processes you can +use the `BoundedSemaphore` class which functions somewhat similar to +`threading.BoundedSemaphore`: + +>>> import portalocker +>>> n = 2 +>>> timeout = 0.1 + +>>> semaphore_a = portalocker.BoundedSemaphore(n, timeout=timeout) +>>> semaphore_b = portalocker.BoundedSemaphore(n, timeout=timeout) +>>> semaphore_c = portalocker.BoundedSemaphore(n, timeout=timeout) + +>>> semaphore_a.acquire() + +>>> semaphore_b.acquire() + +>>> semaphore_c.acquire() +Traceback (most recent call last): + ... +portalocker.exceptions.AlreadyLocked + + +More examples can be found in the +`tests `_. + + +Versioning +---------- + +This library follows `Semantic Versioning `_. + + +Changelog +--------- + +Every release has a ``git tag`` with a commit message for the tag +explaining what was added and/or changed. The list of tags/releases +including the commit messages can be found here: +https://github.com/WoLpH/portalocker/releases + +License +------- + +See the `LICENSE `_ file. + diff --git a/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/RECORD b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..f8d2618221f108eb549f9091942500f00e2cd14c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/RECORD @@ -0,0 +1,23 @@ +portalocker-2.8.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +portalocker-2.8.2.dist-info/LICENSE,sha256=pQVw-jsxAqQte6uwVpI4sLPArtzgBjyOTWUGDf0_cpM,1460 +portalocker-2.8.2.dist-info/METADATA,sha256=2KIoWHT2tr_abTIWy3-8rpyF1uGPtlZUWZw2yK4jxWA,8525 +portalocker-2.8.2.dist-info/RECORD,, +portalocker-2.8.2.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +portalocker-2.8.2.dist-info/top_level.txt,sha256=qfIEwW2X8cgtD0cFJIIWaR-cnKNo4ESR7Raiwxf-UNA,12 +portalocker/__about__.py,sha256=qQIzhUALgyblL5TXWsApg_XFvmUJ70dzk1odhoSjNfo,230 +portalocker/__init__.py,sha256=6z6mM1nNwPQnMvyuAUOsHdXp1KQivxsFhtf_zu5-UmQ,2087 +portalocker/__main__.py,sha256=vhMZUPO17zwNarq7h2b-ne-M4vVpYN2gdIbrHJmBS8k,2624 +portalocker/__pycache__/__about__.cpython-310.pyc,, +portalocker/__pycache__/__init__.cpython-310.pyc,, +portalocker/__pycache__/__main__.cpython-310.pyc,, +portalocker/__pycache__/constants.cpython-310.pyc,, +portalocker/__pycache__/exceptions.cpython-310.pyc,, +portalocker/__pycache__/portalocker.cpython-310.pyc,, +portalocker/__pycache__/redis.cpython-310.pyc,, +portalocker/__pycache__/utils.cpython-310.pyc,, +portalocker/constants.py,sha256=mw8YwUWn6ie91HK4pszEdWrfTU6il--QYPt4ve0rj4w,1130 +portalocker/exceptions.py,sha256=giyP3Ha8URNlsN2YezZgQ9FwtRAcFOosBWl_GH1SnOA,469 +portalocker/portalocker.py,sha256=0rc9ZsFVZ_JJdPJoiy1PhZzXd_FTUYlJqh9Xd2KouKk,4006 +portalocker/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +portalocker/redis.py,sha256=DImklGnN42uHe8GG1viLVMRjGJwydrAKb8PV9uevUrk,8338 +portalocker/utils.py,sha256=HYi0lQDlTPGVMnM21kXKmNNMbB8Q46JGglxqao0Y3IY,17489 diff --git a/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/WHEEL b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7e688737d490be3643d705bc16b5a77f7bd567b7 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/top_level.txt b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..7bbc14e6fa689626ddcf52c84dd711ef31061774 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/portalocker-2.8.2.dist-info/top_level.txt @@ -0,0 +1 @@ +portalocker diff --git a/llmeval-env/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/COPYING b/llmeval-env/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..b161c890897cc16c67281beac870f829e545f397 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/scikit_learn-1.4.2.dist-info/COPYING @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2007-2023 The scikit-learn developers. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/INSTALLER b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/METADATA b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3e4e2809775aad6f54e7c9ea2a4cb9b51fd78b27 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/METADATA @@ -0,0 +1,35 @@ +Metadata-Version: 2.1 +Name: triton +Version: 2.3.0 +Summary: A language and compiler for custom Deep Learning operations +Home-page: https://github.com/openai/triton/ +Author: Philippe Tillet +Author-email: phil@openai.com +Keywords: Compiler,Deep Learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Topic :: Software Development :: Build Tools +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Requires-Dist: filelock +Provides-Extra: build +Requires-Dist: cmake >=3.20 ; extra == 'build' +Requires-Dist: lit ; extra == 'build' +Provides-Extra: tests +Requires-Dist: autopep8 ; extra == 'tests' +Requires-Dist: flake8 ; extra == 'tests' +Requires-Dist: isort ; extra == 'tests' +Requires-Dist: numpy ; extra == 'tests' +Requires-Dist: pytest ; extra == 'tests' +Requires-Dist: scipy >=1.7.1 ; extra == 'tests' +Requires-Dist: torch ; extra == 'tests' +Provides-Extra: tutorials +Requires-Dist: matplotlib ; extra == 'tutorials' +Requires-Dist: pandas ; extra == 'tutorials' +Requires-Dist: tabulate ; extra == 'tutorials' +Requires-Dist: torch ; extra == 'tutorials' + diff --git a/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/WHEEL b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..9bb86cf30c63df9170e9af3dd246ce6f41270402 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.43.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_17_x86_64 +Tag: cp310-cp310-manylinux2014_x86_64 + diff --git a/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/top_level.txt b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..9ad6b88069afd2be5fb84ec8faf4fb4d880e1982 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/triton-2.3.0.dist-info/top_level.txt @@ -0,0 +1,13 @@ +triton +triton/_C +triton/common +triton/compiler +triton/compiler/backends +triton/language +triton/language/extra +triton/ops +triton/ops/blocksparse +triton/runtime +triton/runtime/backends +triton/third_party +triton/tools diff --git a/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/METADATA b/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c4d360b4a8bb101f56769598a05172be56fb258d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/METADATA @@ -0,0 +1,240 @@ +Metadata-Version: 2.1 +Name: typepy +Version: 1.3.2 +Summary: typepy is a Python library for variable type checker/validator/converter at a run time. +Home-page: https://github.com/thombashi/typepy +Author: Tsuyoshi Hombashi +Author-email: tsuyoshi.hombashi@gmail.com +License: MIT License +Project-URL: Documentation, https://typepy.rtfd.io/ +Project-URL: Source, https://github.com/thombashi/typepy +Project-URL: Tracker, https://github.com/thombashi/typepy/issues +Project-URL: Changlog, https://github.com/thombashi/typepy/releases +Keywords: library,type-checking,type-conversion,validator +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: mbstrdecoder <2,>=1.0.0 +Provides-Extra: datetime +Requires-Dist: python-dateutil <3.0.0,>=2.8.0 ; extra == 'datetime' +Requires-Dist: pytz >=2018.9 ; extra == 'datetime' +Requires-Dist: packaging ; extra == 'datetime' +Provides-Extra: test +Requires-Dist: pytest >=6.0.1 ; extra == 'test' +Requires-Dist: tcolorpy ; extra == 'test' +Requires-Dist: python-dateutil <3.0.0,>=2.8.0 ; extra == 'test' +Requires-Dist: pytz >=2018.9 ; extra == 'test' +Requires-Dist: packaging ; extra == 'test' + +.. contents:: **typepy** + :backlinks: top + :depth: 2 + +Summary +========= +`typepy `__ is a Python library for variable type checker/validator/converter at a run time. + +.. image:: https://badge.fury.io/py/typepy.svg + :target: https://badge.fury.io/py/typepy + :alt: PyPI package version + +.. image:: https://anaconda.org/conda-forge/typepy/badges/version.svg + :target: https://anaconda.org/conda-forge/typepy + :alt: conda-forge package version + +.. image:: https://img.shields.io/pypi/pyversions/typepy.svg + :target: https://pypi.org/project/typepy + :alt: Supported Python versions + +.. image:: https://img.shields.io/pypi/implementation/typepy.svg + :target: https://pypi.org/project/typepy + :alt: Supported Python implementations + +.. image:: https://github.com/thombashi/typepy/workflows/Tests/badge.svg + :target: https://github.com/thombashi/typepy/actions?query=workflow%3ATests + :alt: Linux/macOS/Windows CI status + +.. image:: https://coveralls.io/repos/github/thombashi/typepy/badge.svg?branch=master + :target: https://coveralls.io/github/thombashi/typepy?branch=master + :alt: Test coverage + +.. image:: https://github.com/thombashi/typepy/actions/workflows/github-code-scanning/codeql/badge.svg + :target: https://github.com/thombashi/typepy/actions/workflows/github-code-scanning/codeql + :alt: CodeQL + +Features +========== +- checking a value type +- validate a value for a type +- convert a value from one type to the other type + +The correspondence between Python types and ``typepy`` classes are as follows: + +.. table:: Supported Types + + ================================================ ======================================================================================================= + Python Type typepy: Type Class + ================================================ ======================================================================================================= + ``bool`` `Bool `__ + ``datetime`` `DateTime `__ + ``dict`` `Dictionary `__ + ``float``/``decimal.Decimal`` (not infinity/NaN) `RealNumber `__ + ``float``/``decimal.Decimal`` (infinity) `Infinity `__ + ``float``/``decimal.Decimal`` (NaN) `Nan `__ + ``int`` `Integer `__ + ``list`` `List `__ + ``None`` `None `__ + ``str`` (not null) `String `__ + ``str`` (null) `NullString `__ + ``str`` (IP address) `IpAddress `__ + ================================================ ======================================================================================================= + +Installation +============ + +Installation: pip +------------------------------ +:: + + pip install typepy + +Install additional dependency packages with the following command if using ``typepy.DateTime`` class + +:: + + pip install typepy[datetime] + +Installation: conda +------------------------------ +:: + + conda install -c conda-forge typepy + +Installation: apt +------------------------------ +:: + + sudo add-apt-repository ppa:thombashi/ppa + sudo apt update + sudo apt install python3-typepy + + +Dependencies +============ +- Python 3.7+ +- `Python package dependencies (automatically installed) `__ + +Optional dependencies +---------------------------------- +These packages can be installed via ``pip install typepy[datetime]``: + +- `python-dateutil `__ +- `pytz `__ + +Usage +======= +Type Check Method +---------------------- +:Examples: + .. code-block:: pycon + + >>> from typepy import Integer + >>> Integer(1).is_type() + True + >>> Integer(1.1).is_type() + False + + +Type Validation Method +-------------------------------------------- +:Examples: + .. code-block:: pycon + + >>> from typepy import Integer + >>> Integer(1).validate() + >>> try: + ... Integer(1.1).validate() + ... except TypeError as e: + ... # validate() raised TypeError when the value unmatched the type class + ... print(e) + ... + invalid value type: expected=INTEGER, actual= + + +Type Conversion Methods +-------------------------------------------- + +convert method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +:Examples: + .. code-block:: pycon + + >>> from typepy import Integer, TypeConversionError + >>> Integer("1").convert() + 1 + >>> try: + ... Integer(1.1).convert() + ... except TypeConversionError as e: + ... # convert() raised TypeConversionError when conversion failed + ... print(e) + ... + failed to convert from float to INTEGER + +try_convert method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +:Examples: + .. code-block:: pycon + + >>> from typepy import Integer + >>> Integer("1").try_convert() + 1 + >>> print(Integer(1.1).try_convert()) # try_convert() returned None when conversion failed + None + +force_convert +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +:Examples: + .. code-block:: pycon + + >>> from typepy import Integer, TypeConversionError + >>> Integer("1").force_convert() # force_convert() forcibly convert the value + 1 + >>> Integer(1.1).force_convert() + 1 + >>> try: + ... Integer("abc").force_convert() + ... except TypeConversionError as e: + ... # force_convert() raised TypeConversionError when the value was not convertible + ... print(e) + ... + failed to force_convert to int: type= + + +For more information +-------------------------------------------- +Type check/validate/convert results differed according to +``strict_level`` value which can pass to typepy class constructors as an argument. +More information can be found in the +`API reference `__. + +Documentation +=============== +https://typepy.rtfd.io/ + diff --git a/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/RECORD b/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1c817ea2f7d30d515237e02a6c044b4b8cfdf439 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/RECORD @@ -0,0 +1,107 @@ +typepy-1.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +typepy-1.3.2.dist-info/LICENSE,sha256=vrvfBSShR_iaYV__U9eb3JDLx2MVUPtLclzT873NJPY,1074 +typepy-1.3.2.dist-info/METADATA,sha256=cGfwlvtjr-CbCpbIGheSP46P82OT7ki6Gof2jZEdhKo,9309 +typepy-1.3.2.dist-info/RECORD,, +typepy-1.3.2.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +typepy-1.3.2.dist-info/top_level.txt,sha256=JS3pVzz8HrmCDbSyNrOs7vCirWUXl5es6HfIxEtbP2M,7 +typepy/__init__.py,sha256=dbTD5m3Nf_tMD4lWG7FAxqdUMC0dZgtgale52Oe57f0,1129 +typepy/__pycache__/__init__.cpython-310.pyc,, +typepy/__pycache__/__version__.cpython-310.pyc,, +typepy/__pycache__/_common.cpython-310.pyc,, +typepy/__pycache__/_const.cpython-310.pyc,, +typepy/__pycache__/_function.cpython-310.pyc,, +typepy/__pycache__/_typecode.cpython-310.pyc,, +typepy/__pycache__/error.cpython-310.pyc,, +typepy/__version__.py,sha256=bZfSgZ3naje3Nx6ysBkhI-QAm434QZYGFu90lJBPKUI,201 +typepy/_common.py,sha256=NV8Cr2hVr4zs7kkU2pZjPOXON8YQgn8JJptYh9j-JR0,401 +typepy/_const.py,sha256=CPuhx_t7xV5QdCJ6UKGvglDmZBoJIEIt5kSFV7pxGUo,312 +typepy/_function.py,sha256=MsE-BOyhhSPkupgDFPMRlz2YQB9pF0c-fnxhYDROglo,1096 +typepy/_typecode.py,sha256=Oi_zWK5ULiyCjmjb1Urtb3bm-J2LYqyX2TqiCmizuPs,397 +typepy/checker/__init__.py,sha256=Aj1kUaY7OQZd61SW_sktpim10dFkkPD5v8CkQ4mqEe4,1000 +typepy/checker/__pycache__/__init__.cpython-310.pyc,, +typepy/checker/__pycache__/_bool.cpython-310.pyc,, +typepy/checker/__pycache__/_bytes.cpython-310.pyc,, +typepy/checker/__pycache__/_checker.cpython-310.pyc,, +typepy/checker/__pycache__/_common.cpython-310.pyc,, +typepy/checker/__pycache__/_datetime.cpython-310.pyc,, +typepy/checker/__pycache__/_dictionary.cpython-310.pyc,, +typepy/checker/__pycache__/_infinity.cpython-310.pyc,, +typepy/checker/__pycache__/_integer.cpython-310.pyc,, +typepy/checker/__pycache__/_interface.cpython-310.pyc,, +typepy/checker/__pycache__/_ipaddress.cpython-310.pyc,, +typepy/checker/__pycache__/_list.cpython-310.pyc,, +typepy/checker/__pycache__/_nan.cpython-310.pyc,, +typepy/checker/__pycache__/_none.cpython-310.pyc,, +typepy/checker/__pycache__/_realnumber.cpython-310.pyc,, +typepy/checker/__pycache__/_string.cpython-310.pyc,, +typepy/checker/_bool.py,sha256=O6EITPb7OsdZOApFcdRMJADFV0N59D3ulsJkAPFzW9o,1198 +typepy/checker/_bytes.py,sha256=mYmu2ksd0h9qoBsO3SaVm9ple8edQOpV6s3RErjHscA,646 +typepy/checker/_checker.py,sha256=TxeIAXVIBXukmd1881PeXGNW7ZNapsPA9vS53wwVKck,2485 +typepy/checker/_common.py,sha256=PpinqXPbViDkTZ-HSXqemU01EeeSvaoUDuCwndPGbRc,539 +typepy/checker/_datetime.py,sha256=TffEQDoClczSF6P4o29yMbzLl-yzIAIccWXplBybFtY,1159 +typepy/checker/_dictionary.py,sha256=qXhH9plLosj967PEGCTgZvRbHZoreomnPQV6SCu1GC8,885 +typepy/checker/_infinity.py,sha256=CRgTptMZLRHzPjp93ZtgHpYM3WpV-D4p7aLt1ZyttNM,916 +typepy/checker/_integer.py,sha256=eBzHsd4xWprtzaHJglRvET_Dhi0KqrstlWyT5eCKJ88,2002 +typepy/checker/_interface.py,sha256=IiMShH1pAWhl_6JlUxtb10ofao2sUspUlGxDC1nnZps,315 +typepy/checker/_ipaddress.py,sha256=hqPXXD50x-ndLKj-DPjfLCZscN1CXawMTvOodSc1bsc,1070 +typepy/checker/_list.py,sha256=iGkycr08dVONSkerYl51WfYyidlzI3JfN5LJ_zwKU5U,985 +typepy/checker/_nan.py,sha256=SBTyHoTKtQO-wIMZ5lW-y88CGk5MLIoteig29lIQQtc,826 +typepy/checker/_none.py,sha256=xM_PEJQx1WpPUYAN6Bwgl-_IqAmhrV1oie8XIbm_C5Y,617 +typepy/checker/_realnumber.py,sha256=jtA-rv19NUBRjwAS7owNbXehJLB10dS2RCt8sLbIv5Y,1905 +typepy/checker/_string.py,sha256=Wyte6y2c2RYDCvi9BF5exzFXGscgtBrDPY3K5rhrzYs,2055 +typepy/converter/__init__.py,sha256=aN7I5tHOx93voqOeakOoad6JF07mdAKnEk0kknduo3Q,824 +typepy/converter/__pycache__/__init__.cpython-310.pyc,, +typepy/converter/__pycache__/_bool.cpython-310.pyc,, +typepy/converter/__pycache__/_bytes.cpython-310.pyc,, +typepy/converter/__pycache__/_datetime.cpython-310.pyc,, +typepy/converter/__pycache__/_dictionary.cpython-310.pyc,, +typepy/converter/__pycache__/_integer.cpython-310.pyc,, +typepy/converter/__pycache__/_interface.cpython-310.pyc,, +typepy/converter/__pycache__/_ipaddress.cpython-310.pyc,, +typepy/converter/__pycache__/_list.cpython-310.pyc,, +typepy/converter/__pycache__/_nop.cpython-310.pyc,, +typepy/converter/__pycache__/_realnumber.cpython-310.pyc,, +typepy/converter/__pycache__/_string.cpython-310.pyc,, +typepy/converter/_bool.py,sha256=ROvCowqO6nBk_Ywxcc6SUIvDVcO9acWUfsZ1fCo4Dig,1306 +typepy/converter/_bytes.py,sha256=L8e4DJ3qVqLkc2g9zlD2EMyJHYwBL4aB2EyH9w50-B4,291 +typepy/converter/_datetime.py,sha256=AaSsLhJtaNXB6TzaL98m2dpu61ZQBhbJ5MnF_sTiw5U,5382 +typepy/converter/_dictionary.py,sha256=v2ZCaSNq2U-QOgF86BTGfr9fcD0DM8UD2Oe0yFRGVAA,655 +typepy/converter/_integer.py,sha256=9ivAktrr4UQ2Yj4GVZ8Bij_Q11lqGpCxSiTU0VWtGQs,1015 +typepy/converter/_interface.py,sha256=TcqsYIsnbM3LX20k0vx7eCZnxk_Wyo6fnbBvlw4C5RY,661 +typepy/converter/_ipaddress.py,sha256=KrGcw-kn8oD0fnc3R6yaqrbgkXJWdr8XDAqFt6HJoog,843 +typepy/converter/_list.py,sha256=35ERzQ7mQXO0g5ax2Rvk93nC5FYVuAzNEQtAcZKp92E,426 +typepy/converter/_nop.py,sha256=DOkVEKioITGa_pPpgj14VClVj0ELLOjX0sgLN4nl-WI,222 +typepy/converter/_realnumber.py,sha256=7oPwNB8zWtDR6rB1JsRE4JD0CfXFGGGp-LCOmKlDPiw,1265 +typepy/converter/_string.py,sha256=Hj1G3tq0n6Jrbt3RCFAihbMlASm-QmQKgaWcsMxIbYw,498 +typepy/error.py,sha256=9tKHKExk8rOLQGtLfQQewBBaqnS39egkJYpiC7G1pWo,178 +typepy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +typepy/type/__init__.py,sha256=BVyVbzsx2snaim_h-ibWpXELDkRxTqjLCE-xK5FliAg,743 +typepy/type/__pycache__/__init__.cpython-310.pyc,, +typepy/type/__pycache__/_base.cpython-310.pyc,, +typepy/type/__pycache__/_binary.cpython-310.pyc,, +typepy/type/__pycache__/_bool.cpython-310.pyc,, +typepy/type/__pycache__/_bytes.cpython-310.pyc,, +typepy/type/__pycache__/_datetime.cpython-310.pyc,, +typepy/type/__pycache__/_dictionary.cpython-310.pyc,, +typepy/type/__pycache__/_infinity.cpython-310.pyc,, +typepy/type/__pycache__/_integer.cpython-310.pyc,, +typepy/type/__pycache__/_ipaddress.cpython-310.pyc,, +typepy/type/__pycache__/_list.cpython-310.pyc,, +typepy/type/__pycache__/_nan.cpython-310.pyc,, +typepy/type/__pycache__/_none.cpython-310.pyc,, +typepy/type/__pycache__/_realnumber.cpython-310.pyc,, +typepy/type/__pycache__/_string.cpython-310.pyc,, +typepy/type/_base.py,sha256=v9Robzl8j7vFkJoqikzOK9Y31m7OF9QZwvx3hMFRxn4,3552 +typepy/type/_binary.py,sha256=1LV28p-B7q7KTqIWPd2ONPrQH8AmkGOV8imH_a95V_M,794 +typepy/type/_bool.py,sha256=QHYMUKTDTKEeXFilPqoVGFi9cz69qfqrSSPJhRQMGbM,844 +typepy/type/_bytes.py,sha256=i58k-iFWQUMTbp6fJ998KWKoEazvSWwly6LKmB2lD08,792 +typepy/type/_datetime.py,sha256=0hiq7E2DkfOzgQZY7TQ6y8B7edFCqQ7CUMZAOTkmXSI,835 +typepy/type/_dictionary.py,sha256=0UnNrzvsisNQxD6eCcCpNtwRLdXfxSDUgcA9M9geeJ0,849 +typepy/type/_infinity.py,sha256=8pnVfBwlKIEo35tbvSqiCOYsnDpZ1TA_F0tn3oDFAhQ,829 +typepy/type/_integer.py,sha256=HBgXgCfT7TtbHNigVK__-Lbaocb7CY29n6WzkWLbYjY,864 +typepy/type/_ipaddress.py,sha256=MroUImyV-POnQTvmpMpOGH7-PAwAFQz-HU5rjTV9A0c,843 +typepy/type/_list.py,sha256=_KBDpeKDdIEb3dLMJv8vkHjAY9awiKz7RoMQdnCMF6o,807 +typepy/type/_nan.py,sha256=9jbhUqOLXstqr8-FuBKikImEOk5C5RO0WtqpRbj27zU,804 +typepy/type/_none.py,sha256=VGIXkKgdONkcu2CXGPfgusoo-VL-xkEV3rKldPDAbac,859 +typepy/type/_realnumber.py,sha256=_dNKpzDr8FaImBbx84Yr2fsJNBicRE_1QdRu8NrzDq4,913 +typepy/type/_string.py,sha256=Dd0mOTQ_uxXQND-l-AFkzwNFK8EwGg_C-EyQw4TxOXg,1505 diff --git a/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/top_level.txt b/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8245b7ba766af5b5d3536966c639c373c6fc5f57 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/typepy-1.3.2.dist-info/top_level.txt @@ -0,0 +1 @@ +typepy diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/_base_connection.py b/llmeval-env/lib/python3.10/site-packages/urllib3/_base_connection.py new file mode 100644 index 0000000000000000000000000000000000000000..bb349c744bd1a426550b8402f928707c7d1ef1c1 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/_base_connection.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +import typing + +from .util.connection import _TYPE_SOCKET_OPTIONS +from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from .util.url import Url + +_TYPE_BODY = typing.Union[bytes, typing.IO[typing.Any], typing.Iterable[bytes], str] + + +class ProxyConfig(typing.NamedTuple): + ssl_context: ssl.SSLContext | None + use_forwarding_for_https: bool + assert_hostname: None | str | Literal[False] + assert_fingerprint: str | None + + +class _ResponseOptions(typing.NamedTuple): + # TODO: Remove this in favor of a better + # HTTP request/response lifecycle tracking. + request_method: str + request_url: str + preload_content: bool + decode_content: bool + enforce_content_length: bool + + +if typing.TYPE_CHECKING: + import ssl + from typing import Literal, Protocol + + from .response import BaseHTTPResponse + + class BaseHTTPConnection(Protocol): + default_port: typing.ClassVar[int] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + host: str + port: int + timeout: None | ( + float + ) # Instance doesn't store _DEFAULT_TIMEOUT, must be resolved. + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool + proxy_is_verified: bool | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = ..., + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + ... + + def set_tunnel( + self, + host: str, + port: int | None = None, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + ... + + def connect(self) -> None: + ... + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + ... + + def getresponse(self) -> BaseHTTPResponse: + ... + + def close(self) -> None: + ... + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + + class BaseHTTPSConnection(BaseHTTPConnection, Protocol): + default_port: typing.ClassVar[int] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + # Certificate verification methods + cert_reqs: int | str | None + assert_hostname: None | str | Literal[False] + assert_fingerprint: str | None + ssl_context: ssl.SSLContext | None + + # Trusted CAs + ca_certs: str | None + ca_cert_dir: str | None + ca_cert_data: None | str | bytes + + # TLS version + ssl_minimum_version: int | None + ssl_maximum_version: int | None + ssl_version: int | str | None # Deprecated + + # Client certificates + cert_file: str | None + key_file: str | None + key_password: str | None + + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: _TYPE_SOCKET_OPTIONS | None = ..., + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: ssl.SSLContext | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + ... diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/__init__.py b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/__init__.py b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3c5bebdc151eef715663628a697118bb2932ed --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/__init__.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +import urllib3.connection + +from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection + + +def inject_into_urllib3() -> None: + # override connection classes to use emscripten specific classes + # n.b. mypy complains about the overriding of classes below + # if it isn't ignored + HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection + HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection + urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment] + urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment] diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/connection.py b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..2ceb4579eb549cbd22398e5a7d81130b981d824c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/connection.py @@ -0,0 +1,254 @@ +from __future__ import annotations + +import os +import typing + +# use http.client.HTTPException for consistency with non-emscripten +from http.client import HTTPException as HTTPException # noqa: F401 +from http.client import ResponseNotReady + +from ..._base_connection import _TYPE_BODY +from ...connection import HTTPConnection, ProxyConfig, port_by_scheme +from ...exceptions import TimeoutError +from ...response import BaseHTTPResponse +from ...util.connection import _TYPE_SOCKET_OPTIONS +from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT +from ...util.url import Url +from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request +from .request import EmscriptenRequest +from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + + +class EmscriptenHTTPConnection: + default_port: typing.ClassVar[int] = port_by_scheme["http"] + default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] + + timeout: None | (float) + + host: str + port: int + blocksize: int + source_address: tuple[str, int] | None + socket_options: _TYPE_SOCKET_OPTIONS | None + + proxy: Url | None + proxy_config: ProxyConfig | None + + is_verified: bool = False + proxy_is_verified: bool | None = None + + _response: EmscriptenResponse | None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + socket_options: _TYPE_SOCKET_OPTIONS | None = None, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + ) -> None: + self.host = host + self.port = port + self.timeout = timeout if isinstance(timeout, float) else 0.0 + self.scheme = "http" + self._closed = True + self._response = None + # ignore these things because we don't + # have control over that stuff + self.proxy = None + self.proxy_config = None + self.blocksize = blocksize + self.source_address = None + self.socket_options = None + self.is_verified = False + + def set_tunnel( + self, + host: str, + port: int | None = 0, + headers: typing.Mapping[str, str] | None = None, + scheme: str = "http", + ) -> None: + pass + + def connect(self) -> None: + pass + + def request( + self, + method: str, + url: str, + body: _TYPE_BODY | None = None, + headers: typing.Mapping[str, str] | None = None, + # We know *at least* botocore is depending on the order of the + # first 3 parameters so to be safe we only mark the later ones + # as keyword-only to ensure we have space to extend. + *, + chunked: bool = False, + preload_content: bool = True, + decode_content: bool = True, + enforce_content_length: bool = True, + ) -> None: + self._closed = False + if url.startswith("/"): + # no scheme / host / port included, make a full url + url = f"{self.scheme}://{self.host}:{self.port}" + url + request = EmscriptenRequest( + url=url, + method=method, + timeout=self.timeout if self.timeout else 0, + decode_content=decode_content, + ) + request.set_body(body) + if headers: + for k, v in headers.items(): + request.set_header(k, v) + self._response = None + try: + if not preload_content: + self._response = send_streaming_request(request) + if self._response is None: + self._response = send_request(request) + except _TimeoutError as e: + raise TimeoutError(e.message) from e + except _RequestError as e: + raise HTTPException(e.message) from e + + def getresponse(self) -> BaseHTTPResponse: + if self._response is not None: + return EmscriptenHttpResponseWrapper( + internal_response=self._response, + url=self._response.request.url, + connection=self, + ) + else: + raise ResponseNotReady() + + def close(self) -> None: + self._closed = True + self._response = None + + @property + def is_closed(self) -> bool: + """Whether the connection either is brand new or has been previously closed. + If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` + properties must be False. + """ + return self._closed + + @property + def is_connected(self) -> bool: + """Whether the connection is actively connected to any origin (proxy or target)""" + return True + + @property + def has_connected_to_proxy(self) -> bool: + """Whether the connection has successfully connected to its proxy. + This returns False if no proxy is in use. Used to determine whether + errors are coming from the proxy layer or from tunnelling to the target origin. + """ + return False + + +class EmscriptenHTTPSConnection(EmscriptenHTTPConnection): + default_port = port_by_scheme["https"] + # all this is basically ignored, as browser handles https + cert_reqs: int | str | None = None + ca_certs: str | None = None + ca_cert_dir: str | None = None + ca_cert_data: None | str | bytes = None + cert_file: str | None + key_file: str | None + key_password: str | None + ssl_context: typing.Any | None + ssl_version: int | str | None = None + ssl_minimum_version: int | None = None + ssl_maximum_version: int | None = None + assert_hostname: None | str | typing.Literal[False] + assert_fingerprint: str | None = None + + def __init__( + self, + host: str, + port: int = 0, + *, + timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, + source_address: tuple[str, int] | None = None, + blocksize: int = 16384, + socket_options: None + | _TYPE_SOCKET_OPTIONS = HTTPConnection.default_socket_options, + proxy: Url | None = None, + proxy_config: ProxyConfig | None = None, + cert_reqs: int | str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + server_hostname: str | None = None, + ssl_context: typing.Any | None = None, + ca_certs: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ssl_minimum_version: int | None = None, + ssl_maximum_version: int | None = None, + ssl_version: int | str | None = None, # Deprecated + cert_file: str | None = None, + key_file: str | None = None, + key_password: str | None = None, + ) -> None: + super().__init__( + host, + port=port, + timeout=timeout, + source_address=source_address, + blocksize=blocksize, + socket_options=socket_options, + proxy=proxy, + proxy_config=proxy_config, + ) + self.scheme = "https" + + self.key_file = key_file + self.cert_file = cert_file + self.key_password = key_password + self.ssl_context = ssl_context + self.server_hostname = server_hostname + self.assert_hostname = assert_hostname + self.assert_fingerprint = assert_fingerprint + self.ssl_version = ssl_version + self.ssl_minimum_version = ssl_minimum_version + self.ssl_maximum_version = ssl_maximum_version + self.ca_certs = ca_certs and os.path.expanduser(ca_certs) + self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) + self.ca_cert_data = ca_cert_data + + self.cert_reqs = None + + # The browser will automatically verify all requests. + # We have no control over that setting. + self.is_verified = True + + def set_cert( + self, + key_file: str | None = None, + cert_file: str | None = None, + cert_reqs: int | str | None = None, + key_password: str | None = None, + ca_certs: str | None = None, + assert_hostname: None | str | typing.Literal[False] = None, + assert_fingerprint: str | None = None, + ca_cert_dir: str | None = None, + ca_cert_data: None | str | bytes = None, + ) -> None: + pass + + +# verify that this class implements BaseHTTP(s) connection correctly +if typing.TYPE_CHECKING: + _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0) + _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0) diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..243b86222f90a9be4b6b4ce0bf997eefd29289af --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/emscripten_fetch_worker.js @@ -0,0 +1,110 @@ +let Status = { + SUCCESS_HEADER: -1, + SUCCESS_EOF: -2, + ERROR_TIMEOUT: -3, + ERROR_EXCEPTION: -4, +}; + +let connections = {}; +let nextConnectionID = 1; +const encoder = new TextEncoder(); + +self.addEventListener("message", async function (event) { + if (event.data.close) { + let connectionID = event.data.close; + delete connections[connectionID]; + return; + } else if (event.data.getMore) { + let connectionID = event.data.getMore; + let { curOffset, value, reader, intBuffer, byteBuffer } = + connections[connectionID]; + // if we still have some in buffer, then just send it back straight away + if (!value || curOffset >= value.length) { + // read another buffer if required + try { + let readResponse = await reader.read(); + + if (readResponse.done) { + // read everything - clear connection and return + delete connections[connectionID]; + Atomics.store(intBuffer, 0, Status.SUCCESS_EOF); + Atomics.notify(intBuffer, 0); + // finished reading successfully + // return from event handler + return; + } + curOffset = 0; + connections[connectionID].value = readResponse.value; + value = readResponse.value; + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } + + // send as much buffer as we can + let curLen = value.length - curOffset; + if (curLen > byteBuffer.length) { + curLen = byteBuffer.length; + } + byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0); + + Atomics.store(intBuffer, 0, curLen); // store current length in bytes + Atomics.notify(intBuffer, 0); + curOffset += curLen; + connections[connectionID].curOffset = curOffset; + + return; + } else { + // start fetch + let connectionID = nextConnectionID; + nextConnectionID += 1; + const intBuffer = new Int32Array(event.data.buffer); + const byteBuffer = new Uint8Array(event.data.buffer, 8); + try { + const response = await fetch(event.data.url, event.data.fetchParams); + // return the headers first via textencoder + var headers = []; + for (const pair of response.headers.entries()) { + headers.push([pair[0], pair[1]]); + } + let headerObj = { + headers: headers, + status: response.status, + connectionID, + }; + const headerText = JSON.stringify(headerObj); + let headerBytes = encoder.encode(headerText); + let written = headerBytes.length; + byteBuffer.set(headerBytes); + intBuffer[1] = written; + // make a connection + connections[connectionID] = { + reader: response.body.getReader(), + intBuffer: intBuffer, + byteBuffer: byteBuffer, + value: undefined, + curOffset: 0, + }; + // set header ready + Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER); + Atomics.notify(intBuffer, 0); + // all fetching after this goes through a new postmessage call with getMore + // this allows for parallel requests + } catch (error) { + console.log("Request exception:", error); + let errorBytes = encoder.encode(error.message); + let written = errorBytes.length; + byteBuffer.set(errorBytes); + intBuffer[1] = written; + Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); + Atomics.notify(intBuffer, 0); + } + } +}); +self.postMessage({ inited: true }); diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/request.py b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/request.py new file mode 100644 index 0000000000000000000000000000000000000000..e692e692bd0d38f6a0677992a6993fc68050dff3 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/request.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from dataclasses import dataclass, field + +from ..._base_connection import _TYPE_BODY + + +@dataclass +class EmscriptenRequest: + method: str + url: str + params: dict[str, str] | None = None + body: _TYPE_BODY | None = None + headers: dict[str, str] = field(default_factory=dict) + timeout: float = 0 + decode_content: bool = True + + def set_header(self, name: str, value: str) -> None: + self.headers[name.capitalize()] = value + + def set_body(self, body: _TYPE_BODY | None) -> None: + self.body = body diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/response.py b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/response.py new file mode 100644 index 0000000000000000000000000000000000000000..303b4ee0117d45f0f47aa1c7a6e4fcf594665a9a --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/emscripten/response.py @@ -0,0 +1,276 @@ +from __future__ import annotations + +import json as _json +import logging +import typing +from contextlib import contextmanager +from dataclasses import dataclass +from http.client import HTTPException as HTTPException +from io import BytesIO, IOBase + +from ...exceptions import InvalidHeader, TimeoutError +from ...response import BaseHTTPResponse +from ...util.retry import Retry +from .request import EmscriptenRequest + +if typing.TYPE_CHECKING: + from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection + +log = logging.getLogger(__name__) + + +@dataclass +class EmscriptenResponse: + status_code: int + headers: dict[str, str] + body: IOBase | bytes + request: EmscriptenRequest + + +class EmscriptenHttpResponseWrapper(BaseHTTPResponse): + def __init__( + self, + internal_response: EmscriptenResponse, + url: str | None = None, + connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, + ): + self._pool = None # set by pool class + self._body = None + self._response = internal_response + self._url = url + self._connection = connection + self._closed = False + super().__init__( + headers=internal_response.headers, + status=internal_response.status_code, + request_url=url, + version=0, + reason="", + decode_content=True, + ) + self.length_remaining = self._init_length(self._response.request.method) + self.length_is_certain = False + + @property + def url(self) -> str | None: + return self._url + + @url.setter + def url(self, url: str | None) -> None: + self._url = url + + @property + def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None: + return self._connection + + @property + def retries(self) -> Retry | None: + return self._retries + + @retries.setter + def retries(self, retries: Retry | None) -> None: + # Override the request_url if retries has a redirect location. + self._retries = retries + + def stream( + self, amt: int | None = 2**16, decode_content: bool | None = None + ) -> typing.Generator[bytes, None, None]: + """ + A generator wrapper for the read() method. A call will block until + ``amt`` bytes have been read from the connection or until the + connection is closed. + + :param amt: + How much of the content to read. The generator will return up to + much data per iteration, but may return less. This is particularly + likely when using compressed data. However, the empty string will + never be returned. + + :param decode_content: + If True, will attempt to decode the body based on the + 'content-encoding' header. + """ + while True: + data = self.read(amt=amt, decode_content=decode_content) + + if data: + yield data + else: + break + + def _init_length(self, request_method: str | None) -> int | None: + length: int | None + content_length: str | None = self.headers.get("content-length") + + if content_length is not None: + try: + # RFC 7230 section 3.3.2 specifies multiple content lengths can + # be sent in a single Content-Length header + # (e.g. Content-Length: 42, 42). This line ensures the values + # are all valid ints and that as long as the `set` length is 1, + # all values are the same. Otherwise, the header is invalid. + lengths = {int(val) for val in content_length.split(",")} + if len(lengths) > 1: + raise InvalidHeader( + "Content-Length contained multiple " + "unmatching values (%s)" % content_length + ) + length = lengths.pop() + except ValueError: + length = None + else: + if length < 0: + length = None + + else: # if content_length is None + length = None + + # Check for responses that shouldn't include a body + if ( + self.status in (204, 304) + or 100 <= self.status < 200 + or request_method == "HEAD" + ): + length = 0 + + return length + + def read( + self, + amt: int | None = None, + decode_content: bool | None = None, # ignored because browser decodes always + cache_content: bool = False, + ) -> bytes: + if ( + self._closed + or self._response is None + or (isinstance(self._response.body, IOBase) and self._response.body.closed) + ): + return b"" + + with self._error_catcher(): + # body has been preloaded as a string by XmlHttpRequest + if not isinstance(self._response.body, IOBase): + self.length_remaining = len(self._response.body) + self.length_is_certain = True + # wrap body in IOStream + self._response.body = BytesIO(self._response.body) + if amt is not None: + # don't cache partial content + cache_content = False + data = self._response.body.read(amt) + if self.length_remaining is not None: + self.length_remaining = max(self.length_remaining - len(data), 0) + if (self.length_is_certain and self.length_remaining == 0) or len( + data + ) < amt: + # definitely finished reading, close response stream + self._response.body.close() + return typing.cast(bytes, data) + else: # read all we can (and cache it) + data = self._response.body.read() + if cache_content: + self._body = data + if self.length_remaining is not None: + self.length_remaining = max(self.length_remaining - len(data), 0) + if len(data) == 0 or ( + self.length_is_certain and self.length_remaining == 0 + ): + # definitely finished reading, close response stream + self._response.body.close() + return typing.cast(bytes, data) + + def read_chunked( + self, + amt: int | None = None, + decode_content: bool | None = None, + ) -> typing.Generator[bytes, None, None]: + # chunked is handled by browser + while True: + bytes = self.read(amt, decode_content) + if not bytes: + break + yield bytes + + def release_conn(self) -> None: + if not self._pool or not self._connection: + return None + + self._pool._put_conn(self._connection) + self._connection = None + + def drain_conn(self) -> None: + self.close() + + @property + def data(self) -> bytes: + if self._body: + return self._body + else: + return self.read(cache_content=True) + + def json(self) -> typing.Any: + """ + Parses the body of the HTTP response as JSON. + + To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to the decoder. + + This method can raise either `UnicodeDecodeError` or `json.JSONDecodeError`. + + Read more :ref:`here `. + """ + data = self.data.decode("utf-8") + return _json.loads(data) + + def close(self) -> None: + if not self._closed: + if isinstance(self._response.body, IOBase): + self._response.body.close() + if self._connection: + self._connection.close() + self._connection = None + self._closed = True + + @contextmanager + def _error_catcher(self) -> typing.Generator[None, None, None]: + """ + Catch Emscripten specific exceptions thrown by fetch.py, + instead re-raising urllib3 variants, so that low-level exceptions + are not leaked in the high-level api. + + On exit, release the connection back to the pool. + """ + from .fetch import _RequestError, _TimeoutError # avoid circular import + + clean_exit = False + + try: + yield + # If no exception is thrown, we should avoid cleaning up + # unnecessarily. + clean_exit = True + except _TimeoutError as e: + raise TimeoutError(str(e)) + except _RequestError as e: + raise HTTPException(str(e)) + finally: + # If we didn't terminate cleanly, we need to throw away our + # connection. + if not clean_exit: + # The response may not be closed but we're not going to use it + # anymore so close it now + if ( + isinstance(self._response.body, IOBase) + and not self._response.body.closed + ): + self._response.body.close() + # release the connection back to the pool + self.release_conn() + else: + # If we have read everything from the response stream, + # return the connection back to the pool. + if ( + isinstance(self._response.body, IOBase) + and self._response.body.closed + ): + self.release_conn() diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/pyopenssl.py b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/pyopenssl.py new file mode 100644 index 0000000000000000000000000000000000000000..b89a6dab886ffc3cca2495d873cafcc14ffcfe03 --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/pyopenssl.py @@ -0,0 +1,548 @@ +""" +Module for using pyOpenSSL as a TLS backend. This module was relevant before +the standard library ``ssl`` module supported SNI, but now that we've dropped +support for Python 2.7 all relevant Python versions support SNI so +**this module is no longer recommended**. + +This needs the following packages installed: + +* `pyOpenSSL`_ (tested with 16.0.0) +* `cryptography`_ (minimum 1.3.4, from pyopenssl) +* `idna`_ (minimum 2.0) + +However, pyOpenSSL depends on cryptography, so while we use all three directly here we +end up having relatively few packages required. + +You can install them with the following command: + +.. code-block:: bash + + $ python -m pip install pyopenssl cryptography idna + +To activate certificate checking, call +:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code +before you begin making HTTP requests. This can be done in a ``sitecustomize`` +module, or at any other time before your application begins using ``urllib3``, +like this: + +.. code-block:: python + + try: + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + pass + +.. _pyopenssl: https://www.pyopenssl.org +.. _cryptography: https://cryptography.io +.. _idna: https://github.com/kjd/idna +""" + +from __future__ import annotations + +import OpenSSL.SSL # type: ignore[import-untyped] +from cryptography import x509 + +try: + from cryptography.x509 import UnsupportedExtension # type: ignore[attr-defined] +except ImportError: + # UnsupportedExtension is gone in cryptography >= 2.1.0 + class UnsupportedExtension(Exception): # type: ignore[no-redef] + pass + + +import logging +import ssl +import typing +from io import BytesIO +from socket import socket as socket_cls +from socket import timeout + +from .. import util + +if typing.TYPE_CHECKING: + from OpenSSL.crypto import X509 # type: ignore[import-untyped] + + +__all__ = ["inject_into_urllib3", "extract_from_urllib3"] + +# Map from urllib3 to PyOpenSSL compatible parameter-values. +_openssl_versions: dict[int, int] = { + util.ssl_.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + util.ssl_.PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD, # type: ignore[attr-defined] + ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, +} + +if hasattr(ssl, "PROTOCOL_TLSv1_1") and hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD + +if hasattr(ssl, "PROTOCOL_TLSv1_2") and hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"): + _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD + + +_stdlib_to_openssl_verify = { + ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, + ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, + ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, +} +_openssl_to_stdlib_verify = {v: k for k, v in _stdlib_to_openssl_verify.items()} + +# The SSLvX values are the most likely to be missing in the future +# but we check them all just to be sure. +_OP_NO_SSLv2_OR_SSLv3: int = getattr(OpenSSL.SSL, "OP_NO_SSLv2", 0) | getattr( + OpenSSL.SSL, "OP_NO_SSLv3", 0 +) +_OP_NO_TLSv1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1", 0) +_OP_NO_TLSv1_1: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_1", 0) +_OP_NO_TLSv1_2: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_2", 0) +_OP_NO_TLSv1_3: int = getattr(OpenSSL.SSL, "OP_NO_TLSv1_3", 0) + +_openssl_to_ssl_minimum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1, + ssl.TLSVersion.TLSv1_3: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), + ssl.TLSVersion.MAXIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 + ), +} +_openssl_to_ssl_maximum_version: dict[int, int] = { + ssl.TLSVersion.MINIMUM_SUPPORTED: ( + _OP_NO_SSLv2_OR_SSLv3 + | _OP_NO_TLSv1 + | _OP_NO_TLSv1_1 + | _OP_NO_TLSv1_2 + | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1: ( + _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_1 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3 + ), + ssl.TLSVersion.TLSv1_1: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_2 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_2: _OP_NO_SSLv2_OR_SSLv3 | _OP_NO_TLSv1_3, + ssl.TLSVersion.TLSv1_3: _OP_NO_SSLv2_OR_SSLv3, + ssl.TLSVersion.MAXIMUM_SUPPORTED: _OP_NO_SSLv2_OR_SSLv3, +} + +# OpenSSL will only write 16K at a time +SSL_WRITE_BLOCKSIZE = 16384 + +orig_util_SSLContext = util.ssl_.SSLContext + + +log = logging.getLogger(__name__) + + +def inject_into_urllib3() -> None: + "Monkey-patch urllib3 with PyOpenSSL-backed SSL-support." + + _validate_dependencies_met() + + util.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.ssl_.SSLContext = PyOpenSSLContext # type: ignore[assignment] + util.IS_PYOPENSSL = True + util.ssl_.IS_PYOPENSSL = True + + +def extract_from_urllib3() -> None: + "Undo monkey-patching by :func:`inject_into_urllib3`." + + util.SSLContext = orig_util_SSLContext + util.ssl_.SSLContext = orig_util_SSLContext + util.IS_PYOPENSSL = False + util.ssl_.IS_PYOPENSSL = False + + +def _validate_dependencies_met() -> None: + """ + Verifies that PyOpenSSL's package-level dependencies have been met. + Throws `ImportError` if they are not met. + """ + # Method added in `cryptography==1.1`; not available in older versions + from cryptography.x509.extensions import Extensions + + if getattr(Extensions, "get_extension_for_class", None) is None: + raise ImportError( + "'cryptography' module missing required functionality. " + "Try upgrading to v1.3.4 or newer." + ) + + # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 + # attribute is only present on those versions. + from OpenSSL.crypto import X509 + + x509 = X509() + if getattr(x509, "_x509", None) is None: + raise ImportError( + "'pyOpenSSL' module missing required functionality. " + "Try upgrading to v0.14 or newer." + ) + + +def _dnsname_to_stdlib(name: str) -> str | None: + """ + Converts a dNSName SubjectAlternativeName field to the form used by the + standard library on the given Python version. + + Cryptography produces a dNSName as a unicode string that was idna-decoded + from ASCII bytes. We need to idna-encode that string to get it back, and + then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib + uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). + + If the name cannot be idna-encoded then we return None signalling that + the name given should be skipped. + """ + + def idna_encode(name: str) -> bytes | None: + """ + Borrowed wholesale from the Python Cryptography Project. It turns out + that we can't just safely call `idna.encode`: it can explode for + wildcard names. This avoids that problem. + """ + import idna + + try: + for prefix in ["*.", "."]: + if name.startswith(prefix): + name = name[len(prefix) :] + return prefix.encode("ascii") + idna.encode(name) + return idna.encode(name) + except idna.core.IDNAError: + return None + + # Don't send IPv6 addresses through the IDNA encoder. + if ":" in name: + return name + + encoded_name = idna_encode(name) + if encoded_name is None: + return None + return encoded_name.decode("utf-8") + + +def get_subj_alt_name(peer_cert: X509) -> list[tuple[str, str]]: + """ + Given an PyOpenSSL certificate, provides all the subject alternative names. + """ + cert = peer_cert.to_cryptography() + + # We want to find the SAN extension. Ask Cryptography to locate it (it's + # faster than looping in Python) + try: + ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value + except x509.ExtensionNotFound: + # No such extension, return the empty list. + return [] + except ( + x509.DuplicateExtension, + UnsupportedExtension, + x509.UnsupportedGeneralNameType, + UnicodeError, + ) as e: + # A problem has been found with the quality of the certificate. Assume + # no SAN field is present. + log.warning( + "A problem was encountered with the certificate that prevented " + "urllib3 from finding the SubjectAlternativeName field. This can " + "affect certificate validation. The error was %s", + e, + ) + return [] + + # We want to return dNSName and iPAddress fields. We need to cast the IPs + # back to strings because the match_hostname function wants them as + # strings. + # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 + # decoded. This is pretty frustrating, but that's what the standard library + # does with certificates, and so we need to attempt to do the same. + # We also want to skip over names which cannot be idna encoded. + names = [ + ("DNS", name) + for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) + if name is not None + ] + names.extend( + ("IP Address", str(name)) for name in ext.get_values_for_type(x509.IPAddress) + ) + + return names + + +class WrappedSocket: + """API-compatibility wrapper for Python OpenSSL's Connection-class.""" + + def __init__( + self, + connection: OpenSSL.SSL.Connection, + socket: socket_cls, + suppress_ragged_eofs: bool = True, + ) -> None: + self.connection = connection + self.socket = socket + self.suppress_ragged_eofs = suppress_ragged_eofs + self._io_refs = 0 + self._closed = False + + def fileno(self) -> int: + return self.socket.fileno() + + # Copy-pasted from Python 3.5 source code + def _decref_socketios(self) -> None: + if self._io_refs > 0: + self._io_refs -= 1 + if self._closed: + self.close() + + def recv(self, *args: typing.Any, **kwargs: typing.Any) -> bytes: + try: + data = self.connection.recv(*args, **kwargs) + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return b"" + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return b"" + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise timeout("The read operation timed out") from e + else: + return self.recv(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + else: + return data # type: ignore[no-any-return] + + def recv_into(self, *args: typing.Any, **kwargs: typing.Any) -> int: + try: + return self.connection.recv_into(*args, **kwargs) # type: ignore[no-any-return] + except OpenSSL.SSL.SysCallError as e: + if self.suppress_ragged_eofs and e.args == (-1, "Unexpected EOF"): + return 0 + else: + raise OSError(e.args[0], str(e)) from e + except OpenSSL.SSL.ZeroReturnError: + if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: + return 0 + else: + raise + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(self.socket, self.socket.gettimeout()): + raise timeout("The read operation timed out") from e + else: + return self.recv_into(*args, **kwargs) + + # TLS 1.3 post-handshake authentication + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"read error: {e!r}") from e + + def settimeout(self, timeout: float) -> None: + return self.socket.settimeout(timeout) + + def _send_until_done(self, data: bytes) -> int: + while True: + try: + return self.connection.send(data) # type: ignore[no-any-return] + except OpenSSL.SSL.WantWriteError as e: + if not util.wait_for_write(self.socket, self.socket.gettimeout()): + raise timeout() from e + continue + except OpenSSL.SSL.SysCallError as e: + raise OSError(e.args[0], str(e)) from e + + def sendall(self, data: bytes) -> None: + total_sent = 0 + while total_sent < len(data): + sent = self._send_until_done( + data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE] + ) + total_sent += sent + + def shutdown(self) -> None: + # FIXME rethrow compatible exceptions should we ever use this + self.connection.shutdown() + + def close(self) -> None: + self._closed = True + if self._io_refs <= 0: + self._real_close() + + def _real_close(self) -> None: + try: + return self.connection.close() # type: ignore[no-any-return] + except OpenSSL.SSL.Error: + return + + def getpeercert( + self, binary_form: bool = False + ) -> dict[str, list[typing.Any]] | None: + x509 = self.connection.get_peer_certificate() + + if not x509: + return x509 # type: ignore[no-any-return] + + if binary_form: + return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509) # type: ignore[no-any-return] + + return { + "subject": ((("commonName", x509.get_subject().CN),),), # type: ignore[dict-item] + "subjectAltName": get_subj_alt_name(x509), + } + + def version(self) -> str: + return self.connection.get_protocol_version_name() # type: ignore[no-any-return] + + +WrappedSocket.makefile = socket_cls.makefile # type: ignore[attr-defined] + + +class PyOpenSSLContext: + """ + I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible + for translating the interface of the standard library ``SSLContext`` object + to calls into PyOpenSSL. + """ + + def __init__(self, protocol: int) -> None: + self.protocol = _openssl_versions[protocol] + self._ctx = OpenSSL.SSL.Context(self.protocol) + self._options = 0 + self.check_hostname = False + self._minimum_version: int = ssl.TLSVersion.MINIMUM_SUPPORTED + self._maximum_version: int = ssl.TLSVersion.MAXIMUM_SUPPORTED + + @property + def options(self) -> int: + return self._options + + @options.setter + def options(self, value: int) -> None: + self._options = value + self._set_ctx_options() + + @property + def verify_mode(self) -> int: + return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] + + @verify_mode.setter + def verify_mode(self, value: ssl.VerifyMode) -> None: + self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback) + + def set_default_verify_paths(self) -> None: + self._ctx.set_default_verify_paths() + + def set_ciphers(self, ciphers: bytes | str) -> None: + if isinstance(ciphers, str): + ciphers = ciphers.encode("utf-8") + self._ctx.set_cipher_list(ciphers) + + def load_verify_locations( + self, + cafile: str | None = None, + capath: str | None = None, + cadata: bytes | None = None, + ) -> None: + if cafile is not None: + cafile = cafile.encode("utf-8") # type: ignore[assignment] + if capath is not None: + capath = capath.encode("utf-8") # type: ignore[assignment] + try: + self._ctx.load_verify_locations(cafile, capath) + if cadata is not None: + self._ctx.load_verify_locations(BytesIO(cadata)) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"unable to load trusted certificates: {e!r}") from e + + def load_cert_chain( + self, + certfile: str, + keyfile: str | None = None, + password: str | None = None, + ) -> None: + try: + self._ctx.use_certificate_chain_file(certfile) + if password is not None: + if not isinstance(password, bytes): + password = password.encode("utf-8") # type: ignore[assignment] + self._ctx.set_passwd_cb(lambda *_: password) + self._ctx.use_privatekey_file(keyfile or certfile) + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"Unable to load certificate chain: {e!r}") from e + + def set_alpn_protocols(self, protocols: list[bytes | str]) -> None: + protocols = [util.util.to_bytes(p, "ascii") for p in protocols] + return self._ctx.set_alpn_protos(protocols) # type: ignore[no-any-return] + + def wrap_socket( + self, + sock: socket_cls, + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: bytes | str | None = None, + ) -> WrappedSocket: + cnx = OpenSSL.SSL.Connection(self._ctx, sock) + + # If server_hostname is an IP, don't use it for SNI, per RFC6066 Section 3 + if server_hostname and not util.ssl_.is_ipaddress(server_hostname): + if isinstance(server_hostname, str): + server_hostname = server_hostname.encode("utf-8") + cnx.set_tlsext_host_name(server_hostname) + + cnx.set_connect_state() + + while True: + try: + cnx.do_handshake() + except OpenSSL.SSL.WantReadError as e: + if not util.wait_for_read(sock, sock.gettimeout()): + raise timeout("select timed out") from e + continue + except OpenSSL.SSL.Error as e: + raise ssl.SSLError(f"bad handshake: {e!r}") from e + break + + return WrappedSocket(cnx, sock) + + def _set_ctx_options(self) -> None: + self._ctx.set_options( + self._options + | _openssl_to_ssl_minimum_version[self._minimum_version] + | _openssl_to_ssl_maximum_version[self._maximum_version] + ) + + @property + def minimum_version(self) -> int: + return self._minimum_version + + @minimum_version.setter + def minimum_version(self, minimum_version: int) -> None: + self._minimum_version = minimum_version + self._set_ctx_options() + + @property + def maximum_version(self) -> int: + return self._maximum_version + + @maximum_version.setter + def maximum_version(self, maximum_version: int) -> None: + self._maximum_version = maximum_version + self._set_ctx_options() + + +def _verify_callback( + cnx: OpenSSL.SSL.Connection, + x509: X509, + err_no: int, + err_depth: int, + return_code: int, +) -> bool: + return err_no == 0 diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/socks.py b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/socks.py new file mode 100644 index 0000000000000000000000000000000000000000..5a803916b0db1e8075577e9bb594a6225e6ddc1c --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/contrib/socks.py @@ -0,0 +1,230 @@ +""" +This module contains provisional support for SOCKS proxies from within +urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and +SOCKS5. To enable its functionality, either install PySocks or install this +module with the ``socks`` extra. + +The SOCKS implementation supports the full range of urllib3 features. It also +supports the following SOCKS features: + +- SOCKS4A (``proxy_url='socks4a://...``) +- SOCKS4 (``proxy_url='socks4://...``) +- SOCKS5 with remote DNS (``proxy_url='socks5h://...``) +- SOCKS5 with local DNS (``proxy_url='socks5://...``) +- Usernames and passwords for the SOCKS proxy + +.. note:: + It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in + your ``proxy_url`` to ensure that DNS resolution is done from the remote + server instead of client-side when connecting to a domain name. + +SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 +supports IPv4, IPv6, and domain names. + +When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` +will be sent as the ``userid`` section of the SOCKS request: + +.. code-block:: python + + proxy_url="socks4a://@proxy-host" + +When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion +of the ``proxy_url`` will be sent as the username/password to authenticate +with the proxy: + +.. code-block:: python + + proxy_url="socks5h://:@proxy-host" + +""" + +from __future__ import annotations + +try: + import socks # type: ignore[import-not-found] +except ImportError: + import warnings + + from ..exceptions import DependencyWarning + + warnings.warn( + ( + "SOCKS support in urllib3 requires the installation of optional " + "dependencies: specifically, PySocks. For more information, see " + "https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies" + ), + DependencyWarning, + ) + raise + +import typing +from socket import timeout as SocketTimeout + +from ..connection import HTTPConnection, HTTPSConnection +from ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool +from ..exceptions import ConnectTimeoutError, NewConnectionError +from ..poolmanager import PoolManager +from ..util.url import parse_url + +try: + import ssl +except ImportError: + ssl = None # type: ignore[assignment] + +from typing import TypedDict + + +class _TYPE_SOCKS_OPTIONS(TypedDict): + socks_version: int + proxy_host: str | None + proxy_port: str | None + username: str | None + password: str | None + rdns: bool + + +class SOCKSConnection(HTTPConnection): + """ + A plain-text HTTP connection that connects via a SOCKS proxy. + """ + + def __init__( + self, + _socks_options: _TYPE_SOCKS_OPTIONS, + *args: typing.Any, + **kwargs: typing.Any, + ) -> None: + self._socks_options = _socks_options + super().__init__(*args, **kwargs) + + def _new_conn(self) -> socks.socksocket: + """ + Establish a new connection via the SOCKS proxy. + """ + extra_kw: dict[str, typing.Any] = {} + if self.source_address: + extra_kw["source_address"] = self.source_address + + if self.socket_options: + extra_kw["socket_options"] = self.socket_options + + try: + conn = socks.create_connection( + (self.host, self.port), + proxy_type=self._socks_options["socks_version"], + proxy_addr=self._socks_options["proxy_host"], + proxy_port=self._socks_options["proxy_port"], + proxy_username=self._socks_options["username"], + proxy_password=self._socks_options["password"], + proxy_rdns=self._socks_options["rdns"], + timeout=self.timeout, + **extra_kw, + ) + + except SocketTimeout as e: + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + + except socks.ProxyError as e: + # This is fragile as hell, but it seems to be the only way to raise + # useful errors here. + if e.socket_err: + error = e.socket_err + if isinstance(error, SocketTimeout): + raise ConnectTimeoutError( + self, + f"Connection to {self.host} timed out. (connect timeout={self.timeout})", + ) from e + else: + # Adding `from e` messes with coverage somehow, so it's omitted. + # See #2386. + raise NewConnectionError( + self, f"Failed to establish a new connection: {error}" + ) + else: + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + except OSError as e: # Defensive: PySocks should catch all these. + raise NewConnectionError( + self, f"Failed to establish a new connection: {e}" + ) from e + + return conn + + +# We don't need to duplicate the Verified/Unverified distinction from +# urllib3/connection.py here because the HTTPSConnection will already have been +# correctly set to either the Verified or Unverified form by that module. This +# means the SOCKSHTTPSConnection will automatically be the correct type. +class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): + pass + + +class SOCKSHTTPConnectionPool(HTTPConnectionPool): + ConnectionCls = SOCKSConnection + + +class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): + ConnectionCls = SOCKSHTTPSConnection + + +class SOCKSProxyManager(PoolManager): + """ + A version of the urllib3 ProxyManager that routes connections via the + defined SOCKS proxy. + """ + + pool_classes_by_scheme = { + "http": SOCKSHTTPConnectionPool, + "https": SOCKSHTTPSConnectionPool, + } + + def __init__( + self, + proxy_url: str, + username: str | None = None, + password: str | None = None, + num_pools: int = 10, + headers: typing.Mapping[str, str] | None = None, + **connection_pool_kw: typing.Any, + ): + parsed = parse_url(proxy_url) + + if username is None and password is None and parsed.auth is not None: + split = parsed.auth.split(":") + if len(split) == 2: + username, password = split + if parsed.scheme == "socks5": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = False + elif parsed.scheme == "socks5h": + socks_version = socks.PROXY_TYPE_SOCKS5 + rdns = True + elif parsed.scheme == "socks4": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = False + elif parsed.scheme == "socks4a": + socks_version = socks.PROXY_TYPE_SOCKS4 + rdns = True + else: + raise ValueError(f"Unable to determine SOCKS version from {proxy_url}") + + self.proxy_url = proxy_url + + socks_options = { + "socks_version": socks_version, + "proxy_host": parsed.host, + "proxy_port": parsed.port, + "username": username, + "password": password, + "rdns": rdns, + } + connection_pool_kw["_socks_options"] = socks_options + + super().__init__(num_pools, headers, **connection_pool_kw) + + self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme diff --git a/llmeval-env/lib/python3.10/site-packages/urllib3/http2.py b/llmeval-env/lib/python3.10/site-packages/urllib3/http2.py new file mode 100644 index 0000000000000000000000000000000000000000..15fa9d9157e7a1c075fec33e5bea49b44e1f7e0d --- /dev/null +++ b/llmeval-env/lib/python3.10/site-packages/urllib3/http2.py @@ -0,0 +1,229 @@ +from __future__ import annotations + +import threading +import types +import typing + +import h2.config # type: ignore[import-untyped] +import h2.connection # type: ignore[import-untyped] +import h2.events # type: ignore[import-untyped] + +import urllib3.connection +import urllib3.util.ssl_ +from urllib3.response import BaseHTTPResponse + +from ._collections import HTTPHeaderDict +from .connection import HTTPSConnection +from .connectionpool import HTTPSConnectionPool + +orig_HTTPSConnection = HTTPSConnection + +T = typing.TypeVar("T") + + +class _LockedObject(typing.Generic[T]): + """ + A wrapper class that hides a specific object behind a lock. + + The goal here is to provide a simple way to protect access to an object + that cannot safely be simultaneously accessed from multiple threads. The + intended use of this class is simple: take hold of it with a context + manager, which returns the protected object. + """ + + def __init__(self, obj: T): + self.lock = threading.RLock() + self._obj = obj + + def __enter__(self) -> T: + self.lock.acquire() + return self._obj + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: types.TracebackType | None, + ) -> None: + self.lock.release() + + +class HTTP2Connection(HTTPSConnection): + def __init__( + self, host: str, port: int | None = None, **kwargs: typing.Any + ) -> None: + self._h2_conn = self._new_h2_conn() + self._h2_stream: int | None = None + self._h2_headers: list[tuple[bytes, bytes]] = [] + + if "proxy" in kwargs or "proxy_config" in kwargs: # Defensive: + raise NotImplementedError("Proxies aren't supported with HTTP/2") + + super().__init__(host, port, **kwargs) + + def _new_h2_conn(self) -> _LockedObject[h2.connection.H2Connection]: + config = h2.config.H2Configuration(client_side=True) + return _LockedObject(h2.connection.H2Connection(config=config)) + + def connect(self) -> None: + super().connect() + + with self._h2_conn as h2_conn: + h2_conn.initiate_connection() + self.sock.sendall(h2_conn.data_to_send()) + + def putrequest( + self, + method: str, + url: str, + skip_host: bool = False, + skip_accept_encoding: bool = False, + ) -> None: + with self._h2_conn as h2_conn: + self._request_url = url + self._h2_stream = h2_conn.get_next_available_stream_id() + + if ":" in self.host: + authority = f"[{self.host}]:{self.port or 443}" + else: + authority = f"{self.host}:{self.port or 443}" + + self._h2_headers.extend( + ( + (b":scheme", b"https"), + (b":method", method.encode()), + (b":authority", authority.encode()), + (b":path", url.encode()), + ) + ) + + def putheader(self, header: str, *values: str) -> None: # type: ignore[override] + for value in values: + self._h2_headers.append( + (header.encode("utf-8").lower(), value.encode("utf-8")) + ) + + def endheaders(self) -> None: # type: ignore[override] + with self._h2_conn as h2_conn: + h2_conn.send_headers( + stream_id=self._h2_stream, + headers=self._h2_headers, + end_stream=True, + ) + if data_to_send := h2_conn.data_to_send(): + self.sock.sendall(data_to_send) + + def send(self, data: bytes) -> None: # type: ignore[override] # Defensive: + if not data: + return + raise NotImplementedError("Sending data isn't supported yet") + + def getresponse( # type: ignore[override] + self, + ) -> HTTP2Response: + status = None + data = bytearray() + with self._h2_conn as h2_conn: + end_stream = False + while not end_stream: + # TODO: Arbitrary read value. + if received_data := self.sock.recv(65535): + events = h2_conn.receive_data(received_data) + for event in events: + if isinstance(event, h2.events.ResponseReceived): + headers = HTTPHeaderDict() + for header, value in event.headers: + if header == b":status": + status = int(value.decode()) + else: + headers.add( + header.decode("ascii"), value.decode("ascii") + ) + + elif isinstance(event, h2.events.DataReceived): + data += event.data + h2_conn.acknowledge_received_data( + event.flow_controlled_length, event.stream_id + ) + + elif isinstance(event, h2.events.StreamEnded): + end_stream = True + + if data_to_send := h2_conn.data_to_send(): + self.sock.sendall(data_to_send) + + # We always close to not have to handle connection management. + self.close() + + assert status is not None + return HTTP2Response( + status=status, + headers=headers, + request_url=self._request_url, + data=bytes(data), + ) + + def close(self) -> None: + with self._h2_conn as h2_conn: + try: + h2_conn.close_connection() + if data := h2_conn.data_to_send(): + self.sock.sendall(data) + except Exception: + pass + + # Reset all our HTTP/2 connection state. + self._h2_conn = self._new_h2_conn() + self._h2_stream = None + self._h2_headers = [] + + super().close() + + +class HTTP2Response(BaseHTTPResponse): + # TODO: This is a woefully incomplete response object, but works for non-streaming. + def __init__( + self, + status: int, + headers: HTTPHeaderDict, + request_url: str, + data: bytes, + decode_content: bool = False, # TODO: support decoding + ) -> None: + super().__init__( + status=status, + headers=headers, + # Following CPython, we map HTTP versions to major * 10 + minor integers + version=20, + # No reason phrase in HTTP/2 + reason=None, + decode_content=decode_content, + request_url=request_url, + ) + self._data = data + self.length_remaining = 0 + + @property + def data(self) -> bytes: + return self._data + + def get_redirect_location(self) -> None: + return None + + def close(self) -> None: + pass + + +def inject_into_urllib3() -> None: + HTTPSConnectionPool.ConnectionCls = HTTP2Connection + urllib3.connection.HTTPSConnection = HTTP2Connection # type: ignore[misc] + + # TODO: Offer 'http/1.1' as well, but for testing purposes this is handy. + urllib3.util.ssl_.ALPN_PROTOCOLS = ["h2"] + + +def extract_from_urllib3() -> None: + HTTPSConnectionPool.ConnectionCls = orig_HTTPSConnection + urllib3.connection.HTTPSConnection = orig_HTTPSConnection # type: ignore[misc] + + urllib3.util.ssl_.ALPN_PROTOCOLS = ["http/1.1"]