FaustDerLegende commited on
Commit
58d5496
·
verified ·
1 Parent(s): 63a63dd

Upload folder using huggingface_hub (part 8)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +43 -0
  2. .venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/INSTALLER +1 -0
  3. .venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/METADATA +89 -0
  4. .venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/RECORD +204 -0
  5. .venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/WHEEL +6 -0
  6. .venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/licenses/LICENSE.txt +31 -0
  7. .venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/licenses/LICENSES.txt +127 -0
  8. .venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/top_level.txt +1 -0
  9. .venv/lib/python3.12/site-packages/lxml/includes/libxslt/xsltlocale.h +44 -0
  10. .venv/lib/python3.12/site-packages/lxml/includes/libxslt/xsltutils.h +343 -0
  11. .venv/lib/python3.12/site-packages/lxml/includes/lxml-version.h +3 -0
  12. .venv/lib/python3.12/site-packages/lxml/includes/relaxng.pxd +64 -0
  13. .venv/lib/python3.12/site-packages/lxml/includes/schematron.pxd +34 -0
  14. .venv/lib/python3.12/site-packages/lxml/includes/tree.pxd +492 -0
  15. .venv/lib/python3.12/site-packages/lxml/includes/uri.pxd +5 -0
  16. .venv/lib/python3.12/site-packages/lxml/includes/xinclude.pxd +22 -0
  17. .venv/lib/python3.12/site-packages/lxml/includes/xmlerror.pxd +860 -0
  18. .venv/lib/python3.12/site-packages/lxml/includes/xmlparser.pxd +319 -0
  19. .venv/lib/python3.12/site-packages/lxml/includes/xmlschema.pxd +35 -0
  20. .venv/lib/python3.12/site-packages/lxml/includes/xpath.pxd +136 -0
  21. .venv/lib/python3.12/site-packages/lxml/includes/xslt.pxd +190 -0
  22. .venv/lib/python3.12/site-packages/lxml/isoschematron/__init__.py +348 -0
  23. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng +709 -0
  24. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl +75 -0
  25. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl +77 -0
  26. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl +313 -0
  27. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl +1160 -0
  28. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl +55 -0
  29. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl +1796 -0
  30. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl +588 -0
  31. .venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt +84 -0
  32. .venv/lib/python3.12/site-packages/lxml/iterparse.pxi +443 -0
  33. .venv/lib/python3.12/site-packages/lxml/lxml.etree.h +244 -0
  34. .venv/lib/python3.12/site-packages/lxml/lxml.etree_api.h +214 -0
  35. .venv/lib/python3.12/site-packages/lxml/nsclasses.pxi +281 -0
  36. .venv/lib/python3.12/site-packages/lxml/objectify.cpython-312-x86_64-linux-gnu.so +3 -0
  37. .venv/lib/python3.12/site-packages/lxml/objectify.pyx +2148 -0
  38. .venv/lib/python3.12/site-packages/lxml/objectpath.pxi +332 -0
  39. .venv/lib/python3.12/site-packages/lxml/parser.pxi +2085 -0
  40. .venv/lib/python3.12/site-packages/lxml/parsertarget.pxi +180 -0
  41. .venv/lib/python3.12/site-packages/lxml/proxy.pxi +624 -0
  42. .venv/lib/python3.12/site-packages/lxml/public-api.pxi +178 -0
  43. .venv/lib/python3.12/site-packages/lxml/pyclasslookup.py +3 -0
  44. .venv/lib/python3.12/site-packages/lxml/readonlytree.pxi +565 -0
  45. .venv/lib/python3.12/site-packages/lxml/relaxng.pxi +165 -0
  46. .venv/lib/python3.12/site-packages/lxml/sax.cpython-312-x86_64-linux-gnu.so +3 -0
  47. .venv/lib/python3.12/site-packages/lxml/sax.py +285 -0
  48. .venv/lib/python3.12/site-packages/lxml/saxparser.pxi +875 -0
  49. .venv/lib/python3.12/site-packages/lxml/schematron.pxi +173 -0
  50. .venv/lib/python3.12/site-packages/lxml/serializer.pxi +1849 -0
.gitattributes CHANGED
@@ -176,3 +176,46 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
176
  .venv/lib/python3.12/site-packages/lxml/etree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
177
  .venv/lib/python3.12/site-packages/lxml/html/_difflib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
178
  .venv/lib/python3.12/site-packages/lxml/html/diff.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  .venv/lib/python3.12/site-packages/lxml/etree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
177
  .venv/lib/python3.12/site-packages/lxml/html/_difflib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
178
  .venv/lib/python3.12/site-packages/lxml/html/diff.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
179
+ .venv/lib/python3.12/site-packages/lxml/objectify.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
180
+ .venv/lib/python3.12/site-packages/lxml/sax.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
181
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/_cm_listed.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
182
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/_mathtext.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
183
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/axis.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
184
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/backend_bases.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
185
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/cbook.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
186
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/collections.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
187
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/colors.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
188
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/figure.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
189
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/patches.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
190
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/pyplot.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
191
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/ticker.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
192
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/transforms.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
193
+ .venv/lib/python3.12/site-packages/matplotlib/__pycache__/widgets.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
194
+ .venv/lib/python3.12/site-packages/matplotlib/_c_internal_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
195
+ .venv/lib/python3.12/site-packages/matplotlib/_image.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
196
+ .venv/lib/python3.12/site-packages/matplotlib/_path.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
197
+ .venv/lib/python3.12/site-packages/matplotlib/_qhull.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
198
+ .venv/lib/python3.12/site-packages/matplotlib/_tri.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
199
+ .venv/lib/python3.12/site-packages/matplotlib/axes/__pycache__/_axes.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
200
+ .venv/lib/python3.12/site-packages/matplotlib/axes/__pycache__/_base.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
201
+ .venv/lib/python3.12/site-packages/matplotlib/backends/__pycache__/backend_pdf.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
202
+ .venv/lib/python3.12/site-packages/matplotlib/backends/_backend_agg.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
203
+ .venv/lib/python3.12/site-packages/matplotlib/backends/_tkagg.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
204
+ .venv/lib/python3.12/site-packages/matplotlib/ft2font.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
205
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf filter=lfs diff=lfs merge=lfs -text
206
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text
207
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf filter=lfs diff=lfs merge=lfs -text
208
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf filter=lfs diff=lfs merge=lfs -text
209
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf filter=lfs diff=lfs merge=lfs -text
210
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf filter=lfs diff=lfs merge=lfs -text
211
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf filter=lfs diff=lfs merge=lfs -text
212
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSansMono.ttf filter=lfs diff=lfs merge=lfs -text
213
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf filter=lfs diff=lfs merge=lfs -text
214
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf filter=lfs diff=lfs merge=lfs -text
215
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf filter=lfs diff=lfs merge=lfs -text
216
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSerif.ttf filter=lfs diff=lfs merge=lfs -text
217
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/LastResortHE-Regular.ttf filter=lfs diff=lfs merge=lfs -text
218
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneral.ttf filter=lfs diff=lfs merge=lfs -text
219
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBol.ttf filter=lfs diff=lfs merge=lfs -text
220
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf filter=lfs diff=lfs merge=lfs -text
221
+ .venv/lib/python3.12/site-packages/matplotlib/mpl-data/fonts/ttf/STIXGeneralItalic.ttf filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/METADATA ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: lxml
3
+ Version: 6.1.3
4
+ Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
5
+ Home-page: https://lxml.de/
6
+ Author: lxml dev team
7
+ Author-email: lxml@lxml.de
8
+ Maintainer: lxml dev team
9
+ Maintainer-email: lxml@lxml.de
10
+ License: BSD-3-Clause
11
+ Project-URL: Source, https://github.com/lxml/lxml
12
+ Project-URL: Bug Tracker, https://bugs.launchpad.net/lxml
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: Programming Language :: Cython
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: 3.15
26
+ Classifier: Programming Language :: C
27
+ Classifier: Operating System :: OS Independent
28
+ Classifier: Topic :: Text Processing :: Markup :: HTML
29
+ Classifier: Topic :: Text Processing :: Markup :: XML
30
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
31
+ Requires-Python: >=3.8
32
+ License-File: LICENSE.txt
33
+ License-File: LICENSES.txt
34
+ Provides-Extra: source
35
+ Provides-Extra: cssselect
36
+ Requires-Dist: cssselect>=0.7; extra == "cssselect"
37
+ Provides-Extra: html5
38
+ Requires-Dist: html5lib; extra == "html5"
39
+ Provides-Extra: htmlsoup
40
+ Requires-Dist: BeautifulSoup4; extra == "htmlsoup"
41
+ Provides-Extra: html-clean
42
+ Requires-Dist: lxml_html_clean; extra == "html-clean"
43
+ Dynamic: author
44
+ Dynamic: author-email
45
+ Dynamic: classifier
46
+ Dynamic: description
47
+ Dynamic: home-page
48
+ Dynamic: license
49
+ Dynamic: license-file
50
+ Dynamic: maintainer
51
+ Dynamic: maintainer-email
52
+ Dynamic: project-url
53
+ Dynamic: provides-extra
54
+ Dynamic: requires-python
55
+ Dynamic: summary
56
+
57
+ lxml is a Pythonic, mature binding for the libxml2 and libxslt libraries.
58
+ It provides safe and convenient access to these libraries using the
59
+ ElementTree API.
60
+
61
+ It extends the ElementTree API significantly to offer support for XPath,
62
+ RelaxNG, XML Schema, XSLT, C14N and much more.
63
+
64
+ To contact the project, go to the `project home page <https://lxml.de/>`_
65
+ or see our bug tracker at https://launchpad.net/lxml
66
+
67
+ In case you want to use the current in-development version of lxml,
68
+ you can get it from the github repository at
69
+ https://github.com/lxml/lxml . Note that this requires Cython to
70
+ build the sources, see the build instructions on the project home page.
71
+
72
+
73
+ After an official release of a new stable series, bug fixes may become available at
74
+ https://github.com/lxml/lxml/tree/lxml-6.1 .
75
+ Running ``pip install https://github.com/lxml/lxml/archive/refs/heads/lxml-6.1.tar.gz``
76
+ will install the unreleased branch state as soon as a maintenance branch has been established.
77
+ Note that this requires Cython to be installed at an appropriate version for the build.
78
+
79
+ 6.1.3 (2026-09-02)
80
+ ==================
81
+
82
+ Bugs fixed
83
+ ----------
84
+
85
+ * LP#2165901: External parameter entity parsing was allowed by default
86
+ (with ``resolve_entities="internal"``).
87
+ Issue found by Tomer Fichman.
88
+
89
+
.venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/RECORD ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ lxml-6.1.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ lxml-6.1.3.dist-info/METADATA,sha256=qtifgQe8dARbhsm398CYQZYQJSDdf67V5ORWk7fDFe8,3279
3
+ lxml-6.1.3.dist-info/RECORD,,
4
+ lxml-6.1.3.dist-info/WHEEL,sha256=jde8E0A3MBG5-tE7dL5O7F6JnZpcb8QWUfL56f6Fu0E,152
5
+ lxml-6.1.3.dist-info/licenses/LICENSE.txt,sha256=j8K1aBM1FuRoRdIUeRet7uFkjnCumrXtbFQXr-9M6FU,1507
6
+ lxml-6.1.3.dist-info/licenses/LICENSES.txt,sha256=OI-pnzveREfNWky7EUA3vgJoVNts_onhEmkcHYq9zzw,6221
7
+ lxml-6.1.3.dist-info/top_level.txt,sha256=NjD988wqaKq512nshNdLt-uDxsjkp4Bh51m6N-dhUrk,5
8
+ lxml/ElementInclude.py,sha256=PSLeZFvCa76WHJulPLxcZXJtCI2-4dK2CtqPRiYOAQg,8560
9
+ lxml/__init__.py,sha256=PToaS-fM1B7pEplPzWDqTM7RGKaGvE25w_B_kHOfpto,574
10
+ lxml/__pycache__/ElementInclude.cpython-312.pyc,,
11
+ lxml/__pycache__/__init__.cpython-312.pyc,,
12
+ lxml/__pycache__/_elementpath.cpython-312.pyc,,
13
+ lxml/__pycache__/builder.cpython-312.pyc,,
14
+ lxml/__pycache__/cssselect.cpython-312.pyc,,
15
+ lxml/__pycache__/doctestcompare.cpython-312.pyc,,
16
+ lxml/__pycache__/pyclasslookup.cpython-312.pyc,,
17
+ lxml/__pycache__/sax.cpython-312.pyc,,
18
+ lxml/__pycache__/usedoctest.cpython-312.pyc,,
19
+ lxml/_elementpath.cpython-312-x86_64-linux-gnu.so,sha256=93EpQi3H67scveBPLNtz8eoT-8kAuU51E2kyawcJicE,209208
20
+ lxml/_elementpath.py,sha256=b80hM3ndAkTtRX6v54za3LkkAqCcd0700BbMPZHnTBU,10959
21
+ lxml/apihelpers.pxi,sha256=gpBRGS2YahNvLftQaxzjfyPmRAl7Oru02UWp2Dgks7I,64409
22
+ lxml/builder.cpython-312-x86_64-linux-gnu.so,sha256=rQ39QNVzyCIb6Fvs8_7E6GlriLTJwgs6eAX49C8bEIo,120952
23
+ lxml/builder.py,sha256=sL7iKT8NXVmpO_p2p2nHTjShjZOGMFLgFzgbhUFl68g,8487
24
+ lxml/classlookup.pxi,sha256=eEpDXfsFzFs3S3qBfRUOu2ZqqPEWi5VKkWinCtmQibQ,22468
25
+ lxml/cleanup.pxi,sha256=ZNEpbv7qx_ICPzsxhCaMUHCOfiznOoZ_u3jlYXHAuh4,8454
26
+ lxml/cssselect.py,sha256=_wZdX-B9p5MeIYABmENIYRWEkwXwX-7jO8Dkf-1rUZU,3306
27
+ lxml/debug.pxi,sha256=KTcpR8-slUYvmIPbE35GoHDNTb-gjTEvD7bw6LltM4c,1125
28
+ lxml/docloader.pxi,sha256=fcoVd_mwTFZhjItCv_TfwXpgVek7JlvFObSfRxmVqs0,5790
29
+ lxml/doctestcompare.py,sha256=40EDnkwpcvW86qNa86990OXF42xdHaosSZoiBsEjkzU,17731
30
+ lxml/dtd.pxi,sha256=IAKkmA4ZoC68sqAWcTqoS8jEGYcPQrVMCZgn4iLBYko,15281
31
+ lxml/etree.cpython-312-x86_64-linux-gnu.so,sha256=hX1HdKvTrEOC8t4uDo441OW9vRivuIeBtkBc7-5voCo,5276624
32
+ lxml/etree.h,sha256=cT6mKc-zelMXyVmCJKYaJkqaPpaeLDYE5NT8lhz-ap8,9792
33
+ lxml/etree.pyx,sha256=TpuPivOnyHC6JdRbyS-Gngsb41JsHA7s-w1XIQZDPOk,138294
34
+ lxml/etree_api.h,sha256=SCvMfwtBHc_3wy2sGLfPzxl0UuHYblML4zH58VAGGYQ,17710
35
+ lxml/extensions.pxi,sha256=saxxc1mZyA8WdwIIL90B4lQb351j8-G7ttLPI5k-8Hw,32248
36
+ lxml/html/ElementSoup.py,sha256=s_dLobLMuKn2DhexR-iDXdZrMFg1RjLy1feHsIeZMpw,320
37
+ lxml/html/__init__.py,sha256=CC5WdsvSptZhr9MZya1qsL6JKVbviYdrHOhXrGhmORg,64425
38
+ lxml/html/__pycache__/ElementSoup.cpython-312.pyc,,
39
+ lxml/html/__pycache__/__init__.cpython-312.pyc,,
40
+ lxml/html/__pycache__/_diffcommand.cpython-312.pyc,,
41
+ lxml/html/__pycache__/_difflib.cpython-312.pyc,,
42
+ lxml/html/__pycache__/_html5builder.cpython-312.pyc,,
43
+ lxml/html/__pycache__/_setmixin.cpython-312.pyc,,
44
+ lxml/html/__pycache__/builder.cpython-312.pyc,,
45
+ lxml/html/__pycache__/clean.cpython-312.pyc,,
46
+ lxml/html/__pycache__/defs.cpython-312.pyc,,
47
+ lxml/html/__pycache__/diff.cpython-312.pyc,,
48
+ lxml/html/__pycache__/formfill.cpython-312.pyc,,
49
+ lxml/html/__pycache__/html5parser.cpython-312.pyc,,
50
+ lxml/html/__pycache__/soupparser.cpython-312.pyc,,
51
+ lxml/html/__pycache__/usedoctest.cpython-312.pyc,,
52
+ lxml/html/_diffcommand.py,sha256=kz_7EP9PmYWuczlZcGiw74_rG0eTKvQ2lrO0rkiwlYE,2081
53
+ lxml/html/_difflib.cpython-312-x86_64-linux-gnu.so,sha256=rXY7VH5uaFaEdbvNcqVm_L1fMGVcaIZJUtJ6WBEHqWg,533464
54
+ lxml/html/_difflib.py,sha256=42VY1-zXATjVvyfN8oQGesjQUFSo7inagLi8ZGjVL5Q,85022
55
+ lxml/html/_html5builder.py,sha256=NLaT-Ev-aBgJpeQl-6ZbJChLZK5GV-znDkHOJD5VQC4,3230
56
+ lxml/html/_setmixin.py,sha256=8IFIOLmVz0G-XzsD2tCEkSFWO-dgPBHgvHufC8ni67s,1188
57
+ lxml/html/builder.py,sha256=Uz3r5uiuCdoN0UPa7ngoLMwAadVIhslzGvlRPGigY_M,6187
58
+ lxml/html/clean.py,sha256=WU0KfXAyjDFn2ojE7T1dfk4cl_FduBu5ZbFSTc9Up_o,503
59
+ lxml/html/defs.py,sha256=6z6B1ws_2l9zgw3DL7ML62wwBYe6m5reJp6m3uTKptQ,5398
60
+ lxml/html/diff.cpython-312-x86_64-linux-gnu.so,sha256=EBIGH3fz70uh3KioSseviVCdFqrjTwLZF-bk1mGDJv8,361496
61
+ lxml/html/diff.py,sha256=Za0By-yeYlQEjUu7m7xKB288kKiy8VBS5gT0RPOaFY0,32989
62
+ lxml/html/formfill.py,sha256=umgk0BbkAI1W6q9musFbL-cDnI_aap2NsLBJqk0UmVI,9681
63
+ lxml/html/html5parser.py,sha256=dnyC4cqHxywjZSzk0mu2L7THTZjxhg4yF4pncjusa_w,8634
64
+ lxml/html/soupparser.py,sha256=xo8VvNeOEb-SChuXLKCRECh8J7HBiJLE9sAbEskoUUQ,10197
65
+ lxml/html/usedoctest.py,sha256=tPlmVz4KK1GRKV5DJLrdVECeqsT9PlDzSqqTodVi5s0,249
66
+ lxml/includes/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
67
+ lxml/includes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
68
+ lxml/includes/__pycache__/__init__.cpython-312.pyc,,
69
+ lxml/includes/c14n.pxd,sha256=DBQcOJ0c_YS245ohMb8fmuEC1kFyv1LrNY_8Mf-syZg,1110
70
+ lxml/includes/config.pxd,sha256=H6Mrl8It21hzRI2hzMId9W48QqkYYkoLT4dniLNmdTw,96
71
+ lxml/includes/dtdvalid.pxd,sha256=Nv0OykjYehv2lO-Zj--q6jS3TAC_dvQVPSgPMuse1NM,689
72
+ lxml/includes/etree_defs.h,sha256=h_UjJTmNUqPyKNNrWB9hxmt6v4CF7_83XVY8dOfxqW0,14524
73
+ lxml/includes/etreepublic.pxd,sha256=Bn4d3JkWPqXputXqI-eJ0xmPrwNFPTfDCa7axgjB7FM,10184
74
+ lxml/includes/extlibs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
75
+ lxml/includes/extlibs/__pycache__/__init__.cpython-312.pyc,,
76
+ lxml/includes/extlibs/libcharset.h,sha256=GA0FumrbNI4VDGlzq3lf5CLaCwXgn4unw2l0btGQFwI,1510
77
+ lxml/includes/extlibs/localcharset.h,sha256=Z_AagaQeq0aDE7NPsVOqEf4nO4KcUp46ggo4d0ONIOQ,6338
78
+ lxml/includes/extlibs/zconf.h,sha256=BxihG-sylbNF-ymmO0S2VLKC2CxM0FE_YiVYfyspuLs,16921
79
+ lxml/includes/extlibs/zlib.h,sha256=gYZn1qtqN_50acsGp_DLLCyy8slIoD5azPGkp0vzAgo,103848
80
+ lxml/includes/htmlparser.pxd,sha256=9uASkP5dU7OE2lCOLT-z2e01qSbFlp4ehgwdostF_qk,2802
81
+ lxml/includes/libexslt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
82
+ lxml/includes/libexslt/__pycache__/__init__.cpython-312.pyc,,
83
+ lxml/includes/libexslt/exslt.h,sha256=eSW5tMJAewSUANLqk7AGEiU8b2BbCNRyauHnez7nKSU,3114
84
+ lxml/includes/libexslt/exsltconfig.h,sha256=QHxzEbRlv_h0USBvpr0Zrl0Muzlc71VCrvgR6lqnLEY,1172
85
+ lxml/includes/libexslt/exsltexports.h,sha256=1Jm9KTXm2FUUJIZ6V6-Uw55yG0BMULX3_goyxDd2LL8,1077
86
+ lxml/includes/libxml/HTMLparser.h,sha256=sU4xGqj-vBtEvzlxA3hBPWJboifvkc4F1hynKXmsl3k,9569
87
+ lxml/includes/libxml/HTMLtree.h,sha256=Q7UBKFbQ8fx4d_dMnmR6ay8JmfOhopFkDp2B63YkLDU,3517
88
+ lxml/includes/libxml/SAX.h,sha256=SFnG27EFrYGUB9HDL_xSIGBwEns5pl07rApXWThFZFM,386
89
+ lxml/includes/libxml/SAX2.h,sha256=RfFP5o3le-Rg8bnA2GW7L7L9_pfXCs3TieODcv1DTWY,4240
90
+ lxml/includes/libxml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
91
+ lxml/includes/libxml/__pycache__/__init__.cpython-312.pyc,,
92
+ lxml/includes/libxml/c14n.h,sha256=BSBXw6nIZutC8mWvbRrLLmoWjw3wRt-nM93vjXGMCm8,2742
93
+ lxml/includes/libxml/catalog.h,sha256=H9ssTCaBjtDqc-AZqCk1R7h8F2iD9szqLjJyHpaczXg,4633
94
+ lxml/includes/libxml/chvalid.h,sha256=TZcceNp6Cw0QlYwIqK9GxyYqL5UiAjpQyjt_yrZGTQE,5087
95
+ lxml/includes/libxml/debugXML.h,sha256=XXRNI39gJW7bGRC4SzE4ad-SJ906BsUGz3AwOtkKuS4,1667
96
+ lxml/includes/libxml/dict.h,sha256=SweaPGMtTTf4je6dNTIoEzcfEvpsAT9_PhR7FC0K-rQ,1770
97
+ lxml/includes/libxml/encoding.h,sha256=haL7ratww2wkIERGmtwUqU2BbTVe52FZFU7MmrOpsPk,9623
98
+ lxml/includes/libxml/entities.h,sha256=LEOCA826-0f8dhRJzC_2hvUVsSH7lKQjrea9hSTdBbo,4419
99
+ lxml/includes/libxml/globals.h,sha256=NH8zyRI5cXJJGp5k2aLxOm-reJEGOFX6LYP82GBXRlY,583
100
+ lxml/includes/libxml/hash.h,sha256=KIIpAYKBfGUU3ydWhGehUyfuauZz_Ps0gyambzQo_rc,7017
101
+ lxml/includes/libxml/list.h,sha256=oh7iJNQajRA_cHsNk9CcFPYkaW2smf4J_MpedPPjC4k,3128
102
+ lxml/includes/libxml/nanoftp.h,sha256=22PBtWhJueYLFvwukt4oFooRct_xJA83hbluHRBNXUM,302
103
+ lxml/includes/libxml/nanohttp.h,sha256=bLbzYjAyAKmP3ComMOPH6XaUImu6bNAESF1HrVtRve0,2124
104
+ lxml/includes/libxml/parser.h,sha256=Uq7-ce55UUAsvo4n6CiBlNQpmowewvWhOsQtgGM1UQ8,48498
105
+ lxml/includes/libxml/parserInternals.h,sha256=8_Wr6UgRzm8BRn1RPLxyBkw6BagAdDvVqMA_e181_EI,14539
106
+ lxml/includes/libxml/relaxng.h,sha256=VXZ74r5Yja06KqypdBHc8neDwPxQ2aMrsWHSdRt5oi4,5991
107
+ lxml/includes/libxml/schemasInternals.h,sha256=V8M4In3zf24EX55Yt4dcfxwp7NpHGYViKnLKwtyrPJ4,26233
108
+ lxml/includes/libxml/schematron.h,sha256=8EhPDhvtlMxl9e0C5rSbEruOvzJS5BC_OOFbq9RXZnY,4255
109
+ lxml/includes/libxml/threads.h,sha256=mT3CgK4lXK7-NDnUOFXqYuCK6fyY70S3BsHF-TnT45k,1619
110
+ lxml/includes/libxml/tree.h,sha256=zTRLt6h5x6ApyeXgs90CKQZSAl2hKm7b5NxtPKUQFAE,36106
111
+ lxml/includes/libxml/uri.h,sha256=J9teJHme5z883c4twF5oImEYY-E3xSvhdSGpyRVtvIg,2855
112
+ lxml/includes/libxml/valid.h,sha256=By61IbPvk_eLux7a8x0mOaly7oclFaSGaFE8b2xZcUE,13226
113
+ lxml/includes/libxml/xinclude.h,sha256=K3I5jhw2zAMj26LuRNZc15Bwv2JE2hWxwVn4TCqv2b4,3258
114
+ lxml/includes/libxml/xlink.h,sha256=TVLOkISrcKDelo9n_XIUyPiStDYa8NxuF2dz70aBFCI,5062
115
+ lxml/includes/libxml/xmlIO.h,sha256=FvbuMYTy1-S5PScabE03wz0oWKf626pmXvOPZNuLm-w,11948
116
+ lxml/includes/libxml/xmlautomata.h,sha256=7Sc3YgPz1ZIBKCHPSxs5oAwJEZWQ1RT2kyUw85pUtmU,4004
117
+ lxml/includes/libxml/xmlerror.h,sha256=mMfltMxUza6kiSBfP2QfnY3UlMP_rEXKfX0wruBLl4A,37561
118
+ lxml/includes/libxml/xmlexports.h,sha256=IyV3AMeQVbOl0wkjlnNX4B8WUZ-5GNKQmxZc6-maWUU,2025
119
+ lxml/includes/libxml/xmlmemory.h,sha256=m7wGvVMxNzZiuOAo3vkjxaVWstc8aQLzb6obbjPsebE,4658
120
+ lxml/includes/libxml/xmlmodule.h,sha256=ERUHUmDdZRmh6NjLYWUpse51rLWR8qNjPHOtdgmlLF0,1198
121
+ lxml/includes/libxml/xmlreader.h,sha256=BAHinlSOTXX3DEax9BniaIIPAXJyLGfzym9R-27LCcU,12387
122
+ lxml/includes/libxml/xmlregexp.h,sha256=_q6C1XRy8DS3kSmLbEKpvkKQciTgjTJgGc_zUQ6m22M,2632
123
+ lxml/includes/libxml/xmlsave.h,sha256=zcEQr9sO5CsFrnoOLshhdsqMEr8k4AeFhbkYyNfO9Fs,2934
124
+ lxml/includes/libxml/xmlschemas.h,sha256=5AfLnYUcfmxHRzg0dVpdHig--4ui1-XDwDgpKGDKCiU,7067
125
+ lxml/includes/libxml/xmlschemastypes.h,sha256=MYwlGmoKAo3lHRaaKgnCXiLmPT9KRjdxyCJ7TEyZ6jM,4583
126
+ lxml/includes/libxml/xmlstring.h,sha256=d5PpqxP1I1sfmCUHvVJtjoC9h7hLHcAAQ5ok_Rtf50I,5271
127
+ lxml/includes/libxml/xmlunicode.h,sha256=8sq3wEW2AiyTCuc3ZceOEkce7lfrI7VnkRfwEQgc6pU,278
128
+ lxml/includes/libxml/xmlversion.h,sha256=oVpaE_xbttaeZNFKSuSfcLOceWz7LQgKP71Z1msXZNo,5112
129
+ lxml/includes/libxml/xmlwriter.h,sha256=BEUwYNKx3xymDE9vepksEK7yVq9SXYm1d2pQnzlPy90,20688
130
+ lxml/includes/libxml/xpath.h,sha256=CQv6X_pRhuXoCVpqoDXYB7FfusLK7AuPxCNigwhNYAA,16156
131
+ lxml/includes/libxml/xpathInternals.h,sha256=mc9B5tdpfssyz_NPUzww6dKuWCtBybBiBRJkTe4AE4U,18504
132
+ lxml/includes/libxml/xpointer.h,sha256=DAxMsfPp2SSZgXFrPbxBA84RwTMRf35Qg_LBbUzPQhA,1026
133
+ lxml/includes/libxslt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
134
+ lxml/includes/libxslt/__pycache__/__init__.cpython-312.pyc,,
135
+ lxml/includes/libxslt/attributes.h,sha256=qKwzfGf7r89esLC65s96iYJWRA-s-Ezss2_V6Mmo1hk,957
136
+ lxml/includes/libxslt/documents.h,sha256=kBihgH5pqRvFalhm_fOFHtJTFhTpBcm681yT5dxgwfw,2704
137
+ lxml/includes/libxslt/extensions.h,sha256=W5UMyJqUP_1zt6sXZ0mgc0gAIwDJrZ8gjByhyrWqvd8,6899
138
+ lxml/includes/libxslt/extra.h,sha256=6X3Wu3NdPtrlqz-Koo7dB-rccnnszi6j3zg599gTByg,1640
139
+ lxml/includes/libxslt/functions.h,sha256=fc4CZj-9KeBHzO9-WWU_bNqmaEZAz3n7NNwClIBXk14,1972
140
+ lxml/includes/libxslt/imports.h,sha256=18kIjoGqdFXR63Ce3ZtzxsTiYV3XGKpchYakMUPDuUI,1840
141
+ lxml/includes/libxslt/keys.h,sha256=16v25VEluS7jYhgg6gYFwVxgGMn-1ctnlhhWWT4RcBY,1155
142
+ lxml/includes/libxslt/namespaces.h,sha256=VofSn2Kkn-a5JyRKCmY3jPp7amQy3n09vzy0KUQt4q0,1666
143
+ lxml/includes/libxslt/numbersInternals.h,sha256=Eg5gYZ5p3h0_e5wyI61S-0E6_ArVJzv0yr63j6BU2fc,2019
144
+ lxml/includes/libxslt/pattern.h,sha256=tJ-BPfs9UYgiZMMoQZbhij3g7xVppYq7TrrOu25eR7Q,2110
145
+ lxml/includes/libxslt/preproc.h,sha256=D_LjEdHhsdyBnEAvflnwFgoR4hGUb72kgEhXkkmPRsw,896
146
+ lxml/includes/libxslt/security.h,sha256=fUD1cy_WxFCTvTNAF0WOQIU4p5CNWn1LHFyZJd-Fx5U,2652
147
+ lxml/includes/libxslt/templates.h,sha256=bnt6Jqui6KU5pNUdMNPbQZkZ5d-VTWqC0TMGkOlVoIo,2268
148
+ lxml/includes/libxslt/transform.h,sha256=ICT7meUV0OTAx27WaKVrKj-aUmR9LSpTNaOAJd2UStg,6311
149
+ lxml/includes/libxslt/variables.h,sha256=cQAgPe4QCcK2uKbWg7Iz-9peM9xWGm7m3M6jQm0sjIA,3143
150
+ lxml/includes/libxslt/xslt.h,sha256=wmFx2Q31Pd8Iq2phAQpY9J3QQatb8lWg3gABtqKFgEw,1964
151
+ lxml/includes/libxslt/xsltInternals.h,sha256=2EbEKYmnYZq0HjGnUMAlpqnqZJurRXzjlgk5Js1WYaY,57949
152
+ lxml/includes/libxslt/xsltconfig.h,sha256=cV5scdRK6xmOHeOg3OCw6hBfcQ_nrtNs_tKefX67304,2910
153
+ lxml/includes/libxslt/xsltexports.h,sha256=1-luH-0bCIgBAlKAXhV-dqHBfwOAQNDamiYbxIlTf0k,1124
154
+ lxml/includes/libxslt/xsltlocale.h,sha256=ppxGEmJfZIJgwRQzCM0_77p9WNekEWq1NrdYZrQl4IE,942
155
+ lxml/includes/libxslt/xsltutils.h,sha256=1eguYgR9-jeNOVlBUktHboaq-VLX6JXraO80TfbARKM,9085
156
+ lxml/includes/lxml-version.h,sha256=0rZqkMCJLEETewejbKe4d7jbhUTDg4TIIH3iH_08tK0,71
157
+ lxml/includes/relaxng.pxd,sha256=HzHlQ6mCcf_tj_JZ9NAVJTVAv8ScCkE8Ifq15y3bS0c,2615
158
+ lxml/includes/schematron.pxd,sha256=Hob7xh-K-MKqp7WiG8thMagf5EkQzmgfi4ds0EF91JA,1604
159
+ lxml/includes/tree.pxd,sha256=XApzMRy_LSqCtQ-OTS-vNSW7CT_OWstybfIT2H84LsA,20179
160
+ lxml/includes/uri.pxd,sha256=3vOXw6AbSPxAM9uo71T1qnfx-wd9ezXLDQtWsb2zX0I,145
161
+ lxml/includes/xinclude.pxd,sha256=CuO_XZNB6E2JK1qXXWn11APrjFQV5kA6SMyb77WZn0A,804
162
+ lxml/includes/xmlerror.pxd,sha256=OQqayytkV0NigAPbsQCCcvmy7luRe0XhVzpTdzJjP3g,58837
163
+ lxml/includes/xmlparser.pxd,sha256=QI4shDCLpi5w2TrCofrGvoHLrtkf-xhNtjCU0PBf0VQ,13789
164
+ lxml/includes/xmlschema.pxd,sha256=OLZPd2WDJyopiXJJyo-dAyyYHaeSYFiMAI4tqIiv-Ik,1702
165
+ lxml/includes/xpath.pxd,sha256=e8-ZYUbRG7N1mHETAlknJ_QqAteOosrYLRgpH-OsTkg,5603
166
+ lxml/includes/xslt.pxd,sha256=4yl3pOu7pAvsx5Tc-W4IWCoB8wgtSSR62HI1jqu6jko,8241
167
+ lxml/isoschematron/__init__.py,sha256=uauerYeKTlWFCJSqieIHhF5l6rYV2myeEJ0Imd1LzRc,13274
168
+ lxml/isoschematron/__pycache__/__init__.cpython-312.pyc,,
169
+ lxml/isoschematron/resources/rng/iso-schematron.rng,sha256=VsWxPyi3iViJDDbjJJw0wWkEHkLrz9zoCA8zJLor9N4,18337
170
+ lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl,sha256=ObebsB8Wt-d3uIA_U5NU85TpnQ3PxPX38TdOAqosMac,3172
171
+ lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl,sha256=QweRrIIM-zFcgg98GXA2CaWfIbgVE0XKEeYSfvv67A0,4563
172
+ lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl,sha256=xSZ_Ekq_I-62ZpiE5AqYYHwFW_qh855zt9V4_s7rbkY,11703
173
+ lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl,sha256=x42QJ-dxQ1waPzydsCoQnp2Xj15y53nW43O7BuoDRHk,39957
174
+ lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl,sha256=Tr9BnO6pzjVWwhqJfm10UlvAy95EgfSCz2iMlrVGT6Q,2015
175
+ lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl,sha256=ue8q_88X4e_jsJizo31GRNBxNhdxkEE9fY20oq0Iqwk,71764
176
+ lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl,sha256=BBAdsVSi5zAzeGepuN6gS1saQINDqITXKplmmj4dTWg,20382
177
+ lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt,sha256=OGLiFswuLJEW5EPYKOeoauuCJFEtVa6jyzBE1OcJI98,3310
178
+ lxml/iterparse.pxi,sha256=rERnJ9D0Cvn87YDMSq8V880DKV2WthXs5BXSSY2Baj4,16845
179
+ lxml/lxml.etree.h,sha256=cT6mKc-zelMXyVmCJKYaJkqaPpaeLDYE5NT8lhz-ap8,9792
180
+ lxml/lxml.etree_api.h,sha256=BNOxJcjbrM4h_CJEkEIQYJtStHyRqVY-DYTqSNShatg,17715
181
+ lxml/nsclasses.pxi,sha256=5pzNBhBtlqObPdThL9QIGRs1Dxj1qnr0PyXuTCURqTg,9129
182
+ lxml/objectify.cpython-312-x86_64-linux-gnu.so,sha256=4LvCTEQCTQbAAaXjmRQ-usOcUhjal2xaLYoLTqFMtWk,2920920
183
+ lxml/objectify.pyx,sha256=H60YL7qowr6a8VAq9L9ibHd3BnXAJR6Ix5CMYdZMAeM,75804
184
+ lxml/objectpath.pxi,sha256=s5TNG2-EbaWWKLFAiX303B95zK_Ui8ausB__3QvFFGw,11450
185
+ lxml/parser.pxi,sha256=q2_66C-xga6rMU8E8IcYpV9H-8MDsK6pLs7EugyQqbc,85911
186
+ lxml/parsertarget.pxi,sha256=v1PidxRaG5giwXcTDkpBI7PDFmsZuOcK0y9LdkQaY8M,6326
187
+ lxml/proxy.pxi,sha256=LnqqSZVUsJ5MnuVrhYrLwMbAKWuv1eOn-XYslut6CLM,24015
188
+ lxml/public-api.pxi,sha256=yVPuZV2LwN5Ki73mD85V9hnUXxOs5VMeFMLtQMNf0Qk,6756
189
+ lxml/pyclasslookup.py,sha256=gLD1HM2HtITYYiGzjEOewSwbB7XkVx_NZv_quCt79Oc,92
190
+ lxml/readonlytree.pxi,sha256=n2MRjz81EADWBXJx0miosN8PJ4i5y3guQJT_RZF6qKg,19008
191
+ lxml/relaxng.pxi,sha256=3OQ-fZMzP-KF5vM6HTozT_9ee3J0DJnpj9RcHC8LoMw,6339
192
+ lxml/sax.cpython-312-x86_64-linux-gnu.so,sha256=gUC4fxEtgMx8YPE9RedPgPyVXhoOxABFIm_G-2fZFSM,186296
193
+ lxml/sax.py,sha256=5ryEnOMIMeLpLel-PFpszMHq99mWNmsnGrMvLWIm1UM,9708
194
+ lxml/saxparser.pxi,sha256=yV67FWD60DfmFi7hbV_eLyJIMu7X2MOfV2g4X99iUR4,33538
195
+ lxml/schematron.pxi,sha256=F2OHKZUl57-byBk_wWtPTnHZ1fwlj0FtwG3VuGtG-UY,6064
196
+ lxml/serializer.pxi,sha256=iIXfechFHfvFs2sTk7wMIy3sDJxmaMPbNO33mkLLBUE,68063
197
+ lxml/usedoctest.py,sha256=qRgZKQVcAZcl-zN0AIXVJnOsETUXz2nPXkxuzs1lGgk,230
198
+ lxml/xinclude.pxi,sha256=7eBrI_OK47mmrHQ0ixbixRI8pKqQ1nwkMV-OmKUVlD4,2456
199
+ lxml/xmlerror.pxi,sha256=MAQv92NXFoaMOzT8WeeM0L3YyksFoo48tpz3KZHTqcY,50234
200
+ lxml/xmlid.pxi,sha256=5zf9oR6bsCtavGiOmilNyHqYwgG_bnrIabSd2SURtm0,6073
201
+ lxml/xmlschema.pxi,sha256=mumNoHni5S3BQPtcmOHRd61KRaVWu4eOie2wQeB0e6E,8490
202
+ lxml/xpath.pxi,sha256=aqW24V817dUxps4Gnc8h7Tm3QVlITKvxU5_9WgJUIFg,19132
203
+ lxml/xslt.pxi,sha256=ksNo3hkrzYYKeIcz8rR4Lm8s_g0XF-pynPTdCzYIHRA,36482
204
+ lxml/xsltext.pxi,sha256=TImDiAPlAezC07P7RY1N9YChA7AuKFH-G53hXdel9yc,11088
.venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-manylinux_2_26_x86_64
5
+ Tag: cp312-cp312-manylinux_2_28_x86_64
6
+
.venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/licenses/LICENSE.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2004 Infrae. All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are
7
+ met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright
10
+ notice, this list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright
13
+ notice, this list of conditions and the following disclaimer in
14
+ the documentation and/or other materials provided with the
15
+ distribution.
16
+
17
+ 3. Neither the name of Infrae nor the names of its contributors may
18
+ be used to endorse or promote products derived from this software
19
+ without specific prior written permission.
20
+
21
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INFRAE OR
25
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/licenses/LICENSES.txt ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ lxml is copyright Infrae and distributed under the BSD license (see
2
+ doc/licenses/BSD.txt), with the following exceptions:
3
+
4
+ Some code, such a selftest.py, selftest2.py and
5
+ src/lxml/_elementpath.py are derived from ElementTree and
6
+ cElementTree. See doc/licenses/elementtree.txt for the license text.
7
+ Newer versions reuse code from CPython's 'xml.etree' implementation,
8
+ licensed under the PSF-License v2.
9
+ See https://docs.python.org/3/license.html
10
+
11
+ A copy of difflib is used as part of lxml.html, forked from the CPython
12
+ standard library and licensed under the PSF-License v2.
13
+ See https://docs.python.org/3/license.html
14
+
15
+ lxml.cssselect and lxml.html are copyright Ian Bicking and distributed
16
+ under the BSD license (see doc/licenses/BSD.txt).
17
+
18
+ test.py, the test-runner script, is GPL and copyright Shuttleworth
19
+ Foundation. See doc/licenses/GPL.txt. It is believed the unchanged
20
+ inclusion of test.py to run the unit test suite falls under the
21
+ "aggregation" clause of the GPL and thus does not affect the license
22
+ of the rest of the package.
23
+
24
+ The isoschematron implementation uses several XSL and RelaxNG resources:
25
+ * The (XML syntax) RelaxNG schema for schematron, copyright International
26
+ Organization for Standardization (see
27
+ src/lxml/isoschematron/resources/rng/iso-schematron.rng for the license
28
+ text)
29
+ * The skeleton iso-schematron-xlt1 pure-xslt schematron implementation
30
+ xsl stylesheets, copyright Rick Jelliffe and Academia Sinica Computing
31
+ Center, Taiwan (see the xsl files here for the license text:
32
+ src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/)
33
+ * The xsd/rng schema schematron extraction xsl transformations are unlicensed
34
+ and copyright the respective authors as noted (see
35
+ src/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl and
36
+ src/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl)
37
+
38
+
39
+ Binary wheels
40
+ -------------
41
+
42
+ The officiall distributed binary wheels include bundled versions of the libraries
43
+ zlib, iconv, libxml2, libxslt and libexslt.
44
+ These libraries are linked, used and distributed under their following
45
+ respective licenses:
46
+
47
+ **zlib**: zlib-license, https://www.zlib.net/zlib_license.html
48
+
49
+ **iconv**: LGPL 2.1, https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
50
+
51
+ **libxml2**: MIT
52
+
53
+ Except where otherwise noted in the source code (e.g. the files dict.c and
54
+ list.c, which are covered by a similar licence but with different Copyright
55
+ notices) all the files are:
56
+
57
+ Copyright (C) 1998-2012 Daniel Veillard. All Rights Reserved.
58
+ Copyright (C) The Libxml2 Contributors.
59
+
60
+ Permission is hereby granted, free of charge, to any person obtaining a copy
61
+ of this software and associated documentation files (the "Software"), to deal
62
+ in the Software without restriction, including without limitation the rights
63
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
64
+ copies of the Software, and to permit persons to whom the Software is fur-
65
+ nished to do so, subject to the following conditions:
66
+
67
+ The above copyright notice and this permission notice shall be included in
68
+ all copies or substantial portions of the Software.
69
+
70
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
71
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT-
72
+ NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
73
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
74
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
75
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
76
+ THE SOFTWARE.
77
+
78
+ **libxslt**: MIT
79
+
80
+ Copyright (C) 2001-2002 Daniel Veillard. All Rights Reserved.
81
+
82
+ Permission is hereby granted, free of charge, to any person obtaining a copy
83
+ of this software and associated documentation files (the "Software"), to deal
84
+ in the Software without restriction, including without limitation the rights
85
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
86
+ copies of the Software, and to permit persons to whom the Software is fur-
87
+ nished to do so, subject to the following conditions:
88
+
89
+ The above copyright notice and this permission notice shall be included in
90
+ all copies or substantial portions of the Software.
91
+
92
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
93
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT-
94
+ NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
95
+ DANIEL VEILLARD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
96
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CON-
97
+ NECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
98
+
99
+ Except as contained in this notice, the name of Daniel Veillard shall not
100
+ be used in advertising or otherwise to promote the sale, use or other deal-
101
+ ings in this Software without prior written authorization from him.
102
+
103
+ **libexslt**: MIT
104
+
105
+ Copyright (C) 2001-2002 Thomas Broyer, Charlie Bozeman and Daniel Veillard.
106
+ All Rights Reserved.
107
+
108
+ Permission is hereby granted, free of charge, to any person obtaining a copy
109
+ of this software and associated documentation files (the "Software"), to deal
110
+ in the Software without restriction, including without limitation the rights
111
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
112
+ copies of the Software, and to permit persons to whom the Software is fur-
113
+ nished to do so, subject to the following conditions:
114
+
115
+ The above copyright notice and this permission notice shall be included in
116
+ all copies or substantial portions of the Software.
117
+
118
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
119
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT-
120
+ NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
121
+ AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
122
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CON-
123
+ NECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
124
+
125
+ Except as contained in this notice, the name of the authors shall not
126
+ be used in advertising or otherwise to promote the sale, use or other deal-
127
+ ings in this Software without prior written authorization from him.
.venv/lib/python3.12/site-packages/lxml-6.1.3.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ lxml
.venv/lib/python3.12/site-packages/lxml/includes/libxslt/xsltlocale.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Summary: Locale handling
3
+ * Description: Interfaces for locale handling. Needed for language dependent
4
+ * sorting.
5
+ *
6
+ * Copy: See Copyright for the status of this software.
7
+ *
8
+ * Author: Nick Wellnhofer
9
+ */
10
+
11
+ #ifndef __XML_XSLTLOCALE_H__
12
+ #define __XML_XSLTLOCALE_H__
13
+
14
+ #include <libxml/xmlstring.h>
15
+ #include "xsltexports.h"
16
+
17
+ #ifdef __cplusplus
18
+ extern "C" {
19
+ #endif
20
+
21
+ XSLTPUBFUN void * XSLTCALL
22
+ xsltNewLocale (const xmlChar *langName,
23
+ int lowerFirst);
24
+ XSLTPUBFUN void XSLTCALL
25
+ xsltFreeLocale (void *locale);
26
+ XSLTPUBFUN xmlChar * XSLTCALL
27
+ xsltStrxfrm (void *locale,
28
+ const xmlChar *string);
29
+ XSLTPUBFUN void XSLTCALL
30
+ xsltFreeLocales (void);
31
+
32
+ /* Backward compatibility */
33
+ typedef void *xsltLocale;
34
+ typedef xmlChar xsltLocaleChar;
35
+ XSLTPUBFUN int XSLTCALL
36
+ xsltLocaleStrcmp (void *locale,
37
+ const xmlChar *str1,
38
+ const xmlChar *str2);
39
+
40
+ #ifdef __cplusplus
41
+ }
42
+ #endif
43
+
44
+ #endif /* __XML_XSLTLOCALE_H__ */
.venv/lib/python3.12/site-packages/lxml/includes/libxslt/xsltutils.h ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Summary: set of utilities for the XSLT engine
3
+ * Description: interfaces for the utilities module of the XSLT engine.
4
+ * things like message handling, profiling, and other
5
+ * generally useful routines.
6
+ *
7
+ * Copy: See Copyright for the status of this software.
8
+ *
9
+ * Author: Daniel Veillard
10
+ */
11
+
12
+ #ifndef __XML_XSLTUTILS_H__
13
+ #define __XML_XSLTUTILS_H__
14
+
15
+ #include <libxslt/xsltconfig.h>
16
+ #include <libxml/xpath.h>
17
+ #include <libxml/dict.h>
18
+ #include <libxml/xmlerror.h>
19
+ #include "xsltexports.h"
20
+ #include "xsltInternals.h"
21
+
22
+ #ifdef __cplusplus
23
+ extern "C" {
24
+ #endif
25
+
26
+ /**
27
+ * XSLT_TODO:
28
+ *
29
+ * Macro to flag unimplemented blocks.
30
+ */
31
+ #define XSLT_TODO \
32
+ xsltGenericError(xsltGenericErrorContext, \
33
+ "Unimplemented block at %s:%d\n", \
34
+ __FILE__, __LINE__);
35
+
36
+ /**
37
+ * XSLT_STRANGE:
38
+ *
39
+ * Macro to flag that a problem was detected internally.
40
+ */
41
+ #define XSLT_STRANGE \
42
+ xsltGenericError(xsltGenericErrorContext, \
43
+ "Internal error at %s:%d\n", \
44
+ __FILE__, __LINE__);
45
+
46
+ /**
47
+ * IS_XSLT_ELEM:
48
+ *
49
+ * Checks that the element pertains to XSLT namespace.
50
+ */
51
+ #define IS_XSLT_ELEM(n) \
52
+ (((n) != NULL) && ((n)->type == XML_ELEMENT_NODE) && \
53
+ ((n)->ns != NULL) && (xmlStrEqual((n)->ns->href, XSLT_NAMESPACE)))
54
+
55
+ /**
56
+ * IS_XSLT_NAME:
57
+ *
58
+ * Checks the value of an element in XSLT namespace.
59
+ */
60
+ #define IS_XSLT_NAME(n, val) \
61
+ (xmlStrEqual((n)->name, (const xmlChar *) (val)))
62
+
63
+ /**
64
+ * IS_XSLT_REAL_NODE:
65
+ *
66
+ * Check that a node is a 'real' one: document, element, text or attribute.
67
+ */
68
+ #define IS_XSLT_REAL_NODE(n) \
69
+ (((n) != NULL) && \
70
+ (((n)->type == XML_ELEMENT_NODE) || \
71
+ ((n)->type == XML_TEXT_NODE) || \
72
+ ((n)->type == XML_CDATA_SECTION_NODE) || \
73
+ ((n)->type == XML_ATTRIBUTE_NODE) || \
74
+ ((n)->type == XML_DOCUMENT_NODE) || \
75
+ ((n)->type == XML_HTML_DOCUMENT_NODE) || \
76
+ ((n)->type == XML_COMMENT_NODE) || \
77
+ ((n)->type == XML_PI_NODE)))
78
+
79
+ /*
80
+ * Our own version of namespaced attributes lookup.
81
+ */
82
+ XSLTPUBFUN xmlChar * XSLTCALL
83
+ xsltGetNsProp (xmlNodePtr node,
84
+ const xmlChar *name,
85
+ const xmlChar *nameSpace);
86
+ XSLTPUBFUN const xmlChar * XSLTCALL
87
+ xsltGetCNsProp (xsltStylesheetPtr style,
88
+ xmlNodePtr node,
89
+ const xmlChar *name,
90
+ const xmlChar *nameSpace);
91
+ XSLTPUBFUN int XSLTCALL
92
+ xsltGetUTF8Char (const unsigned char *utf,
93
+ int *len);
94
+ #ifdef IN_LIBXSLT
95
+ /** DOC_DISABLE */
96
+ XSLTPUBFUN int XSLTCALL
97
+ xsltGetUTF8CharZ (const unsigned char *utf,
98
+ int *len);
99
+ /** DOC_ENABLE */
100
+ #endif
101
+
102
+ /*
103
+ * XSLT Debug Tracing Tracing Types
104
+ */
105
+ typedef enum {
106
+ XSLT_TRACE_ALL = -1,
107
+ XSLT_TRACE_NONE = 0,
108
+ XSLT_TRACE_COPY_TEXT = 1<<0,
109
+ XSLT_TRACE_PROCESS_NODE = 1<<1,
110
+ XSLT_TRACE_APPLY_TEMPLATE = 1<<2,
111
+ XSLT_TRACE_COPY = 1<<3,
112
+ XSLT_TRACE_COMMENT = 1<<4,
113
+ XSLT_TRACE_PI = 1<<5,
114
+ XSLT_TRACE_COPY_OF = 1<<6,
115
+ XSLT_TRACE_VALUE_OF = 1<<7,
116
+ XSLT_TRACE_CALL_TEMPLATE = 1<<8,
117
+ XSLT_TRACE_APPLY_TEMPLATES = 1<<9,
118
+ XSLT_TRACE_CHOOSE = 1<<10,
119
+ XSLT_TRACE_IF = 1<<11,
120
+ XSLT_TRACE_FOR_EACH = 1<<12,
121
+ XSLT_TRACE_STRIP_SPACES = 1<<13,
122
+ XSLT_TRACE_TEMPLATES = 1<<14,
123
+ XSLT_TRACE_KEYS = 1<<15,
124
+ XSLT_TRACE_VARIABLES = 1<<16
125
+ } xsltDebugTraceCodes;
126
+
127
+ /**
128
+ * XSLT_TRACE:
129
+ *
130
+ * Control the type of xsl debugtrace messages emitted.
131
+ */
132
+ #define XSLT_TRACE(ctxt,code,call) \
133
+ if (ctxt->traceCode && (*(ctxt->traceCode) & code)) \
134
+ call
135
+
136
+ XSLTPUBFUN void XSLTCALL
137
+ xsltDebugSetDefaultTrace(xsltDebugTraceCodes val);
138
+ XSLTPUBFUN xsltDebugTraceCodes XSLTCALL
139
+ xsltDebugGetDefaultTrace(void);
140
+
141
+ /*
142
+ * XSLT specific error and debug reporting functions.
143
+ */
144
+ XSLTPUBVAR xmlGenericErrorFunc xsltGenericError;
145
+ XSLTPUBVAR void *xsltGenericErrorContext;
146
+ XSLTPUBVAR xmlGenericErrorFunc xsltGenericDebug;
147
+ XSLTPUBVAR void *xsltGenericDebugContext;
148
+
149
+ XSLTPUBFUN void XSLTCALL
150
+ xsltPrintErrorContext (xsltTransformContextPtr ctxt,
151
+ xsltStylesheetPtr style,
152
+ xmlNodePtr node);
153
+ XSLTPUBFUN void XSLTCALL
154
+ xsltMessage (xsltTransformContextPtr ctxt,
155
+ xmlNodePtr node,
156
+ xmlNodePtr inst);
157
+ XSLTPUBFUN void XSLTCALL
158
+ xsltSetGenericErrorFunc (void *ctx,
159
+ xmlGenericErrorFunc handler);
160
+ XSLTPUBFUN void XSLTCALL
161
+ xsltSetGenericDebugFunc (void *ctx,
162
+ xmlGenericErrorFunc handler);
163
+ XSLTPUBFUN void XSLTCALL
164
+ xsltSetTransformErrorFunc (xsltTransformContextPtr ctxt,
165
+ void *ctx,
166
+ xmlGenericErrorFunc handler);
167
+ XSLTPUBFUN void XSLTCALL
168
+ xsltTransformError (xsltTransformContextPtr ctxt,
169
+ xsltStylesheetPtr style,
170
+ xmlNodePtr node,
171
+ const char *msg,
172
+ ...) LIBXSLT_ATTR_FORMAT(4,5);
173
+
174
+ XSLTPUBFUN int XSLTCALL
175
+ xsltSetCtxtParseOptions (xsltTransformContextPtr ctxt,
176
+ int options);
177
+ /*
178
+ * Sorting.
179
+ */
180
+
181
+ XSLTPUBFUN void XSLTCALL
182
+ xsltDocumentSortFunction (xmlNodeSetPtr list);
183
+ XSLTPUBFUN void XSLTCALL
184
+ xsltSetSortFunc (xsltSortFunc handler);
185
+ XSLTPUBFUN void XSLTCALL
186
+ xsltSetCtxtSortFunc (xsltTransformContextPtr ctxt,
187
+ xsltSortFunc handler);
188
+ XSLTPUBFUN void XSLTCALL
189
+ xsltSetCtxtLocaleHandlers (xsltTransformContextPtr ctxt,
190
+ xsltNewLocaleFunc newLocale,
191
+ xsltFreeLocaleFunc freeLocale,
192
+ xsltGenSortKeyFunc genSortKey);
193
+ XSLTPUBFUN void XSLTCALL
194
+ xsltDefaultSortFunction (xsltTransformContextPtr ctxt,
195
+ xmlNodePtr *sorts,
196
+ int nbsorts);
197
+ XSLTPUBFUN void XSLTCALL
198
+ xsltDoSortFunction (xsltTransformContextPtr ctxt,
199
+ xmlNodePtr * sorts,
200
+ int nbsorts);
201
+ XSLTPUBFUN xmlXPathObjectPtr * XSLTCALL
202
+ xsltComputeSortResult (xsltTransformContextPtr ctxt,
203
+ xmlNodePtr sort);
204
+
205
+ /*
206
+ * QNames handling.
207
+ */
208
+
209
+ XSLTPUBFUN const xmlChar * XSLTCALL
210
+ xsltSplitQName (xmlDictPtr dict,
211
+ const xmlChar *name,
212
+ const xmlChar **prefix);
213
+ XSLTPUBFUN const xmlChar * XSLTCALL
214
+ xsltGetQNameURI (xmlNodePtr node,
215
+ xmlChar **name);
216
+
217
+ XSLTPUBFUN const xmlChar * XSLTCALL
218
+ xsltGetQNameURI2 (xsltStylesheetPtr style,
219
+ xmlNodePtr node,
220
+ const xmlChar **name);
221
+
222
+ /*
223
+ * Output, reuse libxml I/O buffers.
224
+ */
225
+ XSLTPUBFUN int XSLTCALL
226
+ xsltSaveResultTo (xmlOutputBufferPtr buf,
227
+ xmlDocPtr result,
228
+ xsltStylesheetPtr style);
229
+ XSLTPUBFUN int XSLTCALL
230
+ xsltSaveResultToFilename (const char *URI,
231
+ xmlDocPtr result,
232
+ xsltStylesheetPtr style,
233
+ int compression);
234
+ XSLTPUBFUN int XSLTCALL
235
+ xsltSaveResultToFile (FILE *file,
236
+ xmlDocPtr result,
237
+ xsltStylesheetPtr style);
238
+ XSLTPUBFUN int XSLTCALL
239
+ xsltSaveResultToFd (int fd,
240
+ xmlDocPtr result,
241
+ xsltStylesheetPtr style);
242
+ XSLTPUBFUN int XSLTCALL
243
+ xsltSaveResultToString (xmlChar **doc_txt_ptr,
244
+ int * doc_txt_len,
245
+ xmlDocPtr result,
246
+ xsltStylesheetPtr style);
247
+
248
+ /*
249
+ * XPath interface
250
+ */
251
+ XSLTPUBFUN xmlXPathCompExprPtr XSLTCALL
252
+ xsltXPathCompile (xsltStylesheetPtr style,
253
+ const xmlChar *str);
254
+ XSLTPUBFUN xmlXPathCompExprPtr XSLTCALL
255
+ xsltXPathCompileFlags (xsltStylesheetPtr style,
256
+ const xmlChar *str,
257
+ int flags);
258
+
259
+ #ifdef IN_LIBXSLT
260
+ /** DOC_DISABLE */
261
+ #define XSLT_SOURCE_NODE_MASK 15u
262
+ #define XSLT_SOURCE_NODE_HAS_KEY 1u
263
+ #define XSLT_SOURCE_NODE_HAS_ID 2u
264
+ int
265
+ xsltGetSourceNodeFlags(xmlNodePtr node);
266
+ int
267
+ xsltSetSourceNodeFlags(xsltTransformContextPtr ctxt, xmlNodePtr node,
268
+ int flags);
269
+ int
270
+ xsltClearSourceNodeFlags(xmlNodePtr node, int flags);
271
+ void **
272
+ xsltGetPSVIPtr(xmlNodePtr cur);
273
+ /** DOC_ENABLE */
274
+ #endif
275
+
276
+ #ifdef WITH_PROFILER
277
+ /*
278
+ * Profiling.
279
+ */
280
+ XSLTPUBFUN void XSLTCALL
281
+ xsltSaveProfiling (xsltTransformContextPtr ctxt,
282
+ FILE *output);
283
+ XSLTPUBFUN xmlDocPtr XSLTCALL
284
+ xsltGetProfileInformation (xsltTransformContextPtr ctxt);
285
+
286
+ XSLTPUBFUN long XSLTCALL
287
+ xsltTimestamp (void);
288
+ XSLTPUBFUN void XSLTCALL
289
+ xsltCalibrateAdjust (long delta);
290
+ #endif
291
+
292
+ /**
293
+ * XSLT_TIMESTAMP_TICS_PER_SEC:
294
+ *
295
+ * Sampling precision for profiling
296
+ */
297
+ #define XSLT_TIMESTAMP_TICS_PER_SEC 100000l
298
+
299
+ /*
300
+ * Hooks for the debugger.
301
+ */
302
+
303
+ typedef enum {
304
+ XSLT_DEBUG_NONE = 0, /* no debugging allowed */
305
+ XSLT_DEBUG_INIT,
306
+ XSLT_DEBUG_STEP,
307
+ XSLT_DEBUG_STEPOUT,
308
+ XSLT_DEBUG_NEXT,
309
+ XSLT_DEBUG_STOP,
310
+ XSLT_DEBUG_CONT,
311
+ XSLT_DEBUG_RUN,
312
+ XSLT_DEBUG_RUN_RESTART,
313
+ XSLT_DEBUG_QUIT
314
+ } xsltDebugStatusCodes;
315
+
316
+ XSLTPUBVAR int xslDebugStatus;
317
+
318
+ typedef void (*xsltHandleDebuggerCallback) (xmlNodePtr cur, xmlNodePtr node,
319
+ xsltTemplatePtr templ, xsltTransformContextPtr ctxt);
320
+ typedef int (*xsltAddCallCallback) (xsltTemplatePtr templ, xmlNodePtr source);
321
+ typedef void (*xsltDropCallCallback) (void);
322
+
323
+ XSLTPUBFUN int XSLTCALL
324
+ xsltGetDebuggerStatus (void);
325
+ #ifdef WITH_DEBUGGER
326
+ XSLTPUBFUN void XSLTCALL
327
+ xsltSetDebuggerStatus (int value);
328
+ XSLTPUBFUN int XSLTCALL
329
+ xsltSetDebuggerCallbacks (int no, void *block);
330
+ XSLTPUBFUN int XSLTCALL
331
+ xslAddCall (xsltTemplatePtr templ,
332
+ xmlNodePtr source);
333
+ XSLTPUBFUN void XSLTCALL
334
+ xslDropCall (void);
335
+ #endif
336
+
337
+ #ifdef __cplusplus
338
+ }
339
+ #endif
340
+
341
+ #endif /* __XML_XSLTUTILS_H__ */
342
+
343
+
.venv/lib/python3.12/site-packages/lxml/includes/lxml-version.h ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #ifndef LXML_VERSION_STRING
2
+ #define LXML_VERSION_STRING "6.1.3"
3
+ #endif
.venv/lib/python3.12/site-packages/lxml/includes/relaxng.pxd ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes.tree cimport xmlDoc
2
+ from lxml.includes.xmlerror cimport xmlStructuredErrorFunc
3
+
4
+ cdef extern from "libxml/relaxng.h" nogil:
5
+ ctypedef struct xmlRelaxNG
6
+ ctypedef struct xmlRelaxNGParserCtxt
7
+
8
+ ctypedef struct xmlRelaxNGValidCtxt
9
+
10
+ ctypedef enum xmlRelaxNGValidErr:
11
+ XML_RELAXNG_OK = 0
12
+ XML_RELAXNG_ERR_MEMORY = 1
13
+ XML_RELAXNG_ERR_TYPE = 2
14
+ XML_RELAXNG_ERR_TYPEVAL = 3
15
+ XML_RELAXNG_ERR_DUPID = 4
16
+ XML_RELAXNG_ERR_TYPECMP = 5
17
+ XML_RELAXNG_ERR_NOSTATE = 6
18
+ XML_RELAXNG_ERR_NODEFINE = 7
19
+ XML_RELAXNG_ERR_LISTEXTRA = 8
20
+ XML_RELAXNG_ERR_LISTEMPTY = 9
21
+ XML_RELAXNG_ERR_INTERNODATA = 10
22
+ XML_RELAXNG_ERR_INTERSEQ = 11
23
+ XML_RELAXNG_ERR_INTEREXTRA = 12
24
+ XML_RELAXNG_ERR_ELEMNAME = 13
25
+ XML_RELAXNG_ERR_ATTRNAME = 14
26
+ XML_RELAXNG_ERR_ELEMNONS = 15
27
+ XML_RELAXNG_ERR_ATTRNONS = 16
28
+ XML_RELAXNG_ERR_ELEMWRONGNS = 17
29
+ XML_RELAXNG_ERR_ATTRWRONGNS = 18
30
+ XML_RELAXNG_ERR_ELEMEXTRANS = 19
31
+ XML_RELAXNG_ERR_ATTREXTRANS = 20
32
+ XML_RELAXNG_ERR_ELEMNOTEMPTY = 21
33
+ XML_RELAXNG_ERR_NOELEM = 22
34
+ XML_RELAXNG_ERR_NOTELEM = 23
35
+ XML_RELAXNG_ERR_ATTRVALID = 24
36
+ XML_RELAXNG_ERR_CONTENTVALID = 25
37
+ XML_RELAXNG_ERR_EXTRACONTENT = 26
38
+ XML_RELAXNG_ERR_INVALIDATTR = 27
39
+ XML_RELAXNG_ERR_DATAELEM = 28
40
+ XML_RELAXNG_ERR_VALELEM = 29
41
+ XML_RELAXNG_ERR_LISTELEM = 30
42
+ XML_RELAXNG_ERR_DATATYPE = 31
43
+ XML_RELAXNG_ERR_VALUE = 32
44
+ XML_RELAXNG_ERR_LIST = 33
45
+ XML_RELAXNG_ERR_NOGRAMMAR = 34
46
+ XML_RELAXNG_ERR_EXTRADATA = 35
47
+ XML_RELAXNG_ERR_LACKDATA = 36
48
+ XML_RELAXNG_ERR_INTERNAL = 37
49
+ XML_RELAXNG_ERR_ELEMWRONG = 38
50
+ XML_RELAXNG_ERR_TEXTWRONG = 39
51
+
52
+ cdef xmlRelaxNGValidCtxt* xmlRelaxNGNewValidCtxt(xmlRelaxNG* schema)
53
+ cdef int xmlRelaxNGValidateDoc(xmlRelaxNGValidCtxt* ctxt, xmlDoc* doc)
54
+ cdef xmlRelaxNG* xmlRelaxNGParse(xmlRelaxNGParserCtxt* ctxt)
55
+ cdef xmlRelaxNGParserCtxt* xmlRelaxNGNewParserCtxt(char* URL)
56
+ cdef xmlRelaxNGParserCtxt* xmlRelaxNGNewDocParserCtxt(xmlDoc* doc)
57
+ cdef void xmlRelaxNGFree(xmlRelaxNG* schema)
58
+ cdef void xmlRelaxNGFreeParserCtxt(xmlRelaxNGParserCtxt* ctxt)
59
+ cdef void xmlRelaxNGFreeValidCtxt(xmlRelaxNGValidCtxt* ctxt)
60
+
61
+ cdef void xmlRelaxNGSetValidStructuredErrors(
62
+ xmlRelaxNGValidCtxt* ctxt, xmlStructuredErrorFunc serror, void *ctx)
63
+ cdef void xmlRelaxNGSetParserStructuredErrors(
64
+ xmlRelaxNGParserCtxt* ctxt, xmlStructuredErrorFunc serror, void *ctx)
.venv/lib/python3.12/site-packages/lxml/includes/schematron.pxd ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes cimport xmlerror
2
+ from lxml.includes.tree cimport xmlDoc
3
+
4
+ cdef extern from "libxml/schematron.h" nogil:
5
+ ctypedef struct xmlSchematron
6
+ ctypedef struct xmlSchematronParserCtxt
7
+ ctypedef struct xmlSchematronValidCtxt
8
+
9
+ ctypedef enum xmlSchematronValidOptions:
10
+ XML_SCHEMATRON_OUT_QUIET = 1 # quiet no report
11
+ XML_SCHEMATRON_OUT_TEXT = 2 # build a textual report
12
+ XML_SCHEMATRON_OUT_XML = 4 # output SVRL
13
+ XML_SCHEMATRON_OUT_ERROR = 8 # output via xmlStructuredErrorFunc
14
+ XML_SCHEMATRON_OUT_FILE = 256 # output to a file descriptor
15
+ XML_SCHEMATRON_OUT_BUFFER = 512 # output to a buffer
16
+ XML_SCHEMATRON_OUT_IO = 1024 # output to I/O mechanism
17
+
18
+ cdef xmlSchematronParserCtxt* xmlSchematronNewDocParserCtxt(
19
+ xmlDoc* doc)
20
+ cdef xmlSchematronParserCtxt* xmlSchematronNewParserCtxt(
21
+ char* filename) nogil
22
+ cdef xmlSchematronValidCtxt* xmlSchematronNewValidCtxt(
23
+ xmlSchematron* schema, int options)
24
+
25
+ cdef xmlSchematron* xmlSchematronParse(xmlSchematronParserCtxt* ctxt)
26
+ cdef int xmlSchematronValidateDoc(xmlSchematronValidCtxt* ctxt,
27
+ xmlDoc* instance)
28
+
29
+ cdef void xmlSchematronFreeParserCtxt(xmlSchematronParserCtxt* ctxt)
30
+ cdef void xmlSchematronFreeValidCtxt(xmlSchematronValidCtxt* ctxt)
31
+ cdef void xmlSchematronFree(xmlSchematron* schema)
32
+ cdef void xmlSchematronSetValidStructuredErrors(
33
+ xmlSchematronValidCtxt* ctxt,
34
+ xmlerror.xmlStructuredErrorFunc error_func, void *data)
.venv/lib/python3.12/site-packages/lxml/includes/tree.pxd ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libc cimport stdio
2
+ from libc.string cimport const_char, const_uchar
3
+
4
+ cdef extern from "lxml-version.h":
5
+ # deprecated declaration, use etreepublic.pxd instead
6
+ cdef char* LXML_VERSION_STRING
7
+
8
+ cdef extern from "libxml/xmlversion.h":
9
+ const char* xmlParserVersion
10
+ int LIBXML_VERSION
11
+
12
+
13
+ cdef extern from "libxml/xmlstring.h" nogil:
14
+ ctypedef unsigned char xmlChar
15
+ ctypedef const xmlChar const_xmlChar "const xmlChar"
16
+ cdef int xmlStrlen(const_xmlChar* str)
17
+ cdef xmlChar* xmlStrdup(const_xmlChar* cur)
18
+ cdef int xmlStrncmp(const_xmlChar* str1, const_xmlChar* str2, int length)
19
+ cdef int xmlStrcmp(const_xmlChar* str1, const_xmlChar* str2)
20
+ cdef int xmlStrcasecmp(const xmlChar *str1, const xmlChar *str2)
21
+ cdef const_xmlChar* xmlStrstr(const_xmlChar* str1, const_xmlChar* str2)
22
+ cdef const_xmlChar* xmlStrchr(const_xmlChar* str1, xmlChar ch)
23
+ cdef const_xmlChar* _xcstr "(const xmlChar*)PyBytes_AS_STRING" (object s)
24
+
25
+ cdef extern from "libxml/encoding.h" nogil:
26
+ ctypedef enum xmlCharEncoding:
27
+ XML_CHAR_ENCODING_ERROR = -1 # No char encoding detected
28
+ XML_CHAR_ENCODING_NONE = 0 # No char encoding detected
29
+ XML_CHAR_ENCODING_UTF8 = 1 # UTF-8
30
+ XML_CHAR_ENCODING_UTF16LE = 2 # UTF-16 little endian
31
+ XML_CHAR_ENCODING_UTF16BE = 3 # UTF-16 big endian
32
+ XML_CHAR_ENCODING_UCS4LE = 4 # UCS-4 little endian
33
+ XML_CHAR_ENCODING_UCS4BE = 5 # UCS-4 big endian
34
+ XML_CHAR_ENCODING_EBCDIC = 6 # EBCDIC uh!
35
+ XML_CHAR_ENCODING_UCS4_2143 = 7 # UCS-4 unusual ordering
36
+ XML_CHAR_ENCODING_UCS4_3412 = 8 # UCS-4 unusual ordering
37
+ XML_CHAR_ENCODING_UCS2 = 9 # UCS-2
38
+ XML_CHAR_ENCODING_8859_1 = 10 # ISO-8859-1 ISO Latin 1
39
+ XML_CHAR_ENCODING_8859_2 = 11 # ISO-8859-2 ISO Latin 2
40
+ XML_CHAR_ENCODING_8859_3 = 12 # ISO-8859-3
41
+ XML_CHAR_ENCODING_8859_4 = 13 # ISO-8859-4
42
+ XML_CHAR_ENCODING_8859_5 = 14 # ISO-8859-5
43
+ XML_CHAR_ENCODING_8859_6 = 15 # ISO-8859-6
44
+ XML_CHAR_ENCODING_8859_7 = 16 # ISO-8859-7
45
+ XML_CHAR_ENCODING_8859_8 = 17 # ISO-8859-8
46
+ XML_CHAR_ENCODING_8859_9 = 18 # ISO-8859-9
47
+ XML_CHAR_ENCODING_2022_JP = 19 # ISO-2022-JP
48
+ XML_CHAR_ENCODING_SHIFT_JIS = 20 # Shift_JIS
49
+ XML_CHAR_ENCODING_EUC_JP = 21 # EUC-JP
50
+ XML_CHAR_ENCODING_ASCII = 22 # pure ASCII
51
+
52
+ ctypedef struct xmlCharEncodingHandler:
53
+ char* name
54
+
55
+ cdef xmlCharEncodingHandler* xmlFindCharEncodingHandler(char* name)
56
+ cdef xmlCharEncodingHandler* xmlGetCharEncodingHandler(
57
+ xmlCharEncoding enc)
58
+ cdef int xmlCharEncCloseFunc(xmlCharEncodingHandler* handler)
59
+ cdef xmlCharEncoding xmlDetectCharEncoding(const_xmlChar* text, int len)
60
+ cdef const_char* xmlGetCharEncodingName(xmlCharEncoding enc)
61
+ cdef xmlCharEncoding xmlParseCharEncoding(char* name)
62
+ ctypedef int (*xmlCharEncodingOutputFunc)(
63
+ unsigned char *out_buf, int *outlen, const_uchar *in_buf, int *inlen)
64
+
65
+ cdef extern from "libxml/chvalid.h" nogil:
66
+ cdef int xmlIsChar_ch(char c)
67
+ cdef int xmlIsCharQ(int ch)
68
+
69
+ cdef extern from "libxml/hash.h":
70
+ ctypedef struct xmlHashTable
71
+ ctypedef void (*xmlHashScanner)(void* payload, void* data, const_xmlChar* name) noexcept # may require GIL!
72
+ void xmlHashScan(xmlHashTable* table, xmlHashScanner f, void* data) nogil
73
+ void* xmlHashLookup(xmlHashTable* table, const_xmlChar* name) nogil
74
+ ctypedef void (*xmlHashDeallocator)(void *payload, xmlChar *name) noexcept
75
+ cdef xmlHashTable* xmlHashCreate(int size) nogil
76
+ cdef xmlHashTable* xmlHashCreateDict(int size, xmlDict *dict) nogil
77
+ cdef int xmlHashSize(xmlHashTable* table) nogil
78
+ cdef void xmlHashFree(xmlHashTable* table, xmlHashDeallocator f) nogil
79
+
80
+ cdef extern from * nogil: # actually "libxml/dict.h"
81
+ # libxml/dict.h appears to be broken to include in C
82
+ ctypedef struct xmlDict
83
+ cdef const_xmlChar* xmlDictLookup(xmlDict* dict, const_xmlChar* name, int len)
84
+ cdef const_xmlChar* xmlDictExists(xmlDict* dict, const_xmlChar* name, int len)
85
+ cdef int xmlDictOwns(xmlDict* dict, const_xmlChar* name)
86
+ cdef size_t xmlDictSize(xmlDict* dict)
87
+
88
+ cdef extern from "libxml/tree.h" nogil:
89
+ ctypedef struct xmlDoc
90
+ ctypedef struct xmlAttr
91
+ ctypedef struct xmlNotationTable
92
+
93
+ ctypedef enum xmlElementType:
94
+ XML_ELEMENT_NODE= 1
95
+ XML_ATTRIBUTE_NODE= 2
96
+ XML_TEXT_NODE= 3
97
+ XML_CDATA_SECTION_NODE= 4
98
+ XML_ENTITY_REF_NODE= 5
99
+ XML_ENTITY_NODE= 6
100
+ XML_PI_NODE= 7
101
+ XML_COMMENT_NODE= 8
102
+ XML_DOCUMENT_NODE= 9
103
+ XML_DOCUMENT_TYPE_NODE= 10
104
+ XML_DOCUMENT_FRAG_NODE= 11
105
+ XML_NOTATION_NODE= 12
106
+ XML_HTML_DOCUMENT_NODE= 13
107
+ XML_DTD_NODE= 14
108
+ XML_ELEMENT_DECL= 15
109
+ XML_ATTRIBUTE_DECL= 16
110
+ XML_ENTITY_DECL= 17
111
+ XML_NAMESPACE_DECL= 18
112
+ XML_XINCLUDE_START= 19
113
+ XML_XINCLUDE_END= 20
114
+
115
+ ctypedef enum xmlElementTypeVal:
116
+ XML_ELEMENT_TYPE_UNDEFINED= 0
117
+ XML_ELEMENT_TYPE_EMPTY= 1
118
+ XML_ELEMENT_TYPE_ANY= 2
119
+ XML_ELEMENT_TYPE_MIXED= 3
120
+ XML_ELEMENT_TYPE_ELEMENT= 4
121
+
122
+ ctypedef enum xmlElementContentType:
123
+ XML_ELEMENT_CONTENT_PCDATA= 1
124
+ XML_ELEMENT_CONTENT_ELEMENT= 2
125
+ XML_ELEMENT_CONTENT_SEQ= 3
126
+ XML_ELEMENT_CONTENT_OR= 4
127
+
128
+ ctypedef enum xmlElementContentOccur:
129
+ XML_ELEMENT_CONTENT_ONCE= 1
130
+ XML_ELEMENT_CONTENT_OPT= 2
131
+ XML_ELEMENT_CONTENT_MULT= 3
132
+ XML_ELEMENT_CONTENT_PLUS= 4
133
+
134
+ ctypedef enum xmlAttributeType:
135
+ XML_ATTRIBUTE_CDATA = 1
136
+ XML_ATTRIBUTE_ID= 2
137
+ XML_ATTRIBUTE_IDREF= 3
138
+ XML_ATTRIBUTE_IDREFS= 4
139
+ XML_ATTRIBUTE_ENTITY= 5
140
+ XML_ATTRIBUTE_ENTITIES= 6
141
+ XML_ATTRIBUTE_NMTOKEN= 7
142
+ XML_ATTRIBUTE_NMTOKENS= 8
143
+ XML_ATTRIBUTE_ENUMERATION= 9
144
+ XML_ATTRIBUTE_NOTATION= 10
145
+
146
+ ctypedef enum xmlAttributeDefault:
147
+ XML_ATTRIBUTE_NONE= 1
148
+ XML_ATTRIBUTE_REQUIRED= 2
149
+ XML_ATTRIBUTE_IMPLIED= 3
150
+ XML_ATTRIBUTE_FIXED= 4
151
+
152
+ ctypedef enum xmlEntityType:
153
+ XML_INTERNAL_GENERAL_ENTITY= 1
154
+ XML_EXTERNAL_GENERAL_PARSED_ENTITY= 2
155
+ XML_EXTERNAL_GENERAL_UNPARSED_ENTITY= 3
156
+ XML_INTERNAL_PARAMETER_ENTITY= 4
157
+ XML_EXTERNAL_PARAMETER_ENTITY= 5
158
+ XML_INTERNAL_PREDEFINED_ENTITY= 6
159
+
160
+ ctypedef enum xmlDocProperties:
161
+ XML_DOC_WELLFORMED = 1 # /* document is XML well formed */
162
+ XML_DOC_NSVALID = 2 # /* document is Namespace valid */
163
+ XML_DOC_OLD10 = 4 # /* parsed with old XML-1.0 parser */
164
+ XML_DOC_DTDVALID = 8 # /* DTD validation was successful */
165
+ XML_DOC_XINCLUDE = 16 # /* XInclude substitution was done */
166
+ XML_DOC_USERBUILT = 32 # /* Document was built using the API
167
+ # and not by parsing an instance */
168
+ XML_DOC_INTERNAL = 64 # /* built for internal processing */
169
+ XML_DOC_HTML = 128 # /* parsed or built HTML document */
170
+
171
+ ctypedef struct xmlNs:
172
+ const_xmlChar* href
173
+ const_xmlChar* prefix
174
+ xmlNs* next
175
+
176
+ ctypedef struct xmlNode:
177
+ void* _private
178
+ xmlElementType type
179
+ const_xmlChar* name
180
+ xmlNode* children
181
+ xmlNode* last
182
+ xmlNode* parent
183
+ xmlNode* next
184
+ xmlNode* prev
185
+ xmlDoc* doc
186
+ xmlChar* content
187
+ xmlAttr* properties
188
+ xmlNs* ns
189
+ xmlNs* nsDef
190
+ unsigned short line
191
+
192
+ ctypedef struct xmlElementContent:
193
+ xmlElementContentType type
194
+ xmlElementContentOccur ocur
195
+ const_xmlChar *name
196
+ xmlElementContent *c1
197
+ xmlElementContent *c2
198
+ xmlElementContent *parent
199
+ const_xmlChar *prefix
200
+
201
+ ctypedef struct xmlEnumeration:
202
+ xmlEnumeration *next
203
+ const_xmlChar *name
204
+
205
+ ctypedef struct xmlAttribute:
206
+ void* _private
207
+ xmlElementType type
208
+ const_xmlChar* name
209
+ xmlNode* children
210
+ xmlNode* last
211
+ xmlDtd* parent
212
+ xmlNode* next
213
+ xmlNode* prev
214
+ xmlDoc* doc
215
+ xmlAttribute* nexth
216
+ xmlAttributeType atype
217
+ xmlAttributeDefault def_ "def"
218
+ const_xmlChar* defaultValue
219
+ xmlEnumeration* tree
220
+ const_xmlChar* prefix
221
+ const_xmlChar* elem
222
+
223
+ ctypedef struct xmlElement:
224
+ void* _private
225
+ xmlElementType type
226
+ const_xmlChar* name
227
+ xmlNode* children
228
+ xmlNode* last
229
+ xmlNode* parent
230
+ xmlNode* next
231
+ xmlNode* prev
232
+ xmlDoc* doc
233
+ xmlElementTypeVal etype
234
+ xmlElementContent* content
235
+ xmlAttribute* attributes
236
+ const_xmlChar* prefix
237
+ void *contModel
238
+
239
+ ctypedef struct xmlEntity:
240
+ void* _private
241
+ xmlElementType type
242
+ const_xmlChar* name
243
+ xmlNode* children
244
+ xmlNode* last
245
+ xmlDtd* parent
246
+ xmlNode* next
247
+ xmlNode* prev
248
+ xmlDoc* doc
249
+ xmlChar* orig
250
+ xmlChar* content
251
+ int length
252
+ xmlEntityType etype
253
+ const_xmlChar* ExternalID
254
+ const_xmlChar* SystemID
255
+ xmlEntity* nexte
256
+ const_xmlChar* URI
257
+ int owner
258
+ int checked
259
+
260
+ ctypedef struct xmlDtd:
261
+ const_xmlChar* name
262
+ const_xmlChar* ExternalID
263
+ const_xmlChar* SystemID
264
+ void* notations
265
+ void* entities
266
+ void* pentities
267
+ void* attributes
268
+ void* elements
269
+ xmlNode* children
270
+ xmlNode* last
271
+ xmlDoc* doc
272
+
273
+ ctypedef struct xmlDoc:
274
+ xmlElementType type
275
+ char* name
276
+ xmlNode* children
277
+ xmlNode* last
278
+ xmlNode* parent
279
+ xmlNode* next
280
+ xmlNode* prev
281
+ xmlDoc* doc
282
+ xmlDict* dict
283
+ xmlHashTable* ids
284
+ int standalone
285
+ const_xmlChar* version
286
+ const_xmlChar* encoding
287
+ const_xmlChar* URL
288
+ void* _private
289
+ xmlDtd* intSubset
290
+ xmlDtd* extSubset
291
+ int properties
292
+
293
+ ctypedef struct xmlAttr:
294
+ void* _private
295
+ xmlElementType type
296
+ const_xmlChar* name
297
+ xmlNode* children
298
+ xmlNode* last
299
+ xmlNode* parent
300
+ xmlAttr* next
301
+ xmlAttr* prev
302
+ xmlDoc* doc
303
+ xmlNs* ns
304
+ xmlAttributeType atype
305
+
306
+ ctypedef struct xmlID:
307
+ const_xmlChar* value
308
+ const_xmlChar* name
309
+ xmlAttr* attr
310
+ xmlDoc* doc
311
+
312
+ ctypedef struct xmlBuffer
313
+
314
+ ctypedef struct xmlBuf # new in libxml2 2.9
315
+
316
+ ctypedef struct xmlOutputBuffer:
317
+ xmlBuf* buffer
318
+ xmlBuf* conv
319
+ int error
320
+
321
+ const_xmlChar* XML_XML_NAMESPACE
322
+
323
+ cdef void xmlFreeDoc(xmlDoc* cur)
324
+ cdef void xmlFreeDtd(xmlDtd* cur)
325
+ cdef void xmlFreeNode(xmlNode* cur)
326
+ cdef void xmlFreeNsList(xmlNs* ns)
327
+ cdef void xmlFreeNs(xmlNs* ns)
328
+ cdef void xmlFree(void* buf)
329
+
330
+ cdef xmlNode* xmlNewNode(xmlNs* ns, const_xmlChar* name)
331
+ cdef xmlNode* xmlNewDocText(xmlDoc* doc, const_xmlChar* content)
332
+ cdef xmlNode* xmlNewDocComment(xmlDoc* doc, const_xmlChar* content)
333
+ cdef xmlNode* xmlNewDocPI(xmlDoc* doc, const_xmlChar* name, const_xmlChar* content)
334
+ cdef xmlNode* xmlNewReference(xmlDoc* doc, const_xmlChar* name)
335
+ cdef xmlNode* xmlNewCDataBlock(xmlDoc* doc, const_xmlChar* text, int len)
336
+ cdef xmlNs* xmlNewNs(xmlNode* node, const_xmlChar* href, const_xmlChar* prefix)
337
+ cdef xmlNode* xmlAddChild(xmlNode* parent, xmlNode* cur)
338
+ cdef xmlNode* xmlReplaceNode(xmlNode* old, xmlNode* cur)
339
+ cdef xmlNode* xmlAddPrevSibling(xmlNode* cur, xmlNode* elem)
340
+ cdef xmlNode* xmlAddNextSibling(xmlNode* cur, xmlNode* elem)
341
+ cdef xmlNode* xmlNewDocNode(xmlDoc* doc, xmlNs* ns,
342
+ const_xmlChar* name, const_xmlChar* content)
343
+ cdef xmlDoc* xmlNewDoc(const_xmlChar* version)
344
+ cdef xmlAttr* xmlNewProp(xmlNode* node, const_xmlChar* name, const_xmlChar* value)
345
+ cdef xmlAttr* xmlNewNsProp(xmlNode* node, xmlNs* ns,
346
+ const_xmlChar* name, const_xmlChar* value)
347
+ cdef xmlChar* xmlGetNoNsProp(xmlNode* node, const_xmlChar* name)
348
+ cdef xmlChar* xmlGetNsProp(xmlNode* node, const_xmlChar* name, const_xmlChar* nameSpace)
349
+ cdef void xmlSetNs(xmlNode* node, xmlNs* ns)
350
+ cdef xmlAttr* xmlSetProp(xmlNode* node, const_xmlChar* name, const_xmlChar* value)
351
+ cdef xmlAttr* xmlSetNsProp(xmlNode* node, xmlNs* ns,
352
+ const_xmlChar* name, const_xmlChar* value)
353
+ cdef int xmlRemoveID(xmlDoc* doc, xmlAttr* cur)
354
+ cdef int xmlRemoveProp(xmlAttr* cur)
355
+ cdef void xmlFreePropList(xmlAttr* cur)
356
+ cdef xmlChar* xmlGetNodePath(xmlNode* node)
357
+ cdef void xmlDocDumpMemory(xmlDoc* cur, char** mem, int* size)
358
+ cdef void xmlDocDumpMemoryEnc(xmlDoc* cur, char** mem, int* size,
359
+ char* encoding)
360
+ cdef int xmlSaveFileTo(xmlOutputBuffer* out, xmlDoc* cur,
361
+ char* encoding)
362
+
363
+ cdef void xmlUnlinkNode(xmlNode* cur)
364
+ cdef xmlNode* xmlDocSetRootElement(xmlDoc* doc, xmlNode* root)
365
+ cdef xmlNode* xmlDocGetRootElement(xmlDoc* doc)
366
+ cdef void xmlSetTreeDoc(xmlNode* tree, xmlDoc* doc)
367
+ cdef xmlAttr* xmlHasProp(xmlNode* node, const_xmlChar* name)
368
+ cdef xmlAttr* xmlHasNsProp(xmlNode* node, const_xmlChar* name, const_xmlChar* nameSpace)
369
+ cdef xmlChar* xmlNodeGetContent(xmlNode* cur)
370
+ cdef int xmlNodeBufGetContent(xmlBuffer* buffer, xmlNode* cur)
371
+ cdef xmlNs* xmlSearchNs(xmlDoc* doc, xmlNode* node, const_xmlChar* prefix)
372
+ cdef xmlNs* xmlSearchNsByHref(xmlDoc* doc, xmlNode* node, const_xmlChar* href)
373
+ cdef int xmlIsBlankNode(xmlNode* node)
374
+ cdef long xmlGetLineNo(xmlNode* node)
375
+ cdef void xmlElemDump(stdio.FILE* f, xmlDoc* doc, xmlNode* cur)
376
+ cdef void xmlNodeDumpOutput(xmlOutputBuffer* buf,
377
+ xmlDoc* doc, xmlNode* cur, int level,
378
+ int format, const_char* encoding)
379
+ cdef void xmlBufAttrSerializeTxtContent(xmlOutputBuffer *buf, xmlDoc *doc,
380
+ xmlAttr *attr, const_xmlChar *string)
381
+ cdef void xmlNodeSetName(xmlNode* cur, const_xmlChar* name)
382
+ cdef void xmlNodeSetContent(xmlNode* cur, const_xmlChar* content)
383
+ cdef xmlDtd* xmlCopyDtd(xmlDtd* dtd)
384
+ cdef xmlDoc* xmlCopyDoc(xmlDoc* doc, int recursive)
385
+ cdef xmlNode* xmlCopyNode(xmlNode* node, int extended)
386
+ cdef xmlNode* xmlDocCopyNode(xmlNode* node, xmlDoc* doc, int extended)
387
+ cdef int xmlReconciliateNs(xmlDoc* doc, xmlNode* tree)
388
+ cdef xmlNs* xmlNewReconciliedNs(xmlDoc* doc, xmlNode* tree, xmlNs* ns)
389
+ cdef xmlBuffer* xmlBufferCreate()
390
+ cdef void xmlBufferWriteChar(xmlBuffer* buf, char* string)
391
+ cdef void xmlBufferFree(xmlBuffer* buf)
392
+ cdef const_xmlChar* xmlBufferContent(xmlBuffer* buf)
393
+ cdef int xmlBufferLength(xmlBuffer* buf)
394
+ cdef const_xmlChar* xmlBufContent(xmlBuf* buf) # new in libxml2 2.9
395
+ cdef size_t xmlBufUse(xmlBuf* buf) # new in libxml2 2.9
396
+ cdef int xmlKeepBlanksDefault(int val)
397
+ cdef xmlChar* xmlNodeGetBase(xmlDoc* doc, xmlNode* node)
398
+ cdef xmlDtd* xmlCreateIntSubset(xmlDoc* doc, const_xmlChar* name,
399
+ const_xmlChar* ExternalID, const_xmlChar* SystemID)
400
+ cdef void xmlNodeSetBase(xmlNode* node, const_xmlChar* uri)
401
+ cdef int xmlValidateNCName(const_xmlChar* value, int space)
402
+
403
+ cdef extern from "libxml/uri.h" nogil:
404
+ cdef const_xmlChar* xmlBuildURI(const_xmlChar* href, const_xmlChar* base)
405
+
406
+ cdef extern from "libxml/HTMLtree.h" nogil:
407
+ cdef void htmlNodeDumpFormatOutput(xmlOutputBuffer* buf,
408
+ xmlDoc* doc, xmlNode* cur,
409
+ char* encoding, int format)
410
+ cdef xmlDoc* htmlNewDoc(const_xmlChar* uri, const_xmlChar* externalID)
411
+
412
+ cdef extern from "libxml/valid.h" nogil:
413
+ cdef xmlAttr* xmlGetID(xmlDoc* doc, const_xmlChar* ID)
414
+ cdef void xmlDumpNotationTable(xmlBuffer* buffer,
415
+ xmlNotationTable* table)
416
+ cdef int xmlValidateNameValue(const_xmlChar* value)
417
+
418
+ cdef extern from "libxml/xmlIO.h":
419
+ cdef int xmlOutputBufferWrite(xmlOutputBuffer* out,
420
+ int len, const_char* str) nogil
421
+ cdef int xmlOutputBufferWriteString(xmlOutputBuffer* out, const_char* str) nogil
422
+ cdef int xmlOutputBufferWriteEscape(xmlOutputBuffer* out,
423
+ const_xmlChar* str,
424
+ xmlCharEncodingOutputFunc escapefunc) nogil
425
+ cdef int xmlOutputBufferFlush(xmlOutputBuffer* out) nogil
426
+ cdef int xmlOutputBufferClose(xmlOutputBuffer* out) nogil
427
+
428
+ ctypedef int (*xmlInputReadCallback)(void* context,
429
+ char* buffer, int len) noexcept nogil
430
+ ctypedef int (*xmlInputCloseCallback)(void* context) noexcept nogil
431
+
432
+ ctypedef int (*xmlOutputWriteCallback)(void* context,
433
+ char* buffer, int len) noexcept
434
+ ctypedef int (*xmlOutputCloseCallback)(void* context) noexcept
435
+
436
+ cdef xmlOutputBuffer* xmlAllocOutputBuffer(
437
+ xmlCharEncodingHandler* encoder) nogil
438
+ cdef xmlOutputBuffer* xmlOutputBufferCreateIO(
439
+ xmlOutputWriteCallback iowrite,
440
+ xmlOutputCloseCallback ioclose,
441
+ void * ioctx,
442
+ xmlCharEncodingHandler* encoder) nogil
443
+ cdef xmlOutputBuffer* xmlOutputBufferCreateFile(
444
+ stdio.FILE* file, xmlCharEncodingHandler* encoder) nogil
445
+ cdef xmlOutputBuffer* xmlOutputBufferCreateFilename(
446
+ char* URI, xmlCharEncodingHandler* encoder, int compression) nogil
447
+
448
+ cdef extern from "libxml/xmlsave.h" nogil:
449
+ ctypedef struct xmlSaveCtxt
450
+
451
+ ctypedef enum xmlSaveOption:
452
+ XML_SAVE_FORMAT = 1 # format save output (2.6.17)
453
+ XML_SAVE_NO_DECL = 2 # drop the xml declaration (2.6.21)
454
+ XML_SAVE_NO_EMPTY = 4 # no empty tags (2.6.22)
455
+ XML_SAVE_NO_XHTML = 8 # disable XHTML1 specific rules (2.6.22)
456
+ XML_SAVE_XHTML = 16 # force XHTML1 specific rules (2.7.2)
457
+ XML_SAVE_AS_XML = 32 # force XML serialization on HTML doc (2.7.2)
458
+ XML_SAVE_AS_HTML = 64 # force HTML serialization on XML doc (2.7.2)
459
+
460
+ cdef xmlSaveCtxt* xmlSaveToFilename(char* filename, char* encoding,
461
+ int options)
462
+ cdef xmlSaveCtxt* xmlSaveToBuffer(xmlBuffer* buffer, char* encoding,
463
+ int options) # libxml2 2.6.23
464
+ cdef long xmlSaveDoc(xmlSaveCtxt* ctxt, xmlDoc* doc)
465
+ cdef long xmlSaveTree(xmlSaveCtxt* ctxt, xmlNode* node)
466
+ cdef int xmlSaveClose(xmlSaveCtxt* ctxt)
467
+ cdef int xmlSaveFlush(xmlSaveCtxt* ctxt)
468
+ cdef int xmlSaveSetAttrEscape(xmlSaveCtxt* ctxt, void* escape_func)
469
+ cdef int xmlSaveSetEscape(xmlSaveCtxt* ctxt, void* escape_func)
470
+
471
+ cdef extern from "libxml/globals.h" nogil:
472
+ cdef int xmlThrDefKeepBlanksDefaultValue(int onoff)
473
+ cdef int xmlThrDefLineNumbersDefaultValue(int onoff)
474
+ cdef int xmlThrDefIndentTreeOutput(int onoff)
475
+
476
+ cdef extern from "libxml/xmlmemory.h" nogil:
477
+ cdef void* xmlMalloc(size_t size)
478
+ cdef int xmlMemBlocks()
479
+ cdef int xmlMemUsed()
480
+
481
+ cdef extern from "etree_defs.h" nogil:
482
+ cdef bint _isElement(xmlNode* node)
483
+ cdef bint _isElementOrXInclude(xmlNode* node)
484
+ cdef const_xmlChar* _getNs(xmlNode* node)
485
+ cdef void BEGIN_FOR_EACH_ELEMENT_FROM(xmlNode* tree_top,
486
+ xmlNode* start_node,
487
+ bint inclusive)
488
+ cdef void END_FOR_EACH_ELEMENT_FROM(xmlNode* start_node)
489
+ cdef void BEGIN_FOR_EACH_FROM(xmlNode* tree_top,
490
+ xmlNode* start_node,
491
+ bint inclusive)
492
+ cdef void END_FOR_EACH_FROM(xmlNode* start_node)
.venv/lib/python3.12/site-packages/lxml/includes/uri.pxd ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ cdef extern from "libxml/uri.h" nogil:
2
+ ctypedef struct xmlURI
3
+
4
+ cdef xmlURI* xmlParseURI(char* str)
5
+ cdef void xmlFreeURI(xmlURI* uri)
.venv/lib/python3.12/site-packages/lxml/includes/xinclude.pxd ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes.tree cimport xmlDoc, xmlNode
2
+
3
+ cdef extern from "libxml/xinclude.h" nogil:
4
+
5
+ ctypedef struct xmlXIncludeCtxt
6
+
7
+ cdef int xmlXIncludeProcess(xmlDoc* doc)
8
+ cdef int xmlXIncludeProcessFlags(xmlDoc* doc, int parser_opts)
9
+ cdef int xmlXIncludeProcessTree(xmlNode* doc)
10
+ cdef int xmlXIncludeProcessTreeFlags(xmlNode* doc, int parser_opts)
11
+
12
+ # libxml2 >= 2.7.4
13
+ cdef int xmlXIncludeProcessTreeFlagsData(
14
+ xmlNode* doc, int parser_opts, void* data)
15
+
16
+ cdef xmlXIncludeCtxt* xmlXIncludeNewContext(xmlDoc* doc)
17
+ cdef int xmlXIncludeProcessNode(xmlXIncludeCtxt* ctxt, xmlNode* node)
18
+ cdef int xmlXIncludeSetFlags(xmlXIncludeCtxt* ctxt, int flags)
19
+
20
+ # libxml2 >= 2.6.27
21
+ cdef int xmlXIncludeProcessFlagsData(
22
+ xmlDoc* doc, int flags, void* data)
.venv/lib/python3.12/site-packages/lxml/includes/xmlerror.pxd ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # --- BEGIN: GENERATED CONSTANTS ---
3
+
4
+ # This section is generated by the script 'update-error-constants.py'.
5
+
6
+ cdef extern from "libxml/xmlerror.h":
7
+ ctypedef enum xmlErrorLevel:
8
+ XML_ERR_NONE = 0 # Success
9
+ XML_ERR_WARNING = 1 # A warning
10
+ XML_ERR_ERROR = 2 # An error
11
+ XML_ERR_FATAL = 3 # A fatal error
12
+
13
+ ctypedef enum xmlErrorDomain:
14
+ XML_FROM_NONE = 0 # Unknown
15
+ XML_FROM_PARSER = 1 # The XML parser
16
+ XML_FROM_TREE = 2 # The tree module (unused)
17
+ XML_FROM_NAMESPACE = 3 # The XML Namespace module
18
+ XML_FROM_DTD = 4 # The XML DTD validation with parser context
19
+ XML_FROM_HTML = 5 # The HTML parser
20
+ XML_FROM_MEMORY = 6 # The memory allocator (unused)
21
+ XML_FROM_OUTPUT = 7 # The serialization code
22
+ XML_FROM_IO = 8 # The Input/Output stack
23
+ XML_FROM_FTP = 9 # The FTP module (unused)
24
+ XML_FROM_HTTP = 10 # The HTTP module (unused)
25
+ XML_FROM_XINCLUDE = 11 # The XInclude processing
26
+ XML_FROM_XPATH = 12 # The XPath module
27
+ XML_FROM_XPOINTER = 13 # The XPointer module
28
+ XML_FROM_REGEXP = 14 # The regular expressions module
29
+ XML_FROM_DATATYPE = 15 # The W3C XML Schemas Datatype module
30
+ XML_FROM_SCHEMASP = 16 # The W3C XML Schemas parser module
31
+ XML_FROM_SCHEMASV = 17 # The W3C XML Schemas validation module
32
+ XML_FROM_RELAXNGP = 18 # The Relax-NG parser module
33
+ XML_FROM_RELAXNGV = 19 # The Relax-NG validator module
34
+ XML_FROM_CATALOG = 20 # The Catalog module
35
+ XML_FROM_C14N = 21 # The Canonicalization module
36
+ XML_FROM_XSLT = 22 # The XSLT engine from libxslt (unused)
37
+ XML_FROM_VALID = 23 # The XML DTD validation with valid context
38
+ XML_FROM_CHECK = 24 # The error checking module (unused)
39
+ XML_FROM_WRITER = 25 # The xmlwriter module
40
+ XML_FROM_MODULE = 26 # The dynamically loaded module module (unused)
41
+ XML_FROM_I18N = 27 # The module handling character conversion (unused)
42
+ XML_FROM_SCHEMATRONV = 28 # The Schematron validator module
43
+ XML_FROM_BUFFER = 29 # The buffers module (unused)
44
+ XML_FROM_URI = 30 # The URI module (unused)
45
+
46
+ ctypedef enum xmlParserErrors:
47
+ XML_ERR_OK = 0 # Success
48
+ XML_ERR_INTERNAL_ERROR = 1 # Internal assertion failure
49
+ XML_ERR_NO_MEMORY = 2 # Out of memory
50
+ XML_ERR_DOCUMENT_START = 3
51
+ XML_ERR_DOCUMENT_EMPTY = 4
52
+ XML_ERR_DOCUMENT_END = 5
53
+ XML_ERR_INVALID_HEX_CHARREF = 6
54
+ XML_ERR_INVALID_DEC_CHARREF = 7
55
+ XML_ERR_INVALID_CHARREF = 8
56
+ XML_ERR_INVALID_CHAR = 9
57
+ XML_ERR_CHARREF_AT_EOF = 10
58
+ XML_ERR_CHARREF_IN_PROLOG = 11
59
+ XML_ERR_CHARREF_IN_EPILOG = 12
60
+ XML_ERR_CHARREF_IN_DTD = 13
61
+ XML_ERR_ENTITYREF_AT_EOF = 14
62
+ XML_ERR_ENTITYREF_IN_PROLOG = 15
63
+ XML_ERR_ENTITYREF_IN_EPILOG = 16
64
+ XML_ERR_ENTITYREF_IN_DTD = 17
65
+ XML_ERR_PEREF_AT_EOF = 18
66
+ XML_ERR_PEREF_IN_PROLOG = 19
67
+ XML_ERR_PEREF_IN_EPILOG = 20
68
+ XML_ERR_PEREF_IN_INT_SUBSET = 21
69
+ XML_ERR_ENTITYREF_NO_NAME = 22
70
+ XML_ERR_ENTITYREF_SEMICOL_MISSING = 23
71
+ XML_ERR_PEREF_NO_NAME = 24
72
+ XML_ERR_PEREF_SEMICOL_MISSING = 25
73
+ XML_ERR_UNDECLARED_ENTITY = 26
74
+ XML_WAR_UNDECLARED_ENTITY = 27
75
+ XML_ERR_UNPARSED_ENTITY = 28
76
+ XML_ERR_ENTITY_IS_EXTERNAL = 29
77
+ XML_ERR_ENTITY_IS_PARAMETER = 30
78
+ XML_ERR_UNKNOWN_ENCODING = 31
79
+ XML_ERR_UNSUPPORTED_ENCODING = 32 # Unsupported character encoding
80
+ XML_ERR_STRING_NOT_STARTED = 33
81
+ XML_ERR_STRING_NOT_CLOSED = 34
82
+ XML_ERR_NS_DECL_ERROR = 35
83
+ XML_ERR_ENTITY_NOT_STARTED = 36
84
+ XML_ERR_ENTITY_NOT_FINISHED = 37
85
+ XML_ERR_LT_IN_ATTRIBUTE = 38
86
+ XML_ERR_ATTRIBUTE_NOT_STARTED = 39
87
+ XML_ERR_ATTRIBUTE_NOT_FINISHED = 40
88
+ XML_ERR_ATTRIBUTE_WITHOUT_VALUE = 41
89
+ XML_ERR_ATTRIBUTE_REDEFINED = 42
90
+ XML_ERR_LITERAL_NOT_STARTED = 43
91
+ XML_ERR_LITERAL_NOT_FINISHED = 44
92
+ XML_ERR_COMMENT_NOT_FINISHED = 45
93
+ XML_ERR_PI_NOT_STARTED = 46
94
+ XML_ERR_PI_NOT_FINISHED = 47
95
+ XML_ERR_NOTATION_NOT_STARTED = 48
96
+ XML_ERR_NOTATION_NOT_FINISHED = 49
97
+ XML_ERR_ATTLIST_NOT_STARTED = 50
98
+ XML_ERR_ATTLIST_NOT_FINISHED = 51
99
+ XML_ERR_MIXED_NOT_STARTED = 52
100
+ XML_ERR_MIXED_NOT_FINISHED = 53
101
+ XML_ERR_ELEMCONTENT_NOT_STARTED = 54
102
+ XML_ERR_ELEMCONTENT_NOT_FINISHED = 55
103
+ XML_ERR_XMLDECL_NOT_STARTED = 56
104
+ XML_ERR_XMLDECL_NOT_FINISHED = 57
105
+ XML_ERR_CONDSEC_NOT_STARTED = 58
106
+ XML_ERR_CONDSEC_NOT_FINISHED = 59
107
+ XML_ERR_EXT_SUBSET_NOT_FINISHED = 60
108
+ XML_ERR_DOCTYPE_NOT_FINISHED = 61
109
+ XML_ERR_MISPLACED_CDATA_END = 62
110
+ XML_ERR_CDATA_NOT_FINISHED = 63
111
+ XML_ERR_RESERVED_XML_NAME = 64
112
+ XML_ERR_SPACE_REQUIRED = 65
113
+ XML_ERR_SEPARATOR_REQUIRED = 66
114
+ XML_ERR_NMTOKEN_REQUIRED = 67
115
+ XML_ERR_NAME_REQUIRED = 68
116
+ XML_ERR_PCDATA_REQUIRED = 69
117
+ XML_ERR_URI_REQUIRED = 70
118
+ XML_ERR_PUBID_REQUIRED = 71
119
+ XML_ERR_LT_REQUIRED = 72
120
+ XML_ERR_GT_REQUIRED = 73
121
+ XML_ERR_LTSLASH_REQUIRED = 74
122
+ XML_ERR_EQUAL_REQUIRED = 75
123
+ XML_ERR_TAG_NAME_MISMATCH = 76
124
+ XML_ERR_TAG_NOT_FINISHED = 77
125
+ XML_ERR_STANDALONE_VALUE = 78
126
+ XML_ERR_ENCODING_NAME = 79
127
+ XML_ERR_HYPHEN_IN_COMMENT = 80
128
+ XML_ERR_INVALID_ENCODING = 81
129
+ XML_ERR_EXT_ENTITY_STANDALONE = 82
130
+ XML_ERR_CONDSEC_INVALID = 83
131
+ XML_ERR_VALUE_REQUIRED = 84
132
+ XML_ERR_NOT_WELL_BALANCED = 85
133
+ XML_ERR_EXTRA_CONTENT = 86
134
+ XML_ERR_ENTITY_CHAR_ERROR = 87
135
+ XML_ERR_ENTITY_PE_INTERNAL = 88
136
+ XML_ERR_ENTITY_LOOP = 89
137
+ XML_ERR_ENTITY_BOUNDARY = 90
138
+ XML_ERR_INVALID_URI = 91
139
+ XML_ERR_URI_FRAGMENT = 92
140
+ XML_WAR_CATALOG_PI = 93
141
+ XML_ERR_NO_DTD = 94
142
+ XML_ERR_CONDSEC_INVALID_KEYWORD = 95
143
+ XML_ERR_VERSION_MISSING = 96
144
+ XML_WAR_UNKNOWN_VERSION = 97
145
+ XML_WAR_LANG_VALUE = 98
146
+ XML_WAR_NS_URI = 99
147
+ XML_WAR_NS_URI_RELATIVE = 100
148
+ XML_ERR_MISSING_ENCODING = 101
149
+ XML_WAR_SPACE_VALUE = 102
150
+ XML_ERR_NOT_STANDALONE = 103
151
+ XML_ERR_ENTITY_PROCESSING = 104
152
+ XML_ERR_NOTATION_PROCESSING = 105
153
+ XML_WAR_NS_COLUMN = 106
154
+ XML_WAR_ENTITY_REDEFINED = 107
155
+ XML_ERR_UNKNOWN_VERSION = 108
156
+ XML_ERR_VERSION_MISMATCH = 109
157
+ XML_ERR_NAME_TOO_LONG = 110
158
+ XML_ERR_USER_STOP = 111
159
+ XML_ERR_COMMENT_ABRUPTLY_ENDED = 112
160
+ XML_WAR_ENCODING_MISMATCH = 113
161
+ XML_ERR_RESOURCE_LIMIT = 114 # Internal resource limit like maximum amplification factor exceeded
162
+ XML_ERR_ARGUMENT = 115 # Invalid argument
163
+ XML_ERR_SYSTEM = 116 # Unexpected error from the OS or an external library
164
+ XML_ERR_REDECL_PREDEF_ENTITY = 117
165
+ XML_ERR_INT_SUBSET_NOT_FINISHED = 118
166
+ XML_NS_ERR_XML_NAMESPACE = 200
167
+ XML_NS_ERR_UNDEFINED_NAMESPACE = 201
168
+ XML_NS_ERR_QNAME = 202
169
+ XML_NS_ERR_ATTRIBUTE_REDEFINED = 203
170
+ XML_NS_ERR_EMPTY = 204
171
+ XML_NS_ERR_COLON = 205
172
+ XML_DTD_ATTRIBUTE_DEFAULT = 500
173
+ XML_DTD_ATTRIBUTE_REDEFINED = 501
174
+ XML_DTD_ATTRIBUTE_VALUE = 502
175
+ XML_DTD_CONTENT_ERROR = 503
176
+ XML_DTD_CONTENT_MODEL = 504
177
+ XML_DTD_CONTENT_NOT_DETERMINIST = 505
178
+ XML_DTD_DIFFERENT_PREFIX = 506
179
+ XML_DTD_ELEM_DEFAULT_NAMESPACE = 507
180
+ XML_DTD_ELEM_NAMESPACE = 508
181
+ XML_DTD_ELEM_REDEFINED = 509
182
+ XML_DTD_EMPTY_NOTATION = 510
183
+ XML_DTD_ENTITY_TYPE = 511
184
+ XML_DTD_ID_FIXED = 512
185
+ XML_DTD_ID_REDEFINED = 513
186
+ XML_DTD_ID_SUBSET = 514
187
+ XML_DTD_INVALID_CHILD = 515
188
+ XML_DTD_INVALID_DEFAULT = 516
189
+ XML_DTD_LOAD_ERROR = 517
190
+ XML_DTD_MISSING_ATTRIBUTE = 518
191
+ XML_DTD_MIXED_CORRUPT = 519
192
+ XML_DTD_MULTIPLE_ID = 520
193
+ XML_DTD_NO_DOC = 521
194
+ XML_DTD_NO_DTD = 522
195
+ XML_DTD_NO_ELEM_NAME = 523
196
+ XML_DTD_NO_PREFIX = 524
197
+ XML_DTD_NO_ROOT = 525
198
+ XML_DTD_NOTATION_REDEFINED = 526
199
+ XML_DTD_NOTATION_VALUE = 527
200
+ XML_DTD_NOT_EMPTY = 528
201
+ XML_DTD_NOT_PCDATA = 529
202
+ XML_DTD_NOT_STANDALONE = 530
203
+ XML_DTD_ROOT_NAME = 531
204
+ XML_DTD_STANDALONE_WHITE_SPACE = 532
205
+ XML_DTD_UNKNOWN_ATTRIBUTE = 533
206
+ XML_DTD_UNKNOWN_ELEM = 534
207
+ XML_DTD_UNKNOWN_ENTITY = 535
208
+ XML_DTD_UNKNOWN_ID = 536
209
+ XML_DTD_UNKNOWN_NOTATION = 537
210
+ XML_DTD_STANDALONE_DEFAULTED = 538
211
+ XML_DTD_XMLID_VALUE = 539
212
+ XML_DTD_XMLID_TYPE = 540
213
+ XML_DTD_DUP_TOKEN = 541
214
+ XML_HTML_STRUCURE_ERROR = 800
215
+ XML_HTML_UNKNOWN_TAG = 801
216
+ XML_HTML_INCORRECTLY_OPENED_COMMENT = 802
217
+ XML_RNGP_ANYNAME_ATTR_ANCESTOR = 1000
218
+ XML_RNGP_ATTR_CONFLICT = 1001
219
+ XML_RNGP_ATTRIBUTE_CHILDREN = 1002
220
+ XML_RNGP_ATTRIBUTE_CONTENT = 1003
221
+ XML_RNGP_ATTRIBUTE_EMPTY = 1004
222
+ XML_RNGP_ATTRIBUTE_NOOP = 1005
223
+ XML_RNGP_CHOICE_CONTENT = 1006
224
+ XML_RNGP_CHOICE_EMPTY = 1007
225
+ XML_RNGP_CREATE_FAILURE = 1008
226
+ XML_RNGP_DATA_CONTENT = 1009
227
+ XML_RNGP_DEF_CHOICE_AND_INTERLEAVE = 1010
228
+ XML_RNGP_DEFINE_CREATE_FAILED = 1011
229
+ XML_RNGP_DEFINE_EMPTY = 1012
230
+ XML_RNGP_DEFINE_MISSING = 1013
231
+ XML_RNGP_DEFINE_NAME_MISSING = 1014
232
+ XML_RNGP_ELEM_CONTENT_EMPTY = 1015
233
+ XML_RNGP_ELEM_CONTENT_ERROR = 1016
234
+ XML_RNGP_ELEMENT_EMPTY = 1017
235
+ XML_RNGP_ELEMENT_CONTENT = 1018
236
+ XML_RNGP_ELEMENT_NAME = 1019
237
+ XML_RNGP_ELEMENT_NO_CONTENT = 1020
238
+ XML_RNGP_ELEM_TEXT_CONFLICT = 1021
239
+ XML_RNGP_EMPTY = 1022
240
+ XML_RNGP_EMPTY_CONSTRUCT = 1023
241
+ XML_RNGP_EMPTY_CONTENT = 1024
242
+ XML_RNGP_EMPTY_NOT_EMPTY = 1025
243
+ XML_RNGP_ERROR_TYPE_LIB = 1026
244
+ XML_RNGP_EXCEPT_EMPTY = 1027
245
+ XML_RNGP_EXCEPT_MISSING = 1028
246
+ XML_RNGP_EXCEPT_MULTIPLE = 1029
247
+ XML_RNGP_EXCEPT_NO_CONTENT = 1030
248
+ XML_RNGP_EXTERNALREF_EMTPY = 1031
249
+ XML_RNGP_EXTERNAL_REF_FAILURE = 1032
250
+ XML_RNGP_EXTERNALREF_RECURSE = 1033
251
+ XML_RNGP_FORBIDDEN_ATTRIBUTE = 1034
252
+ XML_RNGP_FOREIGN_ELEMENT = 1035
253
+ XML_RNGP_GRAMMAR_CONTENT = 1036
254
+ XML_RNGP_GRAMMAR_EMPTY = 1037
255
+ XML_RNGP_GRAMMAR_MISSING = 1038
256
+ XML_RNGP_GRAMMAR_NO_START = 1039
257
+ XML_RNGP_GROUP_ATTR_CONFLICT = 1040
258
+ XML_RNGP_HREF_ERROR = 1041
259
+ XML_RNGP_INCLUDE_EMPTY = 1042
260
+ XML_RNGP_INCLUDE_FAILURE = 1043
261
+ XML_RNGP_INCLUDE_RECURSE = 1044
262
+ XML_RNGP_INTERLEAVE_ADD = 1045
263
+ XML_RNGP_INTERLEAVE_CREATE_FAILED = 1046
264
+ XML_RNGP_INTERLEAVE_EMPTY = 1047
265
+ XML_RNGP_INTERLEAVE_NO_CONTENT = 1048
266
+ XML_RNGP_INVALID_DEFINE_NAME = 1049
267
+ XML_RNGP_INVALID_URI = 1050
268
+ XML_RNGP_INVALID_VALUE = 1051
269
+ XML_RNGP_MISSING_HREF = 1052
270
+ XML_RNGP_NAME_MISSING = 1053
271
+ XML_RNGP_NEED_COMBINE = 1054
272
+ XML_RNGP_NOTALLOWED_NOT_EMPTY = 1055
273
+ XML_RNGP_NSNAME_ATTR_ANCESTOR = 1056
274
+ XML_RNGP_NSNAME_NO_NS = 1057
275
+ XML_RNGP_PARAM_FORBIDDEN = 1058
276
+ XML_RNGP_PARAM_NAME_MISSING = 1059
277
+ XML_RNGP_PARENTREF_CREATE_FAILED = 1060
278
+ XML_RNGP_PARENTREF_NAME_INVALID = 1061
279
+ XML_RNGP_PARENTREF_NO_NAME = 1062
280
+ XML_RNGP_PARENTREF_NO_PARENT = 1063
281
+ XML_RNGP_PARENTREF_NOT_EMPTY = 1064
282
+ XML_RNGP_PARSE_ERROR = 1065
283
+ XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME = 1066
284
+ XML_RNGP_PAT_ATTR_ATTR = 1067
285
+ XML_RNGP_PAT_ATTR_ELEM = 1068
286
+ XML_RNGP_PAT_DATA_EXCEPT_ATTR = 1069
287
+ XML_RNGP_PAT_DATA_EXCEPT_ELEM = 1070
288
+ XML_RNGP_PAT_DATA_EXCEPT_EMPTY = 1071
289
+ XML_RNGP_PAT_DATA_EXCEPT_GROUP = 1072
290
+ XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE = 1073
291
+ XML_RNGP_PAT_DATA_EXCEPT_LIST = 1074
292
+ XML_RNGP_PAT_DATA_EXCEPT_ONEMORE = 1075
293
+ XML_RNGP_PAT_DATA_EXCEPT_REF = 1076
294
+ XML_RNGP_PAT_DATA_EXCEPT_TEXT = 1077
295
+ XML_RNGP_PAT_LIST_ATTR = 1078
296
+ XML_RNGP_PAT_LIST_ELEM = 1079
297
+ XML_RNGP_PAT_LIST_INTERLEAVE = 1080
298
+ XML_RNGP_PAT_LIST_LIST = 1081
299
+ XML_RNGP_PAT_LIST_REF = 1082
300
+ XML_RNGP_PAT_LIST_TEXT = 1083
301
+ XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME = 1084
302
+ XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME = 1085
303
+ XML_RNGP_PAT_ONEMORE_GROUP_ATTR = 1086
304
+ XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR = 1087
305
+ XML_RNGP_PAT_START_ATTR = 1088
306
+ XML_RNGP_PAT_START_DATA = 1089
307
+ XML_RNGP_PAT_START_EMPTY = 1090
308
+ XML_RNGP_PAT_START_GROUP = 1091
309
+ XML_RNGP_PAT_START_INTERLEAVE = 1092
310
+ XML_RNGP_PAT_START_LIST = 1093
311
+ XML_RNGP_PAT_START_ONEMORE = 1094
312
+ XML_RNGP_PAT_START_TEXT = 1095
313
+ XML_RNGP_PAT_START_VALUE = 1096
314
+ XML_RNGP_PREFIX_UNDEFINED = 1097
315
+ XML_RNGP_REF_CREATE_FAILED = 1098
316
+ XML_RNGP_REF_CYCLE = 1099
317
+ XML_RNGP_REF_NAME_INVALID = 1100
318
+ XML_RNGP_REF_NO_DEF = 1101
319
+ XML_RNGP_REF_NO_NAME = 1102
320
+ XML_RNGP_REF_NOT_EMPTY = 1103
321
+ XML_RNGP_START_CHOICE_AND_INTERLEAVE = 1104
322
+ XML_RNGP_START_CONTENT = 1105
323
+ XML_RNGP_START_EMPTY = 1106
324
+ XML_RNGP_START_MISSING = 1107
325
+ XML_RNGP_TEXT_EXPECTED = 1108
326
+ XML_RNGP_TEXT_HAS_CHILD = 1109
327
+ XML_RNGP_TYPE_MISSING = 1110
328
+ XML_RNGP_TYPE_NOT_FOUND = 1111
329
+ XML_RNGP_TYPE_VALUE = 1112
330
+ XML_RNGP_UNKNOWN_ATTRIBUTE = 1113
331
+ XML_RNGP_UNKNOWN_COMBINE = 1114
332
+ XML_RNGP_UNKNOWN_CONSTRUCT = 1115
333
+ XML_RNGP_UNKNOWN_TYPE_LIB = 1116
334
+ XML_RNGP_URI_FRAGMENT = 1117
335
+ XML_RNGP_URI_NOT_ABSOLUTE = 1118
336
+ XML_RNGP_VALUE_EMPTY = 1119
337
+ XML_RNGP_VALUE_NO_CONTENT = 1120
338
+ XML_RNGP_XMLNS_NAME = 1121
339
+ XML_RNGP_XML_NS = 1122
340
+ XML_XPATH_EXPRESSION_OK = 1200
341
+ XML_XPATH_NUMBER_ERROR = 1201
342
+ XML_XPATH_UNFINISHED_LITERAL_ERROR = 1202
343
+ XML_XPATH_START_LITERAL_ERROR = 1203
344
+ XML_XPATH_VARIABLE_REF_ERROR = 1204
345
+ XML_XPATH_UNDEF_VARIABLE_ERROR = 1205
346
+ XML_XPATH_INVALID_PREDICATE_ERROR = 1206
347
+ XML_XPATH_EXPR_ERROR = 1207
348
+ XML_XPATH_UNCLOSED_ERROR = 1208
349
+ XML_XPATH_UNKNOWN_FUNC_ERROR = 1209
350
+ XML_XPATH_INVALID_OPERAND = 1210
351
+ XML_XPATH_INVALID_TYPE = 1211
352
+ XML_XPATH_INVALID_ARITY = 1212
353
+ XML_XPATH_INVALID_CTXT_SIZE = 1213
354
+ XML_XPATH_INVALID_CTXT_POSITION = 1214
355
+ XML_XPATH_MEMORY_ERROR = 1215
356
+ XML_XPTR_SYNTAX_ERROR = 1216
357
+ XML_XPTR_RESOURCE_ERROR = 1217
358
+ XML_XPTR_SUB_RESOURCE_ERROR = 1218
359
+ XML_XPATH_UNDEF_PREFIX_ERROR = 1219
360
+ XML_XPATH_ENCODING_ERROR = 1220
361
+ XML_XPATH_INVALID_CHAR_ERROR = 1221
362
+ XML_TREE_INVALID_HEX = 1300
363
+ XML_TREE_INVALID_DEC = 1301
364
+ XML_TREE_UNTERMINATED_ENTITY = 1302
365
+ XML_TREE_NOT_UTF8 = 1303
366
+ XML_SAVE_NOT_UTF8 = 1400
367
+ XML_SAVE_CHAR_INVALID = 1401
368
+ XML_SAVE_NO_DOCTYPE = 1402
369
+ XML_SAVE_UNKNOWN_ENCODING = 1403
370
+ XML_REGEXP_COMPILE_ERROR = 1450
371
+ XML_IO_UNKNOWN = 1500
372
+ XML_IO_EACCES = 1501
373
+ XML_IO_EAGAIN = 1502
374
+ XML_IO_EBADF = 1503
375
+ XML_IO_EBADMSG = 1504
376
+ XML_IO_EBUSY = 1505
377
+ XML_IO_ECANCELED = 1506
378
+ XML_IO_ECHILD = 1507
379
+ XML_IO_EDEADLK = 1508
380
+ XML_IO_EDOM = 1509
381
+ XML_IO_EEXIST = 1510
382
+ XML_IO_EFAULT = 1511
383
+ XML_IO_EFBIG = 1512
384
+ XML_IO_EINPROGRESS = 1513
385
+ XML_IO_EINTR = 1514
386
+ XML_IO_EINVAL = 1515
387
+ XML_IO_EIO = 1516
388
+ XML_IO_EISDIR = 1517
389
+ XML_IO_EMFILE = 1518
390
+ XML_IO_EMLINK = 1519
391
+ XML_IO_EMSGSIZE = 1520
392
+ XML_IO_ENAMETOOLONG = 1521
393
+ XML_IO_ENFILE = 1522
394
+ XML_IO_ENODEV = 1523
395
+ XML_IO_ENOENT = 1524 # File not found
396
+ XML_IO_ENOEXEC = 1525
397
+ XML_IO_ENOLCK = 1526
398
+ XML_IO_ENOMEM = 1527
399
+ XML_IO_ENOSPC = 1528
400
+ XML_IO_ENOSYS = 1529
401
+ XML_IO_ENOTDIR = 1530
402
+ XML_IO_ENOTEMPTY = 1531
403
+ XML_IO_ENOTSUP = 1532
404
+ XML_IO_ENOTTY = 1533
405
+ XML_IO_ENXIO = 1534
406
+ XML_IO_EPERM = 1535
407
+ XML_IO_EPIPE = 1536
408
+ XML_IO_ERANGE = 1537
409
+ XML_IO_EROFS = 1538
410
+ XML_IO_ESPIPE = 1539
411
+ XML_IO_ESRCH = 1540
412
+ XML_IO_ETIMEDOUT = 1541
413
+ XML_IO_EXDEV = 1542
414
+ XML_IO_NETWORK_ATTEMPT = 1543
415
+ XML_IO_ENCODER = 1544
416
+ XML_IO_FLUSH = 1545
417
+ XML_IO_WRITE = 1546
418
+ XML_IO_NO_INPUT = 1547
419
+ XML_IO_BUFFER_FULL = 1548
420
+ XML_IO_LOAD_ERROR = 1549
421
+ XML_IO_ENOTSOCK = 1550
422
+ XML_IO_EISCONN = 1551
423
+ XML_IO_ECONNREFUSED = 1552
424
+ XML_IO_ENETUNREACH = 1553
425
+ XML_IO_EADDRINUSE = 1554
426
+ XML_IO_EALREADY = 1555
427
+ XML_IO_EAFNOSUPPORT = 1556
428
+ XML_IO_UNSUPPORTED_PROTOCOL = 1557
429
+ XML_XINCLUDE_RECURSION = 1600
430
+ XML_XINCLUDE_PARSE_VALUE = 1601
431
+ XML_XINCLUDE_ENTITY_DEF_MISMATCH = 1602
432
+ XML_XINCLUDE_NO_HREF = 1603
433
+ XML_XINCLUDE_NO_FALLBACK = 1604
434
+ XML_XINCLUDE_HREF_URI = 1605
435
+ XML_XINCLUDE_TEXT_FRAGMENT = 1606
436
+ XML_XINCLUDE_TEXT_DOCUMENT = 1607
437
+ XML_XINCLUDE_INVALID_CHAR = 1608
438
+ XML_XINCLUDE_BUILD_FAILED = 1609
439
+ XML_XINCLUDE_UNKNOWN_ENCODING = 1610
440
+ XML_XINCLUDE_MULTIPLE_ROOT = 1611
441
+ XML_XINCLUDE_XPTR_FAILED = 1612
442
+ XML_XINCLUDE_XPTR_RESULT = 1613
443
+ XML_XINCLUDE_INCLUDE_IN_INCLUDE = 1614
444
+ XML_XINCLUDE_FALLBACKS_IN_INCLUDE = 1615
445
+ XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE = 1616
446
+ XML_XINCLUDE_DEPRECATED_NS = 1617
447
+ XML_XINCLUDE_FRAGMENT_ID = 1618
448
+ XML_CATALOG_MISSING_ATTR = 1650
449
+ XML_CATALOG_ENTRY_BROKEN = 1651
450
+ XML_CATALOG_PREFER_VALUE = 1652
451
+ XML_CATALOG_NOT_CATALOG = 1653
452
+ XML_CATALOG_RECURSION = 1654
453
+ XML_SCHEMAP_PREFIX_UNDEFINED = 1700
454
+ XML_SCHEMAP_ATTRFORMDEFAULT_VALUE = 1701
455
+ XML_SCHEMAP_ATTRGRP_NONAME_NOREF = 1702
456
+ XML_SCHEMAP_ATTR_NONAME_NOREF = 1703
457
+ XML_SCHEMAP_COMPLEXTYPE_NONAME_NOREF = 1704
458
+ XML_SCHEMAP_ELEMFORMDEFAULT_VALUE = 1705
459
+ XML_SCHEMAP_ELEM_NONAME_NOREF = 1706
460
+ XML_SCHEMAP_EXTENSION_NO_BASE = 1707
461
+ XML_SCHEMAP_FACET_NO_VALUE = 1708
462
+ XML_SCHEMAP_FAILED_BUILD_IMPORT = 1709
463
+ XML_SCHEMAP_GROUP_NONAME_NOREF = 1710
464
+ XML_SCHEMAP_IMPORT_NAMESPACE_NOT_URI = 1711
465
+ XML_SCHEMAP_IMPORT_REDEFINE_NSNAME = 1712
466
+ XML_SCHEMAP_IMPORT_SCHEMA_NOT_URI = 1713
467
+ XML_SCHEMAP_INVALID_BOOLEAN = 1714
468
+ XML_SCHEMAP_INVALID_ENUM = 1715
469
+ XML_SCHEMAP_INVALID_FACET = 1716
470
+ XML_SCHEMAP_INVALID_FACET_VALUE = 1717
471
+ XML_SCHEMAP_INVALID_MAXOCCURS = 1718
472
+ XML_SCHEMAP_INVALID_MINOCCURS = 1719
473
+ XML_SCHEMAP_INVALID_REF_AND_SUBTYPE = 1720
474
+ XML_SCHEMAP_INVALID_WHITE_SPACE = 1721
475
+ XML_SCHEMAP_NOATTR_NOREF = 1722
476
+ XML_SCHEMAP_NOTATION_NO_NAME = 1723
477
+ XML_SCHEMAP_NOTYPE_NOREF = 1724
478
+ XML_SCHEMAP_REF_AND_SUBTYPE = 1725
479
+ XML_SCHEMAP_RESTRICTION_NONAME_NOREF = 1726
480
+ XML_SCHEMAP_SIMPLETYPE_NONAME = 1727
481
+ XML_SCHEMAP_TYPE_AND_SUBTYPE = 1728
482
+ XML_SCHEMAP_UNKNOWN_ALL_CHILD = 1729
483
+ XML_SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD = 1730
484
+ XML_SCHEMAP_UNKNOWN_ATTR_CHILD = 1731
485
+ XML_SCHEMAP_UNKNOWN_ATTRGRP_CHILD = 1732
486
+ XML_SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP = 1733
487
+ XML_SCHEMAP_UNKNOWN_BASE_TYPE = 1734
488
+ XML_SCHEMAP_UNKNOWN_CHOICE_CHILD = 1735
489
+ XML_SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD = 1736
490
+ XML_SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD = 1737
491
+ XML_SCHEMAP_UNKNOWN_ELEM_CHILD = 1738
492
+ XML_SCHEMAP_UNKNOWN_EXTENSION_CHILD = 1739
493
+ XML_SCHEMAP_UNKNOWN_FACET_CHILD = 1740
494
+ XML_SCHEMAP_UNKNOWN_FACET_TYPE = 1741
495
+ XML_SCHEMAP_UNKNOWN_GROUP_CHILD = 1742
496
+ XML_SCHEMAP_UNKNOWN_IMPORT_CHILD = 1743
497
+ XML_SCHEMAP_UNKNOWN_LIST_CHILD = 1744
498
+ XML_SCHEMAP_UNKNOWN_NOTATION_CHILD = 1745
499
+ XML_SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD = 1746
500
+ XML_SCHEMAP_UNKNOWN_REF = 1747
501
+ XML_SCHEMAP_UNKNOWN_RESTRICTION_CHILD = 1748
502
+ XML_SCHEMAP_UNKNOWN_SCHEMAS_CHILD = 1749
503
+ XML_SCHEMAP_UNKNOWN_SEQUENCE_CHILD = 1750
504
+ XML_SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD = 1751
505
+ XML_SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD = 1752
506
+ XML_SCHEMAP_UNKNOWN_TYPE = 1753
507
+ XML_SCHEMAP_UNKNOWN_UNION_CHILD = 1754
508
+ XML_SCHEMAP_ELEM_DEFAULT_FIXED = 1755
509
+ XML_SCHEMAP_REGEXP_INVALID = 1756
510
+ XML_SCHEMAP_FAILED_LOAD = 1757
511
+ XML_SCHEMAP_NOTHING_TO_PARSE = 1758
512
+ XML_SCHEMAP_NOROOT = 1759
513
+ XML_SCHEMAP_REDEFINED_GROUP = 1760
514
+ XML_SCHEMAP_REDEFINED_TYPE = 1761
515
+ XML_SCHEMAP_REDEFINED_ELEMENT = 1762
516
+ XML_SCHEMAP_REDEFINED_ATTRGROUP = 1763
517
+ XML_SCHEMAP_REDEFINED_ATTR = 1764
518
+ XML_SCHEMAP_REDEFINED_NOTATION = 1765
519
+ XML_SCHEMAP_FAILED_PARSE = 1766
520
+ XML_SCHEMAP_UNKNOWN_PREFIX = 1767
521
+ XML_SCHEMAP_DEF_AND_PREFIX = 1768
522
+ XML_SCHEMAP_UNKNOWN_INCLUDE_CHILD = 1769
523
+ XML_SCHEMAP_INCLUDE_SCHEMA_NOT_URI = 1770
524
+ XML_SCHEMAP_INCLUDE_SCHEMA_NO_URI = 1771
525
+ XML_SCHEMAP_NOT_SCHEMA = 1772
526
+ XML_SCHEMAP_UNKNOWN_MEMBER_TYPE = 1773
527
+ XML_SCHEMAP_INVALID_ATTR_USE = 1774
528
+ XML_SCHEMAP_RECURSIVE = 1775
529
+ XML_SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE = 1776
530
+ XML_SCHEMAP_INVALID_ATTR_COMBINATION = 1777
531
+ XML_SCHEMAP_INVALID_ATTR_INLINE_COMBINATION = 1778
532
+ XML_SCHEMAP_MISSING_SIMPLETYPE_CHILD = 1779
533
+ XML_SCHEMAP_INVALID_ATTR_NAME = 1780
534
+ XML_SCHEMAP_REF_AND_CONTENT = 1781
535
+ XML_SCHEMAP_CT_PROPS_CORRECT_1 = 1782
536
+ XML_SCHEMAP_CT_PROPS_CORRECT_2 = 1783
537
+ XML_SCHEMAP_CT_PROPS_CORRECT_3 = 1784
538
+ XML_SCHEMAP_CT_PROPS_CORRECT_4 = 1785
539
+ XML_SCHEMAP_CT_PROPS_CORRECT_5 = 1786
540
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1 = 1787
541
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1 = 1788
542
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2 = 1789
543
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2 = 1790
544
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3 = 1791
545
+ XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER = 1792
546
+ XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE = 1793
547
+ XML_SCHEMAP_UNION_NOT_EXPRESSIBLE = 1794
548
+ XML_SCHEMAP_SRC_IMPORT_3_1 = 1795
549
+ XML_SCHEMAP_SRC_IMPORT_3_2 = 1796
550
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1 = 1797
551
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2 = 1798
552
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_3 = 1799
553
+ XML_SCHEMAP_COS_CT_EXTENDS_1_3 = 1800
554
+ XML_SCHEMAV_NOROOT = 1801
555
+ XML_SCHEMAV_UNDECLAREDELEM = 1802
556
+ XML_SCHEMAV_NOTTOPLEVEL = 1803
557
+ XML_SCHEMAV_MISSING = 1804
558
+ XML_SCHEMAV_WRONGELEM = 1805
559
+ XML_SCHEMAV_NOTYPE = 1806
560
+ XML_SCHEMAV_NOROLLBACK = 1807
561
+ XML_SCHEMAV_ISABSTRACT = 1808
562
+ XML_SCHEMAV_NOTEMPTY = 1809
563
+ XML_SCHEMAV_ELEMCONT = 1810
564
+ XML_SCHEMAV_HAVEDEFAULT = 1811
565
+ XML_SCHEMAV_NOTNILLABLE = 1812
566
+ XML_SCHEMAV_EXTRACONTENT = 1813
567
+ XML_SCHEMAV_INVALIDATTR = 1814
568
+ XML_SCHEMAV_INVALIDELEM = 1815
569
+ XML_SCHEMAV_NOTDETERMINIST = 1816
570
+ XML_SCHEMAV_CONSTRUCT = 1817
571
+ XML_SCHEMAV_INTERNAL = 1818
572
+ XML_SCHEMAV_NOTSIMPLE = 1819
573
+ XML_SCHEMAV_ATTRUNKNOWN = 1820
574
+ XML_SCHEMAV_ATTRINVALID = 1821
575
+ XML_SCHEMAV_VALUE = 1822
576
+ XML_SCHEMAV_FACET = 1823
577
+ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1 = 1824
578
+ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2 = 1825
579
+ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3 = 1826
580
+ XML_SCHEMAV_CVC_TYPE_3_1_1 = 1827
581
+ XML_SCHEMAV_CVC_TYPE_3_1_2 = 1828
582
+ XML_SCHEMAV_CVC_FACET_VALID = 1829
583
+ XML_SCHEMAV_CVC_LENGTH_VALID = 1830
584
+ XML_SCHEMAV_CVC_MINLENGTH_VALID = 1831
585
+ XML_SCHEMAV_CVC_MAXLENGTH_VALID = 1832
586
+ XML_SCHEMAV_CVC_MININCLUSIVE_VALID = 1833
587
+ XML_SCHEMAV_CVC_MAXINCLUSIVE_VALID = 1834
588
+ XML_SCHEMAV_CVC_MINEXCLUSIVE_VALID = 1835
589
+ XML_SCHEMAV_CVC_MAXEXCLUSIVE_VALID = 1836
590
+ XML_SCHEMAV_CVC_TOTALDIGITS_VALID = 1837
591
+ XML_SCHEMAV_CVC_FRACTIONDIGITS_VALID = 1838
592
+ XML_SCHEMAV_CVC_PATTERN_VALID = 1839
593
+ XML_SCHEMAV_CVC_ENUMERATION_VALID = 1840
594
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1 = 1841
595
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2 = 1842
596
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3 = 1843
597
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_4 = 1844
598
+ XML_SCHEMAV_CVC_ELT_1 = 1845
599
+ XML_SCHEMAV_CVC_ELT_2 = 1846
600
+ XML_SCHEMAV_CVC_ELT_3_1 = 1847
601
+ XML_SCHEMAV_CVC_ELT_3_2_1 = 1848
602
+ XML_SCHEMAV_CVC_ELT_3_2_2 = 1849
603
+ XML_SCHEMAV_CVC_ELT_4_1 = 1850
604
+ XML_SCHEMAV_CVC_ELT_4_2 = 1851
605
+ XML_SCHEMAV_CVC_ELT_4_3 = 1852
606
+ XML_SCHEMAV_CVC_ELT_5_1_1 = 1853
607
+ XML_SCHEMAV_CVC_ELT_5_1_2 = 1854
608
+ XML_SCHEMAV_CVC_ELT_5_2_1 = 1855
609
+ XML_SCHEMAV_CVC_ELT_5_2_2_1 = 1856
610
+ XML_SCHEMAV_CVC_ELT_5_2_2_2_1 = 1857
611
+ XML_SCHEMAV_CVC_ELT_5_2_2_2_2 = 1858
612
+ XML_SCHEMAV_CVC_ELT_6 = 1859
613
+ XML_SCHEMAV_CVC_ELT_7 = 1860
614
+ XML_SCHEMAV_CVC_ATTRIBUTE_1 = 1861
615
+ XML_SCHEMAV_CVC_ATTRIBUTE_2 = 1862
616
+ XML_SCHEMAV_CVC_ATTRIBUTE_3 = 1863
617
+ XML_SCHEMAV_CVC_ATTRIBUTE_4 = 1864
618
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_1 = 1865
619
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1 = 1866
620
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_2 = 1867
621
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_4 = 1868
622
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_1 = 1869
623
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_2 = 1870
624
+ XML_SCHEMAV_ELEMENT_CONTENT = 1871
625
+ XML_SCHEMAV_DOCUMENT_ELEMENT_MISSING = 1872
626
+ XML_SCHEMAV_CVC_COMPLEX_TYPE_1 = 1873
627
+ XML_SCHEMAV_CVC_AU = 1874
628
+ XML_SCHEMAV_CVC_TYPE_1 = 1875
629
+ XML_SCHEMAV_CVC_TYPE_2 = 1876
630
+ XML_SCHEMAV_CVC_IDC = 1877
631
+ XML_SCHEMAV_CVC_WILDCARD = 1878
632
+ XML_SCHEMAV_MISC = 1879
633
+ XML_XPTR_UNKNOWN_SCHEME = 1900
634
+ XML_XPTR_CHILDSEQ_START = 1901
635
+ XML_XPTR_EVAL_FAILED = 1902
636
+ XML_XPTR_EXTRA_OBJECTS = 1903
637
+ XML_C14N_CREATE_CTXT = 1950
638
+ XML_C14N_REQUIRES_UTF8 = 1951
639
+ XML_C14N_CREATE_STACK = 1952
640
+ XML_C14N_INVALID_NODE = 1953
641
+ XML_C14N_UNKNOW_NODE = 1954
642
+ XML_C14N_RELATIVE_NAMESPACE = 1955
643
+ XML_FTP_PASV_ANSWER = 2000
644
+ XML_FTP_EPSV_ANSWER = 2001
645
+ XML_FTP_ACCNT = 2002
646
+ XML_FTP_URL_SYNTAX = 2003
647
+ XML_HTTP_URL_SYNTAX = 2020
648
+ XML_HTTP_USE_IP = 2021
649
+ XML_HTTP_UNKNOWN_HOST = 2022
650
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_1 = 3000
651
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_2 = 3001
652
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_3 = 3002
653
+ XML_SCHEMAP_SRC_SIMPLE_TYPE_4 = 3003
654
+ XML_SCHEMAP_SRC_RESOLVE = 3004
655
+ XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE = 3005
656
+ XML_SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE = 3006
657
+ XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES = 3007
658
+ XML_SCHEMAP_ST_PROPS_CORRECT_1 = 3008
659
+ XML_SCHEMAP_ST_PROPS_CORRECT_2 = 3009
660
+ XML_SCHEMAP_ST_PROPS_CORRECT_3 = 3010
661
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_1 = 3011
662
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_2 = 3012
663
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1 = 3013
664
+ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_2 = 3014
665
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_1 = 3015
666
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1 = 3016
667
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2 = 3017
668
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1 = 3018
669
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2 = 3019
670
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3 = 3020
671
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4 = 3021
672
+ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_5 = 3022
673
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_1 = 3023
674
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1 = 3024
675
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2 = 3025
676
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2 = 3026
677
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1 = 3027
678
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3 = 3028
679
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4 = 3029
680
+ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_5 = 3030
681
+ XML_SCHEMAP_COS_ST_DERIVED_OK_2_1 = 3031
682
+ XML_SCHEMAP_COS_ST_DERIVED_OK_2_2 = 3032
683
+ XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED = 3033
684
+ XML_SCHEMAP_S4S_ELEM_MISSING = 3034
685
+ XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED = 3035
686
+ XML_SCHEMAP_S4S_ATTR_MISSING = 3036
687
+ XML_SCHEMAP_S4S_ATTR_INVALID_VALUE = 3037
688
+ XML_SCHEMAP_SRC_ELEMENT_1 = 3038
689
+ XML_SCHEMAP_SRC_ELEMENT_2_1 = 3039
690
+ XML_SCHEMAP_SRC_ELEMENT_2_2 = 3040
691
+ XML_SCHEMAP_SRC_ELEMENT_3 = 3041
692
+ XML_SCHEMAP_P_PROPS_CORRECT_1 = 3042
693
+ XML_SCHEMAP_P_PROPS_CORRECT_2_1 = 3043
694
+ XML_SCHEMAP_P_PROPS_CORRECT_2_2 = 3044
695
+ XML_SCHEMAP_E_PROPS_CORRECT_2 = 3045
696
+ XML_SCHEMAP_E_PROPS_CORRECT_3 = 3046
697
+ XML_SCHEMAP_E_PROPS_CORRECT_4 = 3047
698
+ XML_SCHEMAP_E_PROPS_CORRECT_5 = 3048
699
+ XML_SCHEMAP_E_PROPS_CORRECT_6 = 3049
700
+ XML_SCHEMAP_SRC_INCLUDE = 3050
701
+ XML_SCHEMAP_SRC_ATTRIBUTE_1 = 3051
702
+ XML_SCHEMAP_SRC_ATTRIBUTE_2 = 3052
703
+ XML_SCHEMAP_SRC_ATTRIBUTE_3_1 = 3053
704
+ XML_SCHEMAP_SRC_ATTRIBUTE_3_2 = 3054
705
+ XML_SCHEMAP_SRC_ATTRIBUTE_4 = 3055
706
+ XML_SCHEMAP_NO_XMLNS = 3056
707
+ XML_SCHEMAP_NO_XSI = 3057
708
+ XML_SCHEMAP_COS_VALID_DEFAULT_1 = 3058
709
+ XML_SCHEMAP_COS_VALID_DEFAULT_2_1 = 3059
710
+ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_1 = 3060
711
+ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_2 = 3061
712
+ XML_SCHEMAP_CVC_SIMPLE_TYPE = 3062
713
+ XML_SCHEMAP_COS_CT_EXTENDS_1_1 = 3063
714
+ XML_SCHEMAP_SRC_IMPORT_1_1 = 3064
715
+ XML_SCHEMAP_SRC_IMPORT_1_2 = 3065
716
+ XML_SCHEMAP_SRC_IMPORT_2 = 3066
717
+ XML_SCHEMAP_SRC_IMPORT_2_1 = 3067
718
+ XML_SCHEMAP_SRC_IMPORT_2_2 = 3068
719
+ XML_SCHEMAP_INTERNAL = 3069
720
+ XML_SCHEMAP_NOT_DETERMINISTIC = 3070
721
+ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_1 = 3071
722
+ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_2 = 3072
723
+ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_3 = 3073
724
+ XML_SCHEMAP_MG_PROPS_CORRECT_1 = 3074
725
+ XML_SCHEMAP_MG_PROPS_CORRECT_2 = 3075
726
+ XML_SCHEMAP_SRC_CT_1 = 3076
727
+ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3 = 3077
728
+ XML_SCHEMAP_AU_PROPS_CORRECT_2 = 3078
729
+ XML_SCHEMAP_A_PROPS_CORRECT_2 = 3079
730
+ XML_SCHEMAP_C_PROPS_CORRECT = 3080
731
+ XML_SCHEMAP_SRC_REDEFINE = 3081
732
+ XML_SCHEMAP_SRC_IMPORT = 3082
733
+ XML_SCHEMAP_WARN_SKIP_SCHEMA = 3083
734
+ XML_SCHEMAP_WARN_UNLOCATED_SCHEMA = 3084
735
+ XML_SCHEMAP_WARN_ATTR_REDECL_PROH = 3085
736
+ XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH = 3086
737
+ XML_SCHEMAP_AG_PROPS_CORRECT = 3087
738
+ XML_SCHEMAP_COS_CT_EXTENDS_1_2 = 3088
739
+ XML_SCHEMAP_AU_PROPS_CORRECT = 3089
740
+ XML_SCHEMAP_A_PROPS_CORRECT_3 = 3090
741
+ XML_SCHEMAP_COS_ALL_LIMITED = 3091
742
+ XML_SCHEMATRONV_ASSERT = 4000
743
+ XML_SCHEMATRONV_REPORT = 4001
744
+ XML_MODULE_OPEN = 4900
745
+ XML_MODULE_CLOSE = 4901
746
+ XML_CHECK_FOUND_ELEMENT = 5000
747
+ XML_CHECK_FOUND_ATTRIBUTE = 5001
748
+ XML_CHECK_FOUND_TEXT = 5002
749
+ XML_CHECK_FOUND_CDATA = 5003
750
+ XML_CHECK_FOUND_ENTITYREF = 5004
751
+ XML_CHECK_FOUND_ENTITY = 5005
752
+ XML_CHECK_FOUND_PI = 5006
753
+ XML_CHECK_FOUND_COMMENT = 5007
754
+ XML_CHECK_FOUND_DOCTYPE = 5008
755
+ XML_CHECK_FOUND_FRAGMENT = 5009
756
+ XML_CHECK_FOUND_NOTATION = 5010
757
+ XML_CHECK_UNKNOWN_NODE = 5011
758
+ XML_CHECK_ENTITY_TYPE = 5012
759
+ XML_CHECK_NO_PARENT = 5013
760
+ XML_CHECK_NO_DOC = 5014
761
+ XML_CHECK_NO_NAME = 5015
762
+ XML_CHECK_NO_ELEM = 5016
763
+ XML_CHECK_WRONG_DOC = 5017
764
+ XML_CHECK_NO_PREV = 5018
765
+ XML_CHECK_WRONG_PREV = 5019
766
+ XML_CHECK_NO_NEXT = 5020
767
+ XML_CHECK_WRONG_NEXT = 5021
768
+ XML_CHECK_NOT_DTD = 5022
769
+ XML_CHECK_NOT_ATTR = 5023
770
+ XML_CHECK_NOT_ATTR_DECL = 5024
771
+ XML_CHECK_NOT_ELEM_DECL = 5025
772
+ XML_CHECK_NOT_ENTITY_DECL = 5026
773
+ XML_CHECK_NOT_NS_DECL = 5027
774
+ XML_CHECK_NO_HREF = 5028
775
+ XML_CHECK_WRONG_PARENT = 5029
776
+ XML_CHECK_NS_SCOPE = 5030
777
+ XML_CHECK_NS_ANCESTOR = 5031
778
+ XML_CHECK_NOT_UTF8 = 5032
779
+ XML_CHECK_NO_DICT = 5033
780
+ XML_CHECK_NOT_NCNAME = 5034
781
+ XML_CHECK_OUTSIDE_DICT = 5035
782
+ XML_CHECK_WRONG_NAME = 5036
783
+ XML_CHECK_NAME_NOT_NULL = 5037
784
+ XML_I18N_NO_NAME = 6000
785
+ XML_I18N_NO_HANDLER = 6001
786
+ XML_I18N_EXCESS_HANDLER = 6002
787
+ XML_I18N_CONV_FAILED = 6003
788
+ XML_I18N_NO_OUTPUT = 6004
789
+ XML_BUF_OVERFLOW = 7000
790
+
791
+ ctypedef enum xmlRelaxNGValidErr:
792
+ XML_RELAXNG_OK = 0
793
+ XML_RELAXNG_ERR_MEMORY = 1
794
+ XML_RELAXNG_ERR_TYPE = 2
795
+ XML_RELAXNG_ERR_TYPEVAL = 3
796
+ XML_RELAXNG_ERR_DUPID = 4
797
+ XML_RELAXNG_ERR_TYPECMP = 5
798
+ XML_RELAXNG_ERR_NOSTATE = 6
799
+ XML_RELAXNG_ERR_NODEFINE = 7
800
+ XML_RELAXNG_ERR_LISTEXTRA = 8
801
+ XML_RELAXNG_ERR_LISTEMPTY = 9
802
+ XML_RELAXNG_ERR_INTERNODATA = 10
803
+ XML_RELAXNG_ERR_INTERSEQ = 11
804
+ XML_RELAXNG_ERR_INTEREXTRA = 12
805
+ XML_RELAXNG_ERR_ELEMNAME = 13
806
+ XML_RELAXNG_ERR_ATTRNAME = 14
807
+ XML_RELAXNG_ERR_ELEMNONS = 15
808
+ XML_RELAXNG_ERR_ATTRNONS = 16
809
+ XML_RELAXNG_ERR_ELEMWRONGNS = 17
810
+ XML_RELAXNG_ERR_ATTRWRONGNS = 18
811
+ XML_RELAXNG_ERR_ELEMEXTRANS = 19
812
+ XML_RELAXNG_ERR_ATTREXTRANS = 20
813
+ XML_RELAXNG_ERR_ELEMNOTEMPTY = 21
814
+ XML_RELAXNG_ERR_NOELEM = 22
815
+ XML_RELAXNG_ERR_NOTELEM = 23
816
+ XML_RELAXNG_ERR_ATTRVALID = 24
817
+ XML_RELAXNG_ERR_CONTENTVALID = 25
818
+ XML_RELAXNG_ERR_EXTRACONTENT = 26
819
+ XML_RELAXNG_ERR_INVALIDATTR = 27
820
+ XML_RELAXNG_ERR_DATAELEM = 28
821
+ XML_RELAXNG_ERR_VALELEM = 29
822
+ XML_RELAXNG_ERR_LISTELEM = 30
823
+ XML_RELAXNG_ERR_DATATYPE = 31
824
+ XML_RELAXNG_ERR_VALUE = 32
825
+ XML_RELAXNG_ERR_LIST = 33
826
+ XML_RELAXNG_ERR_NOGRAMMAR = 34
827
+ XML_RELAXNG_ERR_EXTRADATA = 35
828
+ XML_RELAXNG_ERR_LACKDATA = 36
829
+ XML_RELAXNG_ERR_INTERNAL = 37
830
+ XML_RELAXNG_ERR_ELEMWRONG = 38
831
+ XML_RELAXNG_ERR_TEXTWRONG = 39
832
+ # --- END: GENERATED CONSTANTS ---
833
+
834
+ cdef extern from "libxml/xmlerror.h" nogil:
835
+ ctypedef struct xmlError:
836
+ int domain
837
+ int code
838
+ char* message
839
+ xmlErrorLevel level
840
+ char* file
841
+ char* str1
842
+ char* str2
843
+ char* str3
844
+ int line
845
+ int int1
846
+ int int2
847
+ void* node
848
+
849
+ ctypedef void (*xmlGenericErrorFunc)(void* ctxt, char* msg, ...) noexcept
850
+ ctypedef void (*xmlStructuredErrorFunc)(void* userData,
851
+ const xmlError* error) noexcept
852
+
853
+ cdef void xmlSetGenericErrorFunc(
854
+ void* ctxt, xmlGenericErrorFunc func)
855
+ cdef void xmlSetStructuredErrorFunc(
856
+ void* ctxt, xmlStructuredErrorFunc func)
857
+
858
+ cdef extern from "libxml/globals.h" nogil:
859
+ cdef xmlStructuredErrorFunc xmlStructuredError
860
+ cdef void* xmlStructuredErrorContext
.venv/lib/python3.12/site-packages/lxml/includes/xmlparser.pxd ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libc.string cimport const_char
2
+
3
+ from lxml.includes.tree cimport (
4
+ xmlDoc, xmlNode, xmlEntity, xmlDict, xmlDtd, xmlChar, const_xmlChar)
5
+ from lxml.includes.tree cimport xmlInputReadCallback, xmlInputCloseCallback
6
+ from lxml.includes.xmlerror cimport xmlError, xmlStructuredErrorFunc, xmlErrorLevel
7
+
8
+
9
+ cdef extern from "libxml/parser.h" nogil:
10
+ ctypedef void (*startElementNsSAX2Func)(void* ctx,
11
+ const_xmlChar* localname,
12
+ const_xmlChar* prefix,
13
+ const_xmlChar* URI,
14
+ int nb_namespaces,
15
+ const_xmlChar** namespaces,
16
+ int nb_attributes,
17
+ int nb_defaulted,
18
+ const_xmlChar** attributes) noexcept
19
+
20
+ ctypedef void (*endElementNsSAX2Func)(void* ctx,
21
+ const_xmlChar* localname,
22
+ const_xmlChar* prefix,
23
+ const_xmlChar* URI) noexcept
24
+
25
+ ctypedef void (*startElementSAXFunc)(void* ctx, const_xmlChar* name, const_xmlChar** atts) noexcept
26
+
27
+ ctypedef void (*endElementSAXFunc)(void* ctx, const_xmlChar* name) noexcept
28
+
29
+ ctypedef void (*charactersSAXFunc)(void* ctx, const_xmlChar* ch, int len) noexcept
30
+
31
+ ctypedef void (*cdataBlockSAXFunc)(void* ctx, const_xmlChar* value, int len) noexcept
32
+
33
+ ctypedef void (*commentSAXFunc)(void* ctx, const_xmlChar* value) noexcept
34
+
35
+ ctypedef void (*processingInstructionSAXFunc)(void* ctx,
36
+ const_xmlChar* target,
37
+ const_xmlChar* data) noexcept
38
+
39
+ ctypedef void (*internalSubsetSAXFunc)(void* ctx,
40
+ const_xmlChar* name,
41
+ const_xmlChar* externalID,
42
+ const_xmlChar* systemID) noexcept
43
+
44
+ ctypedef void (*endDocumentSAXFunc)(void* ctx) noexcept
45
+
46
+ ctypedef void (*startDocumentSAXFunc)(void* ctx) noexcept
47
+
48
+ ctypedef void (*referenceSAXFunc)(void * ctx, const_xmlChar* name) noexcept
49
+
50
+ ctypedef xmlEntity* (*getEntitySAXFunc)(void* ctx, const_xmlChar* name) noexcept
51
+
52
+ cdef int XML_SAX2_MAGIC
53
+
54
+ cdef extern from "libxml/tree.h" nogil:
55
+ ctypedef struct xmlParserInput:
56
+ int line
57
+ int col
58
+ int length
59
+ const_xmlChar* base
60
+ const_xmlChar* cur
61
+ const_xmlChar* end
62
+ const_char *filename
63
+
64
+ ctypedef struct xmlParserInputBuffer:
65
+ void* context
66
+ xmlInputReadCallback readcallback
67
+ xmlInputCloseCallback closecallback
68
+
69
+ ctypedef struct xmlSAXHandlerV1:
70
+ # same as xmlSAXHandler, but without namespaces
71
+ pass
72
+
73
+ ctypedef struct xmlSAXHandler:
74
+ internalSubsetSAXFunc internalSubset
75
+ startElementNsSAX2Func startElementNs
76
+ endElementNsSAX2Func endElementNs
77
+ startElementSAXFunc startElement
78
+ endElementSAXFunc endElement
79
+ charactersSAXFunc characters
80
+ cdataBlockSAXFunc cdataBlock
81
+ referenceSAXFunc reference
82
+ getEntitySAXFunc getEntity
83
+ getEntitySAXFunc getParameterEntity
84
+ commentSAXFunc comment
85
+ processingInstructionSAXFunc processingInstruction
86
+ startDocumentSAXFunc startDocument
87
+ endDocumentSAXFunc endDocument
88
+ int initialized
89
+ xmlStructuredErrorFunc serror
90
+ void* _private
91
+
92
+
93
+ cdef extern from "libxml/SAX2.h" nogil:
94
+ cdef void xmlSAX2StartDocument(void* ctxt)
95
+
96
+
97
+ cdef extern from "libxml/xmlIO.h" nogil:
98
+ cdef xmlParserInputBuffer* xmlAllocParserInputBuffer(int enc)
99
+
100
+
101
+ cdef extern from "libxml/parser.h" nogil:
102
+
103
+ ctypedef enum xmlFeature:
104
+ XML_WITH_THREAD = 1
105
+ XML_WITH_TREE = 2
106
+ XML_WITH_OUTPUT = 3
107
+ XML_WITH_PUSH = 4
108
+ XML_WITH_READER = 5
109
+ XML_WITH_PATTERN = 6
110
+ XML_WITH_WRITER = 7
111
+ XML_WITH_SAX1 = 8
112
+ XML_WITH_FTP = 9
113
+ XML_WITH_HTTP = 10
114
+ XML_WITH_VALID = 11
115
+ XML_WITH_HTML = 12
116
+ XML_WITH_LEGACY = 13
117
+ XML_WITH_C14N = 14
118
+ XML_WITH_CATALOG = 15
119
+ XML_WITH_XPATH = 16
120
+ XML_WITH_XPTR = 17
121
+ XML_WITH_XINCLUDE = 18
122
+ XML_WITH_ICONV = 19
123
+ XML_WITH_ISO8859X = 20
124
+ XML_WITH_UNICODE = 21
125
+ XML_WITH_REGEXP = 22
126
+ XML_WITH_AUTOMATA = 23
127
+ XML_WITH_EXPR = 24
128
+ XML_WITH_SCHEMAS = 25
129
+ XML_WITH_SCHEMATRON = 26
130
+ XML_WITH_MODULES = 27
131
+ XML_WITH_DEBUG = 28
132
+ XML_WITH_DEBUG_MEM = 29
133
+ XML_WITH_DEBUG_RUN = 30
134
+ XML_WITH_ZLIB = 31
135
+ XML_WITH_ICU = 32
136
+ XML_WITH_LZMA = 33
137
+
138
+ cdef bint xmlHasFeature(xmlFeature feature)
139
+
140
+ cdef xmlDict* xmlDictCreate()
141
+ cdef xmlDict* xmlDictCreateSub(xmlDict* subdict)
142
+ cdef void xmlDictFree(xmlDict* sub)
143
+ cdef int xmlDictReference(xmlDict* dict)
144
+
145
+ cdef int XML_COMPLETE_ATTRS # SAX option for adding DTD default attributes
146
+ cdef int XML_SKIP_IDS # SAX option for not building an XML ID dict
147
+
148
+ ctypedef enum xmlParserInputState:
149
+ XML_PARSER_EOF = -1 # nothing is to be parsed
150
+ XML_PARSER_START = 0 # nothing has been parsed
151
+ XML_PARSER_MISC = 1 # Misc* before int subset
152
+ XML_PARSER_PI = 2 # Within a processing instruction
153
+ XML_PARSER_DTD = 3 # within some DTD content
154
+ XML_PARSER_PROLOG = 4 # Misc* after internal subset
155
+ XML_PARSER_COMMENT = 5 # within a comment
156
+ XML_PARSER_START_TAG = 6 # within a start tag
157
+ XML_PARSER_CONTENT = 7 # within the content
158
+ XML_PARSER_CDATA_SECTION = 8 # within a CDATA section
159
+ XML_PARSER_END_TAG = 9 # within a closing tag
160
+ XML_PARSER_ENTITY_DECL = 10 # within an entity declaration
161
+ XML_PARSER_ENTITY_VALUE = 11 # within an entity value in a decl
162
+ XML_PARSER_ATTRIBUTE_VALUE = 12 # within an attribute value
163
+ XML_PARSER_SYSTEM_LITERAL = 13 # within a SYSTEM value
164
+ XML_PARSER_EPILOG = 14 # the Misc* after the last end tag
165
+ XML_PARSER_IGNORE = 15 # within an IGNORED section
166
+ XML_PARSER_PUBLIC_LITERAL = 16 # within a PUBLIC value
167
+
168
+
169
+ ctypedef struct xmlParserCtxt:
170
+ xmlDoc* myDoc
171
+ xmlDict* dict
172
+ int dictNames
173
+ void* _private
174
+ bint wellFormed
175
+ bint recovery
176
+ int options
177
+ bint disableSAX
178
+ int errNo
179
+ xmlParserInputState instate
180
+ bint replaceEntities
181
+ int loadsubset # != 0 if enabled, int value == why
182
+ bint validate
183
+ xmlError lastError
184
+ xmlNode* node
185
+ xmlSAXHandler* sax
186
+ void* userData
187
+ int* spaceTab
188
+ int spaceMax
189
+ int nsNr
190
+ bint html
191
+ bint progressive
192
+ int inSubset
193
+ int charset
194
+ xmlParserInput* input
195
+ int inputNr
196
+ xmlParserInput* inputTab[]
197
+
198
+ ctypedef enum xmlParserOption:
199
+ XML_PARSE_RECOVER = 0x1 # recover on errors
200
+ XML_PARSE_NOENT = 0x2 # substitute entities
201
+ XML_PARSE_DTDLOAD = 0x4 # load the external subset
202
+ XML_PARSE_DTDATTR = 0x8 # default DTD attributes
203
+ XML_PARSE_DTDVALID = 0x10 # validate with the DTD
204
+ XML_PARSE_NOERROR = 0x20 # suppress error reports
205
+ XML_PARSE_NOWARNING = 0x40 # suppress warning reports
206
+ XML_PARSE_PEDANTIC = 0x80 # pedantic error reporting
207
+ XML_PARSE_NOBLANKS = 0x100 # remove blank nodes
208
+ XML_PARSE_SAX1 = 0x200 # use the SAX1 interface internally
209
+ XML_PARSE_XINCLUDE = 0x400 # Implement XInclude substitution
210
+ XML_PARSE_NONET = 0x800 # Forbid network access
211
+ XML_PARSE_NODICT = 0x1000 # Do not reuse the context dictionary
212
+ XML_PARSE_NSCLEAN = 0x2000 # remove redundant namespaces declarations
213
+ XML_PARSE_NOCDATA = 0x4000 # merge CDATA as text nodes
214
+ XML_PARSE_NOXINCNODE = 0x8000 # do not generate XINCLUDE START/END nodes
215
+ # libxml2 2.6.21+ only:
216
+ XML_PARSE_COMPACT = 0x1_0000 # compact small text nodes
217
+ # libxml2 2.7.0+ only:
218
+ XML_PARSE_OLD10 = 0x2_0000 # parse using XML-1.0 before update 5
219
+ XML_PARSE_NOBASEFIX = 0x4_0000 # do not fixup XINCLUDE xml:base uris
220
+ XML_PARSE_HUGE = 0x8_0000 # relax any hardcoded limit from the parser
221
+ # libxml2 2.7.3+ only:
222
+ XML_PARSE_OLDSAX = 0x10_0000 # parse using SAX2 interface before 2.7.0
223
+ # libxml2 2.8.0+ only:
224
+ XML_PARSE_IGNORE_ENC = 0x20_0000 # ignore internal document encoding hint
225
+ # libxml2 2.9.0+ only:
226
+ XML_PARSE_BIG_LINES = 0x40_0000 # Store big lines numbers in text PSVI field
227
+ # libxml2 2.13.0+ only:
228
+ XML_PARSE_NO_XXE = 0x80_0000 # Disable loading of external DTDs or entities
229
+ # libxml2 2.14.0+ only:
230
+ XML_PARSE_UNZIP = 0x100_0000 # Enable input decompression (and potential gzip bombs)
231
+ XML_PARSE_NO_SYS_CATALOG = 0x200_0000 # Disable the global system XML catalog
232
+ XML_PARSE_CATALOG_PI = 0x400_0000 # Enable XML catalog processing instructions
233
+ # libxml2 2.15.0+ only:
234
+ XML_PARSE_SKIP_IDS = 0x800_0000 # Force the parser to ignore IDs
235
+
236
+ cdef void xmlInitParser()
237
+ cdef void xmlCleanupParser()
238
+
239
+ cdef int xmlLineNumbersDefault(int onoff)
240
+ cdef xmlParserCtxt* xmlNewParserCtxt()
241
+ cdef xmlParserInput* xmlNewIOInputStream(xmlParserCtxt* ctxt,
242
+ xmlParserInputBuffer* input,
243
+ int enc)
244
+ cdef int xmlCtxtUseOptions(xmlParserCtxt* ctxt, int options)
245
+ cdef void xmlFreeParserCtxt(xmlParserCtxt* ctxt)
246
+ cdef void xmlCtxtReset(xmlParserCtxt* ctxt)
247
+ cdef void xmlClearParserCtxt(xmlParserCtxt* ctxt)
248
+ cdef int xmlParseChunk(xmlParserCtxt* ctxt,
249
+ char* chunk, int size, int terminate)
250
+ cdef xmlDoc* xmlCtxtReadDoc(xmlParserCtxt* ctxt,
251
+ char* cur, char* URL, char* encoding,
252
+ int options)
253
+ cdef xmlDoc* xmlCtxtReadFile(xmlParserCtxt* ctxt,
254
+ char* filename, char* encoding,
255
+ int options)
256
+ cdef xmlDoc* xmlCtxtReadIO(xmlParserCtxt* ctxt,
257
+ xmlInputReadCallback ioread,
258
+ xmlInputCloseCallback ioclose,
259
+ void* ioctx,
260
+ char* URL, char* encoding,
261
+ int options)
262
+ cdef xmlDoc* xmlCtxtReadMemory(xmlParserCtxt* ctxt,
263
+ char* buffer, int size,
264
+ char* filename, const_char* encoding,
265
+ int options)
266
+
267
+ cdef void xmlErrParser(xmlParserCtxt* ctxt, xmlNode* node,
268
+ int domain, int code, xmlErrorLevel level,
269
+ const xmlChar *str1, const xmlChar *str2, const xmlChar *str3,
270
+ int int1, const char *msg, ...)
271
+
272
+
273
+ # iterparse:
274
+
275
+ cdef xmlParserCtxt* xmlCreatePushParserCtxt(xmlSAXHandler* sax,
276
+ void* user_data,
277
+ char* chunk,
278
+ int size,
279
+ char* filename)
280
+
281
+ cdef int xmlCtxtResetPush(xmlParserCtxt* ctxt,
282
+ char* chunk,
283
+ int size,
284
+ char* filename,
285
+ char* encoding)
286
+
287
+ # entity loaders:
288
+
289
+ ctypedef xmlParserInput* (*xmlExternalEntityLoader)(
290
+ const_char * URL, const_char * ID, xmlParserCtxt* context) noexcept
291
+ cdef xmlExternalEntityLoader xmlGetExternalEntityLoader()
292
+ cdef void xmlSetExternalEntityLoader(xmlExternalEntityLoader f)
293
+
294
+ cdef xmlEntity* xmlSAX2GetEntity(void* ctxt, const_xmlChar* name) noexcept
295
+
296
+ # DTDs:
297
+
298
+ cdef xmlDtd* xmlParseDTD(const_xmlChar* ExternalID, const_xmlChar* SystemID)
299
+ cdef xmlDtd* xmlIOParseDTD(xmlSAXHandler* sax,
300
+ xmlParserInputBuffer* input,
301
+ int enc)
302
+
303
+
304
+ cdef extern from "libxml/parserInternals.h" nogil:
305
+ """
306
+ #if LIBXML_VERSION < 21400
307
+ #define xmlNewInputFromMemory(url, mem, size, flags) (NULL)
308
+ #endif
309
+ """
310
+ cdef xmlParserInput* xmlNewInputStream(xmlParserCtxt* ctxt)
311
+ cdef xmlParserInput* xmlNewStringInputStream(xmlParserCtxt* ctxt,
312
+ char* buffer)
313
+ cdef xmlParserInput* xmlNewInputFromFile(xmlParserCtxt* ctxt,
314
+ char* filename)
315
+ cdef xmlParserInput* xmlNewInputFromMemory(
316
+ const char *url, const void *mem, size_t size, int flags) # actually "xmlParserInputFlags flags"
317
+ cdef void xmlFreeInputStream(xmlParserInput* input)
318
+ cdef int xmlSwitchEncoding(xmlParserCtxt* ctxt, int enc)
319
+ cdef bint xmlCtxtIsStopped(xmlParserCtxt* ctxt)
.venv/lib/python3.12/site-packages/lxml/includes/xmlschema.pxd ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes.tree cimport xmlDoc
2
+ from lxml.includes.xmlparser cimport xmlSAXHandler
3
+ from lxml.includes.xmlerror cimport xmlStructuredErrorFunc
4
+
5
+ cdef extern from "libxml/xmlschemas.h" nogil:
6
+ ctypedef struct xmlSchema
7
+ ctypedef struct xmlSchemaParserCtxt
8
+
9
+ ctypedef struct xmlSchemaSAXPlugStruct
10
+ ctypedef struct xmlSchemaValidCtxt
11
+
12
+ ctypedef enum xmlSchemaValidOption:
13
+ XML_SCHEMA_VAL_VC_I_CREATE = 1
14
+
15
+ cdef xmlSchemaValidCtxt* xmlSchemaNewValidCtxt(xmlSchema* schema) nogil
16
+ cdef void xmlSchemaSetParserStructuredErrors(xmlSchemaParserCtxt* ctxt,
17
+ xmlStructuredErrorFunc serror, void *ctx)
18
+ cdef void xmlSchemaSetValidStructuredErrors(xmlSchemaValidCtxt* ctxt,
19
+ xmlStructuredErrorFunc serror, void *ctx)
20
+
21
+ cdef int xmlSchemaValidateDoc(xmlSchemaValidCtxt* ctxt, xmlDoc* doc) nogil
22
+ cdef xmlSchema* xmlSchemaParse(xmlSchemaParserCtxt* ctxt) nogil
23
+ cdef xmlSchemaParserCtxt* xmlSchemaNewParserCtxt(char* URL) nogil
24
+ cdef xmlSchemaParserCtxt* xmlSchemaNewDocParserCtxt(xmlDoc* doc) nogil
25
+ cdef void xmlSchemaFree(xmlSchema* schema) nogil
26
+ cdef void xmlSchemaFreeParserCtxt(xmlSchemaParserCtxt* ctxt) nogil
27
+ cdef void xmlSchemaFreeValidCtxt(xmlSchemaValidCtxt* ctxt) nogil
28
+ cdef int xmlSchemaSetValidOptions(xmlSchemaValidCtxt* ctxt,
29
+ int options) nogil
30
+
31
+ cdef xmlSchemaSAXPlugStruct* xmlSchemaSAXPlug(xmlSchemaValidCtxt* ctxt,
32
+ xmlSAXHandler** sax,
33
+ void** data) nogil
34
+ cdef int xmlSchemaSAXUnplug(xmlSchemaSAXPlugStruct* sax_plug)
35
+ cdef int xmlSchemaIsValid(xmlSchemaValidCtxt* ctxt)
.venv/lib/python3.12/site-packages/lxml/includes/xpath.pxd ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes cimport tree
2
+ from lxml.includes cimport xmlerror
3
+
4
+ from libc.string cimport const_char
5
+ from lxml.includes.tree cimport xmlChar, const_xmlChar
6
+
7
+
8
+ cdef extern from "libxml/xpath.h" nogil:
9
+ ctypedef enum xmlXPathObjectType:
10
+ XPATH_UNDEFINED = 0
11
+ XPATH_NODESET = 1
12
+ XPATH_BOOLEAN = 2
13
+ XPATH_NUMBER = 3
14
+ XPATH_STRING = 4
15
+ XPATH_POINT = 5
16
+ XPATH_RANGE = 6
17
+ XPATH_LOCATIONSET = 7
18
+ XPATH_USERS = 8
19
+ XPATH_XSLT_TREE = 9
20
+
21
+ ctypedef enum xmlXPathError:
22
+ XPATH_EXPRESSION_OK = 0
23
+ XPATH_NUMBER_ERROR = 1
24
+ XPATH_UNFINISHED_LITERAL_ERROR = 2
25
+ XPATH_START_LITERAL_ERROR = 3
26
+ XPATH_VARIABLE_REF_ERROR = 4
27
+ XPATH_UNDEF_VARIABLE_ERROR = 5
28
+ XPATH_INVALID_PREDICATE_ERROR = 6
29
+ XPATH_EXPR_ERROR = 7
30
+ XPATH_UNCLOSED_ERROR = 8
31
+ XPATH_UNKNOWN_FUNC_ERROR = 9
32
+ XPATH_INVALID_OPERAND = 10
33
+ XPATH_INVALID_TYPE = 11
34
+ XPATH_INVALID_ARITY = 12
35
+ XPATH_INVALID_CTXT_SIZE = 13
36
+ XPATH_INVALID_CTXT_POSITION = 14
37
+ XPATH_MEMORY_ERROR = 15
38
+ XPTR_SYNTAX_ERROR = 16
39
+ XPTR_RESOURCE_ERROR = 17
40
+ XPTR_SUB_RESOURCE_ERROR = 18
41
+ XPATH_UNDEF_PREFIX_ERROR = 19
42
+ XPATH_ENCODING_ERROR = 20
43
+ XPATH_INVALID_CHAR_ERROR = 21
44
+ XPATH_INVALID_CTXT = 22
45
+
46
+ ctypedef struct xmlNodeSet:
47
+ int nodeNr
48
+ int nodeMax
49
+ tree.xmlNode** nodeTab
50
+
51
+ ctypedef struct xmlXPathObject:
52
+ xmlXPathObjectType type
53
+ xmlNodeSet* nodesetval
54
+ bint boolval
55
+ double floatval
56
+ xmlChar* stringval
57
+
58
+ ctypedef struct xmlXPathContext:
59
+ tree.xmlDoc* doc
60
+ tree.xmlNode* node
61
+ tree.xmlDict* dict
62
+ tree.xmlHashTable* nsHash
63
+ const_xmlChar* function
64
+ const_xmlChar* functionURI
65
+ xmlerror.xmlStructuredErrorFunc error
66
+ xmlerror.xmlError lastError
67
+ void* userData
68
+
69
+ ctypedef struct xmlXPathParserContext:
70
+ xmlXPathContext* context
71
+ xmlXPathObject* value
72
+ tree.xmlNode* ancestor
73
+ int error
74
+
75
+ ctypedef struct xmlXPathCompExpr
76
+
77
+ ctypedef void (*xmlXPathFunction)(xmlXPathParserContext* ctxt, int nargs)
78
+ ctypedef xmlXPathFunction (*xmlXPathFuncLookupFunc)(void* ctxt,
79
+ const_xmlChar* name,
80
+ const_xmlChar* ns_uri)
81
+
82
+ cdef xmlXPathContext* xmlXPathNewContext(tree.xmlDoc* doc)
83
+ cdef xmlXPathObject* xmlXPathEvalExpression(const_xmlChar* str,
84
+ xmlXPathContext* ctxt)
85
+ cdef xmlXPathObject* xmlXPathCompiledEval(xmlXPathCompExpr* comp,
86
+ xmlXPathContext* ctxt)
87
+ cdef xmlXPathCompExpr* xmlXPathCompile(const_xmlChar* str)
88
+ cdef xmlXPathCompExpr* xmlXPathCtxtCompile(xmlXPathContext* ctxt,
89
+ const_xmlChar* str)
90
+ cdef void xmlXPathFreeContext(xmlXPathContext* ctxt)
91
+ cdef void xmlXPathFreeCompExpr(xmlXPathCompExpr* comp)
92
+ cdef void xmlXPathFreeObject(xmlXPathObject* obj)
93
+ cdef int xmlXPathRegisterNs(xmlXPathContext* ctxt,
94
+ const_xmlChar* prefix, const_xmlChar* ns_uri)
95
+
96
+ cdef xmlNodeSet* xmlXPathNodeSetCreate(tree.xmlNode* val)
97
+ cdef void xmlXPathFreeNodeSet(xmlNodeSet* val)
98
+
99
+
100
+ cdef extern from "libxml/xpathInternals.h" nogil:
101
+ cdef int xmlXPathRegisterFunc(xmlXPathContext* ctxt,
102
+ const_xmlChar* name,
103
+ xmlXPathFunction f)
104
+ cdef int xmlXPathRegisterFuncNS(xmlXPathContext* ctxt,
105
+ const_xmlChar* name,
106
+ const_xmlChar* ns_uri,
107
+ xmlXPathFunction f)
108
+ cdef void xmlXPathRegisterFuncLookup(xmlXPathContext *ctxt,
109
+ xmlXPathFuncLookupFunc f,
110
+ void *funcCtxt)
111
+ cdef int xmlXPathRegisterVariable(xmlXPathContext *ctxt,
112
+ const_xmlChar* name,
113
+ xmlXPathObject* value)
114
+ cdef int xmlXPathRegisterVariableNS(xmlXPathContext *ctxt,
115
+ const_xmlChar* name,
116
+ const_xmlChar* ns_uri,
117
+ xmlXPathObject* value)
118
+ cdef void xmlXPathRegisteredVariablesCleanup(xmlXPathContext *ctxt)
119
+ cdef void xmlXPathRegisteredNsCleanup(xmlXPathContext *ctxt)
120
+ cdef xmlXPathObject* valuePop (xmlXPathParserContext *ctxt)
121
+ cdef int valuePush(xmlXPathParserContext* ctxt, xmlXPathObject *value)
122
+
123
+ cdef xmlXPathObject* xmlXPathNewCString(const_char *val)
124
+ cdef xmlXPathObject* xmlXPathWrapCString(const_char * val)
125
+ cdef xmlXPathObject* xmlXPathNewString(const_xmlChar *val)
126
+ cdef xmlXPathObject* xmlXPathWrapString(const_xmlChar * val)
127
+ cdef xmlXPathObject* xmlXPathNewFloat(double val)
128
+ cdef xmlXPathObject* xmlXPathNewBoolean(int val)
129
+ cdef xmlXPathObject* xmlXPathNewNodeSet(tree.xmlNode* val)
130
+ cdef xmlXPathObject* xmlXPathNewValueTree(tree.xmlNode* val)
131
+ cdef void xmlXPathNodeSetAdd(xmlNodeSet* cur,
132
+ tree.xmlNode* val)
133
+ cdef void xmlXPathNodeSetAddUnique(xmlNodeSet* cur,
134
+ tree.xmlNode* val)
135
+ cdef xmlXPathObject* xmlXPathWrapNodeSet(xmlNodeSet* val)
136
+ cdef void xmlXPathErr(xmlXPathParserContext* ctxt, int error)
.venv/lib/python3.12/site-packages/lxml/includes/xslt.pxd ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from lxml.includes.tree cimport xmlDoc, xmlNode, xmlDict, xmlChar, const_xmlChar, xmlOutputBuffer
2
+ from lxml.includes.xmlerror cimport xmlGenericErrorFunc
3
+ from lxml.includes.xpath cimport xmlXPathContext, xmlXPathFunction
4
+
5
+ from libc.string cimport const_char
6
+
7
+ cdef extern from "libxslt/xslt.h":
8
+ cdef int xsltLibxsltVersion
9
+ cdef int xsltMaxDepth
10
+
11
+ cdef extern from "libxslt/xsltconfig.h":
12
+ cdef int LIBXSLT_VERSION
13
+
14
+ cdef extern from "libxslt/xsltInternals.h" nogil:
15
+ ctypedef enum xsltTransformState:
16
+ XSLT_STATE_OK # 0
17
+ XSLT_STATE_ERROR # 1
18
+ XSLT_STATE_STOPPED # 2
19
+
20
+ ctypedef struct xsltDocument:
21
+ xmlDoc* doc
22
+
23
+ ctypedef struct xsltStylesheet:
24
+ xmlChar* encoding
25
+ xmlDoc* doc
26
+ int errors
27
+
28
+ ctypedef struct xsltTransformContext:
29
+ xsltStylesheet* style
30
+ xmlXPathContext* xpathCtxt
31
+ xsltDocument* document
32
+ void* _private
33
+ xmlDict* dict
34
+ int profile
35
+ xmlNode* node
36
+ xmlDoc* output
37
+ xmlNode* insert
38
+ xmlNode* inst
39
+ xsltTransformState state
40
+
41
+ ctypedef struct xsltStackElem
42
+
43
+ ctypedef struct xsltTemplate
44
+
45
+ cdef xsltStylesheet* xsltParseStylesheetDoc(xmlDoc* doc)
46
+ cdef void xsltFreeStylesheet(xsltStylesheet* sheet)
47
+
48
+ cdef extern from "libxslt/imports.h" nogil:
49
+ # actually defined in "etree_defs.h"
50
+ cdef void LXML_GET_XSLT_ENCODING(const_xmlChar* result_var, xsltStylesheet* style)
51
+
52
+ cdef extern from "libxslt/extensions.h" nogil:
53
+ ctypedef void (*xsltTransformFunction)(xsltTransformContext* ctxt,
54
+ xmlNode* context_node,
55
+ xmlNode* inst,
56
+ void* precomp_unused) noexcept
57
+
58
+ cdef int xsltRegisterExtFunction(xsltTransformContext* ctxt,
59
+ const_xmlChar* name,
60
+ const_xmlChar* URI,
61
+ xmlXPathFunction function)
62
+ cdef int xsltRegisterExtModuleFunction(const_xmlChar* name, const_xmlChar* URI,
63
+ xmlXPathFunction function)
64
+ cdef int xsltUnregisterExtModuleFunction(const_xmlChar* name, const_xmlChar* URI)
65
+ cdef xmlXPathFunction xsltExtModuleFunctionLookup(
66
+ const_xmlChar* name, const_xmlChar* URI)
67
+ cdef int xsltRegisterExtPrefix(xsltStylesheet* style,
68
+ const_xmlChar* prefix, const_xmlChar* URI)
69
+ cdef int xsltRegisterExtElement(xsltTransformContext* ctxt,
70
+ const_xmlChar* name, const_xmlChar* URI,
71
+ xsltTransformFunction function)
72
+
73
+ cdef extern from "libxslt/documents.h" nogil:
74
+ ctypedef enum xsltLoadType:
75
+ XSLT_LOAD_START
76
+ XSLT_LOAD_STYLESHEET
77
+ XSLT_LOAD_DOCUMENT
78
+
79
+ ctypedef xmlDoc* (*xsltDocLoaderFunc)(const_xmlChar* URI, xmlDict* dict,
80
+ int options,
81
+ void* ctxt,
82
+ xsltLoadType type) noexcept
83
+ cdef xsltDocLoaderFunc xsltDocDefaultLoader
84
+ cdef void xsltSetLoaderFunc(xsltDocLoaderFunc f)
85
+
86
+ cdef extern from "libxslt/transform.h" nogil:
87
+ cdef xmlDoc* xsltApplyStylesheet(xsltStylesheet* style, xmlDoc* doc,
88
+ const_char** params)
89
+ cdef xmlDoc* xsltApplyStylesheetUser(xsltStylesheet* style, xmlDoc* doc,
90
+ const_char** params, const_char* output,
91
+ void* profile,
92
+ xsltTransformContext* context)
93
+ cdef void xsltProcessOneNode(xsltTransformContext* ctxt,
94
+ xmlNode* contextNode,
95
+ xsltStackElem* params)
96
+ cdef xsltTransformContext* xsltNewTransformContext(xsltStylesheet* style,
97
+ xmlDoc* doc)
98
+ cdef void xsltFreeTransformContext(xsltTransformContext* context)
99
+ cdef void xsltApplyOneTemplate(xsltTransformContext* ctxt,
100
+ xmlNode* contextNode, xmlNode* list,
101
+ xsltTemplate* templ,
102
+ xsltStackElem* params)
103
+
104
+
105
+ cdef extern from "libxslt/xsltutils.h" nogil:
106
+ cdef int xsltSaveResultToString(xmlChar** doc_txt_ptr,
107
+ int* doc_txt_len,
108
+ xmlDoc* result,
109
+ xsltStylesheet* style)
110
+ cdef int xsltSaveResultToFilename(const_char *URL,
111
+ xmlDoc* result,
112
+ xsltStylesheet* style,
113
+ int compression)
114
+ cdef int xsltSaveResultTo(xmlOutputBuffer* buf,
115
+ xmlDoc* result,
116
+ xsltStylesheet* style)
117
+ cdef xmlGenericErrorFunc xsltGenericError
118
+ cdef void *xsltGenericErrorContext
119
+ cdef void xsltSetGenericErrorFunc(
120
+ void* ctxt, void (*handler)(void* ctxt, char* msg, ...) nogil)
121
+ cdef void xsltSetTransformErrorFunc(
122
+ xsltTransformContext*, void* ctxt,
123
+ void (*handler)(void* ctxt, char* msg, ...) nogil)
124
+ cdef void xsltTransformError(xsltTransformContext* ctxt,
125
+ xsltStylesheet* style,
126
+ xmlNode* node, char* msg, ...)
127
+ cdef void xsltSetCtxtParseOptions(
128
+ xsltTransformContext* ctxt, int options)
129
+
130
+
131
+ cdef extern from "libxslt/security.h" nogil:
132
+ ctypedef struct xsltSecurityPrefs
133
+ ctypedef enum xsltSecurityOption:
134
+ XSLT_SECPREF_READ_FILE = 1
135
+ XSLT_SECPREF_WRITE_FILE = 2
136
+ XSLT_SECPREF_CREATE_DIRECTORY = 3
137
+ XSLT_SECPREF_READ_NETWORK = 4
138
+ XSLT_SECPREF_WRITE_NETWORK = 5
139
+
140
+ ctypedef int (*xsltSecurityCheck)(xsltSecurityPrefs* sec,
141
+ xsltTransformContext* ctxt,
142
+ char* value) noexcept
143
+
144
+ cdef xsltSecurityPrefs* xsltNewSecurityPrefs()
145
+ cdef void xsltFreeSecurityPrefs(xsltSecurityPrefs* sec)
146
+ cdef int xsltSecurityForbid(xsltSecurityPrefs* sec,
147
+ xsltTransformContext* ctxt,
148
+ char* value)
149
+ cdef int xsltSecurityAllow(xsltSecurityPrefs* sec,
150
+ xsltTransformContext* ctxt,
151
+ char* value)
152
+ cdef int xsltSetSecurityPrefs(xsltSecurityPrefs* sec,
153
+ xsltSecurityOption option,
154
+ xsltSecurityCheck func)
155
+ cdef xsltSecurityCheck xsltGetSecurityPrefs(
156
+ xsltSecurityPrefs* sec,
157
+ xsltSecurityOption option)
158
+ cdef int xsltSetCtxtSecurityPrefs(xsltSecurityPrefs* sec,
159
+ xsltTransformContext* ctxt)
160
+ cdef xmlDoc* xsltGetProfileInformation(xsltTransformContext* ctxt)
161
+
162
+ cdef extern from "libxslt/variables.h" nogil:
163
+ cdef int xsltQuoteUserParams(xsltTransformContext* ctxt,
164
+ const_char** params)
165
+ cdef int xsltQuoteOneUserParam(xsltTransformContext* ctxt,
166
+ const_xmlChar* name,
167
+ const_xmlChar* value)
168
+
169
+ cdef extern from "libxslt/extra.h" nogil:
170
+ const_xmlChar* XSLT_LIBXSLT_NAMESPACE
171
+ const_xmlChar* XSLT_XALAN_NAMESPACE
172
+ const_xmlChar* XSLT_SAXON_NAMESPACE
173
+ const_xmlChar* XSLT_XT_NAMESPACE
174
+
175
+ cdef xmlXPathFunction xsltFunctionNodeSet
176
+ cdef void xsltRegisterAllExtras()
177
+
178
+ cdef extern from "libexslt/exslt.h" nogil:
179
+ cdef void exsltRegisterAll()
180
+
181
+ # libexslt 1.1.25+
182
+ const_xmlChar* EXSLT_DATE_NAMESPACE
183
+ const_xmlChar* EXSLT_SETS_NAMESPACE
184
+ const_xmlChar* EXSLT_MATH_NAMESPACE
185
+ const_xmlChar* EXSLT_STRINGS_NAMESPACE
186
+
187
+ cdef int exsltDateXpathCtxtRegister(xmlXPathContext* ctxt, const_xmlChar* prefix)
188
+ cdef int exsltSetsXpathCtxtRegister(xmlXPathContext* ctxt, const_xmlChar* prefix)
189
+ cdef int exsltMathXpathCtxtRegister(xmlXPathContext* ctxt, const_xmlChar* prefix)
190
+ cdef int exsltStrXpathCtxtRegister(xmlXPathContext* ctxt, const_xmlChar* prefix)
.venv/lib/python3.12/site-packages/lxml/isoschematron/__init__.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The ``lxml.isoschematron`` package implements ISO Schematron support on top
2
+ of the pure-xslt 'skeleton' implementation.
3
+ """
4
+
5
+ import sys
6
+ import os.path
7
+ from lxml import etree as _etree # due to validator __init__ signature
8
+
9
+
10
+ # some compat stuff, borrowed from lxml.html
11
+ try:
12
+ unicode
13
+ except NameError:
14
+ # Python 3
15
+ unicode = str
16
+ try:
17
+ basestring
18
+ except NameError:
19
+ # Python 3
20
+ basestring = str
21
+
22
+
23
+ __all__ = ['extract_xsd', 'extract_rng', 'iso_dsdl_include',
24
+ 'iso_abstract_expand', 'iso_svrl_for_xslt1',
25
+ 'svrl_validation_errors', 'schematron_schema_valid',
26
+ 'stylesheet_params', 'Schematron']
27
+
28
+
29
+ # some namespaces
30
+ #FIXME: Maybe lxml should provide a dedicated place for common namespace
31
+ #FIXME: definitions?
32
+ XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema"
33
+ RELAXNG_NS = "http://relaxng.org/ns/structure/1.0"
34
+ SCHEMATRON_NS = "http://purl.oclc.org/dsdl/schematron"
35
+ SVRL_NS = "http://purl.oclc.org/dsdl/svrl"
36
+
37
+
38
+ # some helpers
39
+ _schematron_root = '{%s}schema' % SCHEMATRON_NS
40
+ _xml_schema_root = '{%s}schema' % XML_SCHEMA_NS
41
+ _resources_dir = os.path.join(os.path.dirname(__file__), 'resources')
42
+
43
+
44
+ # the iso-schematron skeleton implementation steps aka xsl transformations
45
+ extract_xsd = _etree.XSLT(_etree.parse(
46
+ os.path.join(_resources_dir, 'xsl', 'XSD2Schtrn.xsl')))
47
+ extract_rng = _etree.XSLT(_etree.parse(
48
+ os.path.join(_resources_dir, 'xsl', 'RNG2Schtrn.xsl')))
49
+ iso_dsdl_include = _etree.XSLT(_etree.parse(
50
+ os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1',
51
+ 'iso_dsdl_include.xsl')))
52
+ iso_abstract_expand = _etree.XSLT(_etree.parse(
53
+ os.path.join(_resources_dir, 'xsl', 'iso-schematron-xslt1',
54
+ 'iso_abstract_expand.xsl')))
55
+ iso_svrl_for_xslt1 = _etree.XSLT(_etree.parse(
56
+ os.path.join(_resources_dir,
57
+ 'xsl', 'iso-schematron-xslt1', 'iso_svrl_for_xslt1.xsl')))
58
+
59
+
60
+ # svrl result accessors
61
+ svrl_validation_errors = _etree.XPath(
62
+ '//svrl:failed-assert', namespaces={'svrl': SVRL_NS})
63
+
64
+ # RelaxNG validator for schematron schemas
65
+ schematron_schema_valid_supported = False
66
+ try:
67
+ schematron_schema_valid = _etree.RelaxNG(
68
+ file=os.path.join(_resources_dir, 'rng', 'iso-schematron.rng'))
69
+ schematron_schema_valid_supported = True
70
+ except _etree.RelaxNGParseError:
71
+ # Some distributions delete the file due to licensing issues.
72
+ def schematron_schema_valid(arg):
73
+ raise NotImplementedError("Validating the ISO schematron requires iso-schematron.rng")
74
+
75
+
76
+ def stylesheet_params(**kwargs):
77
+ """Convert keyword args to a dictionary of stylesheet parameters.
78
+ XSL stylesheet parameters must be XPath expressions, i.e.:
79
+
80
+ * string expressions, like "'5'"
81
+ * simple (number) expressions, like "5"
82
+ * valid XPath expressions, like "/a/b/text()"
83
+
84
+ This function converts native Python keyword arguments to stylesheet
85
+ parameters following these rules:
86
+ If an arg is a string wrap it with XSLT.strparam().
87
+ If an arg is an XPath object use its path string.
88
+ If arg is None raise TypeError.
89
+ Else convert arg to string.
90
+ """
91
+ result = {}
92
+ for key, val in kwargs.items():
93
+ if isinstance(val, basestring):
94
+ val = _etree.XSLT.strparam(val)
95
+ elif val is None:
96
+ raise TypeError('None not allowed as a stylesheet parameter')
97
+ elif not isinstance(val, _etree.XPath):
98
+ val = unicode(val)
99
+ result[key] = val
100
+ return result
101
+
102
+
103
+ # helper function for use in Schematron __init__
104
+ def _stylesheet_param_dict(paramsDict, kwargsDict):
105
+ """Return a copy of paramsDict, updated with kwargsDict entries, wrapped as
106
+ stylesheet arguments.
107
+ kwargsDict entries with a value of None are ignored.
108
+ """
109
+ # beware of changing mutable default arg
110
+ paramsDict = dict(paramsDict)
111
+ for k, v in kwargsDict.items():
112
+ if v is not None: # None values do not override
113
+ paramsDict[k] = v
114
+ paramsDict = stylesheet_params(**paramsDict)
115
+ return paramsDict
116
+
117
+
118
+ class Schematron(_etree._Validator):
119
+ """An ISO Schematron validator.
120
+
121
+ Pass a root Element or an ElementTree to turn it into a validator.
122
+ Alternatively, pass a filename as keyword argument 'file' to parse from
123
+ the file system.
124
+
125
+ Schematron is a less well known, but very powerful schema language.
126
+ The main idea is to use the capabilities of XPath to put restrictions on
127
+ the structure and the content of XML documents.
128
+
129
+ The standard behaviour is to fail on ``failed-assert`` findings only
130
+ (``ASSERTS_ONLY``). To change this, you can either pass a report filter
131
+ function to the ``error_finder`` parameter (e.g. ``ASSERTS_AND_REPORTS``
132
+ or a custom ``XPath`` object), or subclass isoschematron.Schematron for
133
+ complete control of the validation process.
134
+
135
+ Built on the Schematron language 'reference' skeleton pure-xslt
136
+ implementation, the validator is created as an XSLT 1.0 stylesheet using
137
+ these steps:
138
+
139
+ 0) (Extract from XML Schema or RelaxNG schema)
140
+ 1) Process inclusions
141
+ 2) Process abstract patterns
142
+ 3) Compile the schematron schema to XSLT
143
+
144
+ The ``include`` and ``expand`` keyword arguments can be used to switch off
145
+ steps 1) and 2).
146
+ To set parameters for steps 1), 2) and 3) hand parameter dictionaries to the
147
+ keyword arguments ``include_params``, ``expand_params`` or
148
+ ``compile_params``.
149
+ For convenience, the compile-step parameter ``phase`` is also exposed as a
150
+ keyword argument ``phase``. This takes precedence if the parameter is also
151
+ given in the parameter dictionary.
152
+
153
+ If ``store_schematron`` is set to True, the (included-and-expanded)
154
+ schematron document tree is stored and available through the ``schematron``
155
+ property.
156
+ If ``store_xslt`` is set to True, the validation XSLT document tree will be
157
+ stored and can be retrieved through the ``validator_xslt`` property.
158
+ With ``store_report`` set to True (default: False), the resulting validation
159
+ report document gets stored and can be accessed as the ``validation_report``
160
+ property.
161
+
162
+ If ``validate_schema`` is set to False, the validation of the schema file
163
+ itself is disabled. Validation happens by default after building the full
164
+ schema, unless the schema validation file cannot be found at import time,
165
+ in which case the validation gets disabled. Some lxml distributions exclude
166
+ this file due to licensing issues. ISO-Schematron validation can then still
167
+ be used normally, but the schemas themselves cannot be validated.
168
+
169
+ Here is a usage example::
170
+
171
+ >>> from lxml import etree
172
+ >>> from lxml.isoschematron import Schematron
173
+
174
+ >>> schematron = Schematron(etree.XML('''
175
+ ... <schema xmlns="http://purl.oclc.org/dsdl/schematron" >
176
+ ... <pattern id="id_only_attribute">
177
+ ... <title>id is the only permitted attribute name</title>
178
+ ... <rule context="*">
179
+ ... <report test="@*[not(name()='id')]">Attribute
180
+ ... <name path="@*[not(name()='id')]"/> is forbidden<name/>
181
+ ... </report>
182
+ ... </rule>
183
+ ... </pattern>
184
+ ... </schema>'''),
185
+ ... error_finder=Schematron.ASSERTS_AND_REPORTS)
186
+
187
+ >>> xml = etree.XML('''
188
+ ... <AAA name="aaa">
189
+ ... <BBB id="bbb"/>
190
+ ... <CCC color="ccc"/>
191
+ ... </AAA>
192
+ ... ''')
193
+
194
+ >>> schematron.validate(xml)
195
+ False
196
+
197
+ >>> xml = etree.XML('''
198
+ ... <AAA id="aaa">
199
+ ... <BBB id="bbb"/>
200
+ ... <CCC/>
201
+ ... </AAA>
202
+ ... ''')
203
+
204
+ >>> schematron.validate(xml)
205
+ True
206
+ """
207
+
208
+ # libxml2 error categorization for validation errors
209
+ _domain = _etree.ErrorDomains.SCHEMATRONV
210
+ _level = _etree.ErrorLevels.ERROR
211
+ _error_type = _etree.ErrorTypes.SCHEMATRONV_ASSERT
212
+
213
+ # convenience definitions for common behaviours
214
+ ASSERTS_ONLY = svrl_validation_errors # Default
215
+ ASSERTS_AND_REPORTS = _etree.XPath(
216
+ '//svrl:failed-assert | //svrl:successful-report',
217
+ namespaces={'svrl': SVRL_NS})
218
+
219
+ def _extract(self, element):
220
+ """Extract embedded schematron schema from non-schematron host schema.
221
+ This method will only be called by __init__ if the given schema document
222
+ is not a schematron schema by itself.
223
+ Must return a schematron schema document tree or None.
224
+ """
225
+ schematron = None
226
+ if element.tag == _xml_schema_root:
227
+ schematron = self._extract_xsd(element)
228
+ elif element.nsmap.get(element.prefix) == RELAXNG_NS:
229
+ # RelaxNG does not have a single unique root element
230
+ schematron = self._extract_rng(element)
231
+ return schematron
232
+
233
+ # customization points
234
+ # etree.XSLT objects that provide the extract, include, expand, compile
235
+ # steps
236
+ _extract_xsd = extract_xsd
237
+ _extract_rng = extract_rng
238
+ _include = iso_dsdl_include
239
+ _expand = iso_abstract_expand
240
+ _compile = iso_svrl_for_xslt1
241
+
242
+ # etree.xpath object that determines input document validity when applied to
243
+ # the svrl result report; must return a list of result elements (empty if
244
+ # valid)
245
+ _validation_errors = ASSERTS_ONLY
246
+
247
+ def __init__(self, etree=None, file=None, include=True, expand=True,
248
+ include_params={}, expand_params={}, compile_params={},
249
+ store_schematron=False, store_xslt=False, store_report=False,
250
+ phase=None, error_finder=ASSERTS_ONLY,
251
+ validate_schema=schematron_schema_valid_supported):
252
+ super().__init__()
253
+
254
+ self._store_report = store_report
255
+ self._schematron = None
256
+ self._validator_xslt = None
257
+ self._validation_report = None
258
+ if error_finder is not self.ASSERTS_ONLY:
259
+ self._validation_errors = error_finder
260
+
261
+ # parse schema document, may be a schematron schema or an XML Schema or
262
+ # a RelaxNG schema with embedded schematron rules
263
+ root = None
264
+ try:
265
+ if etree is not None:
266
+ if _etree.iselement(etree):
267
+ root = etree
268
+ else:
269
+ root = etree.getroot()
270
+ elif file is not None:
271
+ root = _etree.parse(file).getroot()
272
+ except Exception:
273
+ raise _etree.SchematronParseError(
274
+ "No tree or file given: %s" % sys.exc_info()[1])
275
+ if root is None:
276
+ raise ValueError("Empty tree")
277
+ if root.tag == _schematron_root:
278
+ schematron = root
279
+ else:
280
+ schematron = self._extract(root)
281
+ if schematron is None:
282
+ raise _etree.SchematronParseError(
283
+ "Document is not a schematron schema or schematron-extractable")
284
+ # perform the iso-schematron skeleton implementation steps to get a
285
+ # validating xslt
286
+ if include:
287
+ schematron = self._include(schematron, **include_params)
288
+ if expand:
289
+ schematron = self._expand(schematron, **expand_params)
290
+ if validate_schema and not schematron_schema_valid(schematron):
291
+ raise _etree.SchematronParseError(
292
+ "invalid schematron schema: %s" %
293
+ schematron_schema_valid.error_log)
294
+ if store_schematron:
295
+ self._schematron = schematron
296
+ # add new compile keyword args here if exposing them
297
+ compile_kwargs = {'phase': phase}
298
+ compile_params = _stylesheet_param_dict(compile_params, compile_kwargs)
299
+ validator_xslt = self._compile(schematron, **compile_params)
300
+ if store_xslt:
301
+ self._validator_xslt = validator_xslt
302
+ self._validator = _etree.XSLT(validator_xslt)
303
+
304
+ def __call__(self, etree):
305
+ """Validate doc using Schematron.
306
+
307
+ Returns true if document is valid, false if not.
308
+ """
309
+ self._clear_error_log()
310
+ result = self._validator(etree)
311
+ if self._store_report:
312
+ self._validation_report = result
313
+ errors = self._validation_errors(result)
314
+ if errors:
315
+ if _etree.iselement(etree):
316
+ fname = etree.getroottree().docinfo.URL or '<file>'
317
+ else:
318
+ fname = etree.docinfo.URL or '<file>'
319
+ for error in errors:
320
+ # Does svrl report the line number, anywhere? Don't think so.
321
+ self._append_log_message(
322
+ domain=self._domain, type=self._error_type,
323
+ level=self._level, line=0,
324
+ message=_etree.tostring(error, encoding='unicode'),
325
+ filename=fname)
326
+ return False
327
+ return True
328
+
329
+ @property
330
+ def schematron(self):
331
+ """ISO-schematron schema document (None if object has been initialized
332
+ with store_schematron=False).
333
+ """
334
+ return self._schematron
335
+
336
+ @property
337
+ def validator_xslt(self):
338
+ """ISO-schematron skeleton implementation XSLT validator document (None
339
+ if object has been initialized with store_xslt=False).
340
+ """
341
+ return self._validator_xslt
342
+
343
+ @property
344
+ def validation_report(self):
345
+ """ISO-schematron validation result report (None if result-storing has
346
+ been turned off).
347
+ """
348
+ return self._validation_report
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng ADDED
@@ -0,0 +1,709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!-- Copyright © ISO/IEC 2015 -->
3
+ <!--
4
+ The following permission notice and disclaimer shall be included in all
5
+ copies of this XML schema ("the Schema"), and derivations of the Schema:
6
+
7
+ Permission is hereby granted, free of charge in perpetuity, to any
8
+ person obtaining a copy of the Schema, to use, copy, modify, merge and
9
+ distribute free of charge, copies of the Schema for the purposes of
10
+ developing, implementing, installing and using software based on the
11
+ Schema, and to permit persons to whom the Schema is furnished to do so,
12
+ subject to the following conditions:
13
+
14
+ THE SCHEMA IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
18
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SCHEMA OR THE USE OR
20
+ OTHER DEALINGS IN THE SCHEMA.
21
+
22
+ In addition, any modified copy of the Schema shall include the following
23
+ notice:
24
+
25
+ "THIS SCHEMA HAS BEEN MODIFIED FROM THE SCHEMA DEFINED IN ISO/IEC 19757-3,
26
+ AND SHOULD NOT BE INTERPRETED AS COMPLYING WITH THAT STANDARD".
27
+ -->
28
+ <grammar ns="http://purl.oclc.org/dsdl/schematron" xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
29
+ <start>
30
+ <ref name="schema"/>
31
+ </start>
32
+ <!-- Element declarations -->
33
+ <define name="schema">
34
+ <element name="schema">
35
+ <optional>
36
+ <attribute name="id">
37
+ <data type="ID"/>
38
+ </attribute>
39
+ </optional>
40
+ <ref name="rich"/>
41
+ <optional>
42
+ <attribute name="schemaVersion">
43
+ <ref name="non-empty-string"/>
44
+ </attribute>
45
+ </optional>
46
+ <optional>
47
+ <attribute name="defaultPhase">
48
+ <data type="IDREF"/>
49
+ </attribute>
50
+ </optional>
51
+ <optional>
52
+ <attribute name="queryBinding">
53
+ <ref name="non-empty-string"/>
54
+ </attribute>
55
+ </optional>
56
+ <interleave>
57
+ <ref name="foreign"/>
58
+ <zeroOrMore>
59
+ <ref name="inclusion"/>
60
+ </zeroOrMore>
61
+ <group>
62
+ <optional>
63
+ <ref name="title"/>
64
+ </optional>
65
+ <zeroOrMore>
66
+ <ref name="ns"/>
67
+ </zeroOrMore>
68
+ <zeroOrMore>
69
+ <ref name="p"/>
70
+ </zeroOrMore>
71
+ <zeroOrMore>
72
+ <ref name="let"/>
73
+ </zeroOrMore>
74
+ <zeroOrMore>
75
+ <ref name="phase"/>
76
+ </zeroOrMore>
77
+ <oneOrMore>
78
+ <ref name="pattern"/>
79
+ </oneOrMore>
80
+ <zeroOrMore>
81
+ <ref name="p"/>
82
+ </zeroOrMore>
83
+ <optional>
84
+ <ref name="diagnostics"/>
85
+ </optional>
86
+ <optional>
87
+ <!-- edited (lxml): required in standard, optional here (since it can be empty anyway) -->
88
+ <ref name="properties"/>
89
+ </optional>
90
+ </group>
91
+ </interleave>
92
+ </element>
93
+ </define>
94
+ <define name="active">
95
+ <element name="active">
96
+ <attribute name="pattern">
97
+ <data type="IDREF"/>
98
+ </attribute>
99
+ <interleave>
100
+ <ref name="foreign"/>
101
+ <zeroOrMore>
102
+ <choice>
103
+ <text/>
104
+ <ref name="dir"/>
105
+ <ref name="emph"/>
106
+ <ref name="span"/>
107
+ </choice>
108
+ </zeroOrMore>
109
+ </interleave>
110
+ </element>
111
+ </define>
112
+ <define name="assert">
113
+ <element name="assert">
114
+ <attribute name="test">
115
+ <ref name="exprValue"/>
116
+ </attribute>
117
+ <optional>
118
+ <attribute name="flag">
119
+ <ref name="flagValue"/>
120
+ </attribute>
121
+ </optional>
122
+ <optional>
123
+ <attribute name="id">
124
+ <data type="ID"/>
125
+ </attribute>
126
+ </optional>
127
+ <optional>
128
+ <attribute name="diagnostics">
129
+ <data type="IDREFS"/>
130
+ </attribute>
131
+ </optional>
132
+ <optional>
133
+ <attribute name="properties">
134
+ <data type="IDREFS"/>
135
+ </attribute>
136
+ </optional>
137
+ <ref name="rich"/>
138
+ <ref name="linkable"/>
139
+ <interleave>
140
+ <ref name="foreign"/>
141
+ <zeroOrMore>
142
+ <choice>
143
+ <text/>
144
+ <ref name="name"/>
145
+ <ref name="value-of"/>
146
+ <ref name="emph"/>
147
+ <ref name="dir"/>
148
+ <ref name="span"/>
149
+ </choice>
150
+ </zeroOrMore>
151
+ </interleave>
152
+ </element>
153
+ </define>
154
+ <define name="diagnostic">
155
+ <element name="diagnostic">
156
+ <attribute name="id">
157
+ <data type="ID"/>
158
+ </attribute>
159
+ <ref name="rich"/>
160
+ <interleave>
161
+ <ref name="foreign"/>
162
+ <zeroOrMore>
163
+ <choice>
164
+ <text/>
165
+ <ref name="value-of"/>
166
+ <ref name="emph"/>
167
+ <ref name="dir"/>
168
+ <ref name="span"/>
169
+ </choice>
170
+ </zeroOrMore>
171
+ </interleave>
172
+ </element>
173
+ </define>
174
+ <define name="diagnostics">
175
+ <element name="diagnostics">
176
+ <interleave>
177
+ <ref name="foreign"/>
178
+ <zeroOrMore>
179
+ <ref name="inclusion"/>
180
+ </zeroOrMore>
181
+ <zeroOrMore>
182
+ <ref name="diagnostic"/>
183
+ </zeroOrMore>
184
+ </interleave>
185
+ </element>
186
+ </define>
187
+ <define name="dir">
188
+ <element name="dir">
189
+ <optional>
190
+ <attribute name="value">
191
+ <choice>
192
+ <value>ltr</value>
193
+ <value>rtl</value>
194
+ </choice>
195
+ </attribute>
196
+ </optional>
197
+ <interleave>
198
+ <ref name="foreign"/>
199
+ <text/>
200
+ </interleave>
201
+ </element>
202
+ </define>
203
+ <define name="emph">
204
+ <element name="emph">
205
+ <text/>
206
+ </element>
207
+ </define>
208
+ <define name="extends">
209
+ <element name="extends">
210
+ <choice>
211
+ <attribute name="rule">
212
+ <data type="IDREF"/>
213
+ </attribute>
214
+ <attribute name="href">
215
+ <ref name="uriValue"/>
216
+ </attribute>
217
+ </choice>
218
+ <ref name="foreign-empty"/>
219
+ </element>
220
+ </define>
221
+ <define name="let">
222
+ <element name="let">
223
+ <attribute name="name">
224
+ <ref name="nameValue"/>
225
+ </attribute>
226
+ <choice>
227
+ <attribute name="value">
228
+ <data type="string" datatypeLibrary=""/>
229
+ </attribute>
230
+ <oneOrMore>
231
+ <ref name="foreign-element"/>
232
+ </oneOrMore>
233
+ </choice>
234
+ </element>
235
+ </define>
236
+ <define name="name">
237
+ <element name="name">
238
+ <optional>
239
+ <attribute name="path">
240
+ <ref name="pathValue"/>
241
+ </attribute>
242
+ </optional>
243
+ <ref name="foreign-empty"/>
244
+ </element>
245
+ </define>
246
+ <define name="ns">
247
+ <element name="ns">
248
+ <attribute name="uri">
249
+ <ref name="uriValue"/>
250
+ </attribute>
251
+ <attribute name="prefix">
252
+ <ref name="nameValue"/>
253
+ </attribute>
254
+ <ref name="foreign-empty"/>
255
+ </element>
256
+ </define>
257
+ <define name="p">
258
+ <element name="p">
259
+ <optional>
260
+ <attribute name="id">
261
+ <data type="ID"/>
262
+ </attribute>
263
+ </optional>
264
+ <optional>
265
+ <attribute name="class">
266
+ <ref name="classValue"/>
267
+ </attribute>
268
+ </optional>
269
+ <optional>
270
+ <attribute name="icon">
271
+ <ref name="uriValue"/>
272
+ </attribute>
273
+ </optional>
274
+ <interleave>
275
+ <ref name="foreign"/>
276
+ <zeroOrMore>
277
+ <choice>
278
+ <text/>
279
+ <ref name="dir"/>
280
+ <ref name="emph"/>
281
+ <ref name="span"/>
282
+ </choice>
283
+ </zeroOrMore>
284
+ </interleave>
285
+ </element>
286
+ </define>
287
+ <define name="param">
288
+ <element name="param">
289
+ <attribute name="name">
290
+ <ref name="nameValue"/>
291
+ </attribute>
292
+ <attribute name="value">
293
+ <ref name="non-empty-string"/>
294
+ </attribute>
295
+ </element>
296
+ </define>
297
+ <define name="pattern">
298
+ <element name="pattern">
299
+ <optional>
300
+ <attribute name="documents">
301
+ <ref name="pathValue"/>
302
+ </attribute>
303
+ </optional>
304
+ <ref name="rich"/>
305
+ <interleave>
306
+ <ref name="foreign"/>
307
+ <zeroOrMore>
308
+ <ref name="inclusion"/>
309
+ </zeroOrMore>
310
+ <choice>
311
+ <group>
312
+ <attribute name="abstract">
313
+ <value>true</value>
314
+ </attribute>
315
+ <attribute name="id">
316
+ <data type="ID"/>
317
+ </attribute>
318
+ <optional>
319
+ <ref name="title"/>
320
+ </optional>
321
+ <group>
322
+ <zeroOrMore>
323
+ <ref name="p"/>
324
+ </zeroOrMore>
325
+ <zeroOrMore>
326
+ <ref name="let"/>
327
+ </zeroOrMore>
328
+ <zeroOrMore>
329
+ <ref name="rule"/>
330
+ </zeroOrMore>
331
+ </group>
332
+ </group>
333
+ <group>
334
+ <optional>
335
+ <attribute name="abstract">
336
+ <value>false</value>
337
+ </attribute>
338
+ </optional>
339
+ <optional>
340
+ <attribute name="id">
341
+ <data type="ID"/>
342
+ </attribute>
343
+ </optional>
344
+ <optional>
345
+ <ref name="title"/>
346
+ </optional>
347
+ <group>
348
+ <zeroOrMore>
349
+ <ref name="p"/>
350
+ </zeroOrMore>
351
+ <zeroOrMore>
352
+ <ref name="let"/>
353
+ </zeroOrMore>
354
+ <zeroOrMore>
355
+ <ref name="rule"/>
356
+ </zeroOrMore>
357
+ </group>
358
+ </group>
359
+ <group>
360
+ <optional>
361
+ <attribute name="abstract">
362
+ <value>false</value>
363
+ </attribute>
364
+ </optional>
365
+ <attribute name="is-a">
366
+ <data type="IDREF"/>
367
+ </attribute>
368
+ <optional>
369
+ <attribute name="id">
370
+ <data type="ID"/>
371
+ </attribute>
372
+ </optional>
373
+ <optional>
374
+ <ref name="title"/>
375
+ </optional>
376
+ <group>
377
+ <zeroOrMore>
378
+ <ref name="p"/>
379
+ </zeroOrMore>
380
+ <zeroOrMore>
381
+ <ref name="param"/>
382
+ </zeroOrMore>
383
+ </group>
384
+ </group>
385
+ </choice>
386
+ </interleave>
387
+ </element>
388
+ </define>
389
+ <define name="phase">
390
+ <element name="phase">
391
+ <attribute name="id">
392
+ <data type="ID"/>
393
+ </attribute>
394
+ <ref name="rich"/>
395
+ <interleave>
396
+ <ref name="foreign"/>
397
+ <zeroOrMore>
398
+ <ref name="inclusion"/>
399
+ </zeroOrMore>
400
+ <group>
401
+ <zeroOrMore>
402
+ <ref name="p"/>
403
+ </zeroOrMore>
404
+ <zeroOrMore>
405
+ <ref name="let"/>
406
+ </zeroOrMore>
407
+ <zeroOrMore>
408
+ <ref name="active"/>
409
+ </zeroOrMore>
410
+ </group>
411
+ </interleave>
412
+ </element>
413
+ </define>
414
+ <define name="properties">
415
+ <element name="properties">
416
+ <zeroOrMore>
417
+ <ref name="property"/>
418
+ </zeroOrMore>
419
+ </element>
420
+ </define>
421
+ <define name="property">
422
+ <element name="property">
423
+ <attribute name="id">
424
+ <data type="ID"/>
425
+ </attribute>
426
+ <optional>
427
+ <attribute name="role">
428
+ <ref name="roleValue"/>
429
+ </attribute>
430
+ </optional>
431
+ <optional>
432
+ <attribute name="scheme"/>
433
+ </optional>
434
+ <interleave>
435
+ <ref name="foreign"/>
436
+ <zeroOrMore>
437
+ <choice>
438
+ <text/>
439
+ <ref name="name"/>
440
+ <ref name="value-of"/>
441
+ <ref name="emph"/>
442
+ <ref name="dir"/>
443
+ <ref name="span"/>
444
+ </choice>
445
+ </zeroOrMore>
446
+ </interleave>
447
+ </element>
448
+ </define>
449
+ <define name="report">
450
+ <element name="report">
451
+ <attribute name="test">
452
+ <ref name="exprValue"/>
453
+ </attribute>
454
+ <optional>
455
+ <attribute name="flag">
456
+ <ref name="flagValue"/>
457
+ </attribute>
458
+ </optional>
459
+ <optional>
460
+ <attribute name="id">
461
+ <data type="ID"/>
462
+ </attribute>
463
+ </optional>
464
+ <optional>
465
+ <attribute name="diagnostics">
466
+ <data type="IDREFS"/>
467
+ </attribute>
468
+ </optional>
469
+ <optional>
470
+ <attribute name="properties">
471
+ <data type="IDREFS"/>
472
+ </attribute>
473
+ </optional>
474
+ <ref name="rich"/>
475
+ <ref name="linkable"/>
476
+ <interleave>
477
+ <ref name="foreign"/>
478
+ <zeroOrMore>
479
+ <choice>
480
+ <text/>
481
+ <ref name="name"/>
482
+ <ref name="value-of"/>
483
+ <ref name="emph"/>
484
+ <ref name="dir"/>
485
+ <ref name="span"/>
486
+ </choice>
487
+ </zeroOrMore>
488
+ </interleave>
489
+ </element>
490
+ </define>
491
+ <define name="rule">
492
+ <element name="rule">
493
+ <optional>
494
+ <attribute name="flag">
495
+ <ref name="flagValue"/>
496
+ </attribute>
497
+ </optional>
498
+ <ref name="rich"/>
499
+ <ref name="linkable"/>
500
+ <interleave>
501
+ <ref name="foreign"/>
502
+ <zeroOrMore>
503
+ <ref name="inclusion"/>
504
+ </zeroOrMore>
505
+ <choice>
506
+ <group>
507
+ <attribute name="abstract">
508
+ <value>true</value>
509
+ </attribute>
510
+ <attribute name="id">
511
+ <data type="ID"/>
512
+ </attribute>
513
+ <zeroOrMore>
514
+ <ref name="let"/>
515
+ </zeroOrMore>
516
+ <oneOrMore>
517
+ <choice>
518
+ <ref name="assert"/>
519
+ <ref name="report"/>
520
+ <ref name="extends"/>
521
+ <ref name="p"/>
522
+ </choice>
523
+ </oneOrMore>
524
+ </group>
525
+ <group>
526
+ <attribute name="context">
527
+ <ref name="pathValue"/>
528
+ </attribute>
529
+ <optional>
530
+ <attribute name="id">
531
+ <data type="ID"/>
532
+ </attribute>
533
+ </optional>
534
+ <optional>
535
+ <attribute name="abstract">
536
+ <value>false</value>
537
+ </attribute>
538
+ </optional>
539
+ <zeroOrMore>
540
+ <ref name="let"/>
541
+ </zeroOrMore>
542
+ <oneOrMore>
543
+ <choice>
544
+ <ref name="assert"/>
545
+ <ref name="report"/>
546
+ <ref name="extends"/>
547
+ <ref name="p"/>
548
+ </choice>
549
+ </oneOrMore>
550
+ </group>
551
+ </choice>
552
+ </interleave>
553
+ </element>
554
+ </define>
555
+ <define name="span">
556
+ <element name="span">
557
+ <attribute name="class">
558
+ <ref name="classValue"/>
559
+ </attribute>
560
+ <interleave>
561
+ <ref name="foreign"/>
562
+ <text/>
563
+ </interleave>
564
+ </element>
565
+ </define>
566
+ <define name="title">
567
+ <element name="title">
568
+ <zeroOrMore>
569
+ <choice>
570
+ <text/>
571
+ <ref name="dir"/>
572
+ </choice>
573
+ </zeroOrMore>
574
+ </element>
575
+ </define>
576
+ <define name="value-of">
577
+ <element name="value-of">
578
+ <attribute name="select">
579
+ <ref name="pathValue"/>
580
+ </attribute>
581
+ <ref name="foreign-empty"/>
582
+ </element>
583
+ </define>
584
+ <!-- common declarations -->
585
+ <define name="inclusion">
586
+ <element name="include">
587
+ <attribute name="href">
588
+ <ref name="uriValue"/>
589
+ </attribute>
590
+ <ref name="foreign-empty"/>
591
+ </element>
592
+ </define>
593
+ <define name="rich">
594
+ <optional>
595
+ <attribute name="icon">
596
+ <ref name="uriValue"/>
597
+ </attribute>
598
+ </optional>
599
+ <optional>
600
+ <attribute name="see">
601
+ <ref name="uriValue"/>
602
+ </attribute>
603
+ </optional>
604
+ <optional>
605
+ <attribute name="fpi">
606
+ <ref name="fpiValue"/>
607
+ </attribute>
608
+ </optional>
609
+ <optional>
610
+ <attribute name="xml:lang">
611
+ <ref name="langValue"/>
612
+ </attribute>
613
+ </optional>
614
+ <optional>
615
+ <attribute name="xml:space">
616
+ <choice>
617
+ <value>preserve</value>
618
+ <value>default</value>
619
+ </choice>
620
+ </attribute>
621
+ </optional>
622
+ </define>
623
+ <define name="linkable">
624
+ <optional>
625
+ <attribute name="role">
626
+ <ref name="roleValue"/>
627
+ </attribute>
628
+ </optional>
629
+ <optional>
630
+ <attribute name="subject">
631
+ <ref name="pathValue"/>
632
+ </attribute>
633
+ </optional>
634
+ </define>
635
+ <define name="foreign">
636
+ <ref name="foreign-attributes"/>
637
+ <zeroOrMore>
638
+ <ref name="foreign-element"/>
639
+ </zeroOrMore>
640
+ </define>
641
+ <define name="foreign-empty">
642
+ <ref name="foreign-attributes"/>
643
+ </define>
644
+ <define name="foreign-attributes">
645
+ <zeroOrMore>
646
+ <attribute>
647
+ <anyName>
648
+ <except>
649
+ <nsName ns=""/>
650
+ <nsName ns="http://www.w3.org/XML/1998/namespace"/>
651
+ </except>
652
+ </anyName>
653
+ </attribute>
654
+ </zeroOrMore>
655
+ </define>
656
+ <define name="foreign-element">
657
+ <element>
658
+ <anyName>
659
+ <except>
660
+ <nsName/>
661
+ </except>
662
+ </anyName>
663
+ <zeroOrMore>
664
+ <choice>
665
+ <attribute>
666
+ <anyName/>
667
+ </attribute>
668
+ <ref name="foreign-element"/>
669
+ <ref name="schema"/>
670
+ <text/>
671
+ </choice>
672
+ </zeroOrMore>
673
+ </element>
674
+ </define>
675
+ <!-- Data types -->
676
+ <define name="uriValue">
677
+ <data type="anyURI"/>
678
+ </define>
679
+ <define name="pathValue">
680
+ <data type="string" datatypeLibrary=""/>
681
+ </define>
682
+ <define name="exprValue">
683
+ <data type="string" datatypeLibrary=""/>
684
+ </define>
685
+ <define name="fpiValue">
686
+ <data type="string" datatypeLibrary=""/>
687
+ </define>
688
+ <define name="langValue">
689
+ <data type="language"/>
690
+ </define>
691
+ <define name="roleValue">
692
+ <data type="string" datatypeLibrary=""/>
693
+ </define>
694
+ <define name="flagValue">
695
+ <data type="string" datatypeLibrary=""/>
696
+ </define>
697
+ <define name="nameValue">
698
+ <data type="string" datatypeLibrary=""/>
699
+ </define>
700
+ <!-- In the default query language binding, xsd:NCNAME -->
701
+ <define name="classValue">
702
+ <data type="string" datatypeLibrary=""/>
703
+ </define>
704
+ <define name="non-empty-string">
705
+ <data type="token">
706
+ <param name="minLength">1</param>
707
+ </data>
708
+ </define>
709
+ </grammar>
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!--
3
+ Stylesheet for extracting Schematron information from a RELAX-NG schema.
4
+ Based on the stylesheet for extracting Schematron information from W3C XML Schema.
5
+ Created by Eddie Robertsson 2002/06/01
6
+ 2009/12/10 hj: changed Schematron namespace to ISO URI (Holger Joukl)
7
+ -->
8
+ <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
9
+ xmlns:sch="http://purl.oclc.org/dsdl/schematron" xmlns:rng="http://relaxng.org/ns/structure/1.0">
10
+ <!-- Set the output to be XML with an XML declaration and use indentation -->
11
+ <xsl:output method="xml" omit-xml-declaration="no" indent="yes" standalone="yes"/>
12
+ <!-- -->
13
+ <!-- match schema and call recursive template to extract included schemas -->
14
+ <!-- -->
15
+ <xsl:template match="/rng:grammar | /rng:element">
16
+ <!-- call the schema definition template ... -->
17
+ <xsl:call-template name="gatherSchema">
18
+ <!-- ... with current node as the $schemas parameter ... -->
19
+ <xsl:with-param name="schemas" select="."/>
20
+ <!-- ... and any includes in the $include parameter -->
21
+ <xsl:with-param name="includes" select="document(/rng:grammar/rng:include/@href
22
+ | //rng:externalRef/@href)"/>
23
+ </xsl:call-template>
24
+ </xsl:template>
25
+ <!-- -->
26
+ <!-- gather all included schemas into a single parameter variable -->
27
+ <!-- -->
28
+ <xsl:template name="gatherSchema">
29
+ <xsl:param name="schemas"/>
30
+ <xsl:param name="includes"/>
31
+ <xsl:choose>
32
+ <xsl:when test="count($schemas) &lt; count($schemas | $includes)">
33
+ <!-- when $includes includes something new, recurse ... -->
34
+ <xsl:call-template name="gatherSchema">
35
+ <!-- ... with current $includes added to the $schemas parameter ... -->
36
+ <xsl:with-param name="schemas" select="$schemas | $includes"/>
37
+ <!-- ... and any *new* includes in the $include parameter -->
38
+ <xsl:with-param name="includes" select="document($includes/rng:grammar/rng:include/@href
39
+ | $includes//rng:externalRef/@href)"/>
40
+ </xsl:call-template>
41
+ </xsl:when>
42
+ <xsl:otherwise>
43
+ <!-- we have the complete set of included schemas, so now let's output the embedded schematron -->
44
+ <xsl:call-template name="output">
45
+ <xsl:with-param name="schemas" select="$schemas"/>
46
+ </xsl:call-template>
47
+ </xsl:otherwise>
48
+ </xsl:choose>
49
+ </xsl:template>
50
+ <!-- -->
51
+ <!-- output the schematron information -->
52
+ <!-- -->
53
+ <xsl:template name="output">
54
+ <xsl:param name="schemas"/>
55
+ <!-- -->
56
+ <sch:schema>
57
+ <!-- get header-type elements - eg title and especially ns -->
58
+ <!-- title (just one) -->
59
+ <xsl:copy-of select="$schemas//sch:title[1]"/>
60
+ <!-- get remaining schematron schema children -->
61
+ <!-- get non-blank namespace elements, dropping duplicates -->
62
+ <xsl:for-each select="$schemas//sch:ns">
63
+ <xsl:if test="generate-id(.) = generate-id($schemas//sch:ns[@prefix = current()/@prefix][1])">
64
+ <xsl:copy-of select="."/>
65
+ </xsl:if>
66
+ </xsl:for-each>
67
+ <xsl:copy-of select="$schemas//sch:phase"/>
68
+ <xsl:copy-of select="$schemas//sch:pattern"/>
69
+ <sch:diagnostics>
70
+ <xsl:copy-of select="$schemas//sch:diagnostics/*"/>
71
+ </sch:diagnostics>
72
+ </sch:schema>
73
+ </xsl:template>
74
+ <!-- -->
75
+ </xsl:transform>
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!--
3
+ based on an original transform by Eddie Robertsson
4
+ 2001/04/21 fn: added support for included schemas
5
+ 2001/06/27 er: changed XMl Schema prefix from xsd: to xs: and changed to the Rec namespace
6
+ 2009/12/10 hj: changed Schematron namespace to ISO URI (Holger Joukl)
7
+ -->
8
+ <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
9
+ xmlns:sch="http://purl.oclc.org/dsdl/schematron" xmlns:xs="http://www.w3.org/2001/XMLSchema">
10
+ <!-- Set the output to be XML with an XML declaration and use indentation -->
11
+ <xsl:output method="xml" omit-xml-declaration="no" indent="yes" standalone="yes"/>
12
+ <!-- -->
13
+ <!-- match schema and call recursive template to extract included schemas -->
14
+ <!-- -->
15
+ <xsl:template match="xs:schema">
16
+ <!-- call the schema definition template ... -->
17
+ <xsl:call-template name="gatherSchema">
18
+ <!-- ... with current current root as the $schemas parameter ... -->
19
+ <xsl:with-param name="schemas" select="/"/>
20
+ <!-- ... and any includes in the $include parameter -->
21
+ <xsl:with-param name="includes"
22
+ select="document(/xs:schema/xs:*[self::xs:include or self::xs:import or self::xs:redefine]/@schemaLocation)"/>
23
+ </xsl:call-template>
24
+ </xsl:template>
25
+ <!-- -->
26
+ <!-- gather all included schemas into a single parameter variable -->
27
+ <!-- -->
28
+ <xsl:template name="gatherSchema">
29
+ <xsl:param name="schemas"/>
30
+ <xsl:param name="includes"/>
31
+ <xsl:choose>
32
+ <xsl:when test="count($schemas) &lt; count($schemas | $includes)">
33
+ <!-- when $includes includes something new, recurse ... -->
34
+ <xsl:call-template name="gatherSchema">
35
+ <!-- ... with current $includes added to the $schemas parameter ... -->
36
+ <xsl:with-param name="schemas" select="$schemas | $includes"/>
37
+ <!-- ... and any *new* includes in the $include parameter -->
38
+ <xsl:with-param name="includes"
39
+ select="document($includes/xs:schema/xs:*[self::xs:include or self::xs:import or self::xs:redefine]/@schemaLocation)"/>
40
+ </xsl:call-template>
41
+ </xsl:when>
42
+ <xsl:otherwise>
43
+ <!-- we have the complete set of included schemas,
44
+ so now let's output the embedded schematron -->
45
+ <xsl:call-template name="output">
46
+ <xsl:with-param name="schemas" select="$schemas"/>
47
+ </xsl:call-template>
48
+ </xsl:otherwise>
49
+ </xsl:choose>
50
+ </xsl:template>
51
+ <!-- -->
52
+ <!-- output the schematron information -->
53
+ <!-- -->
54
+ <xsl:template name="output">
55
+ <xsl:param name="schemas"/>
56
+ <!-- -->
57
+ <sch:schema>
58
+ <!-- get header-type elements - eg title and especially ns -->
59
+ <!-- title (just one) -->
60
+ <xsl:copy-of select="$schemas//xs:appinfo/sch:title[1]"/>
61
+ <!-- get remaining schematron schema children -->
62
+ <!-- get non-blank namespace elements, dropping duplicates -->
63
+ <xsl:for-each select="$schemas//xs:appinfo/sch:ns">
64
+ <xsl:if test="generate-id(.) =
65
+ generate-id($schemas//xs:appinfo/sch:ns[@prefix = current()/@prefix][1])">
66
+ <xsl:copy-of select="."/>
67
+ </xsl:if>
68
+ </xsl:for-each>
69
+ <xsl:copy-of select="$schemas//xs:appinfo/sch:phase"/>
70
+ <xsl:copy-of select="$schemas//xs:appinfo/sch:pattern"/>
71
+ <sch:diagnostics>
72
+ <xsl:copy-of select="$schemas//xs:appinfo/sch:diagnostics/*"/>
73
+ </sch:diagnostics>
74
+ </sch:schema>
75
+ </xsl:template>
76
+ <!-- -->
77
+ </xsl:transform>
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?><?xar XSLT?>
2
+
3
+ <!--
4
+ OVERVIEW - iso_abstract_expand.xsl
5
+
6
+ This is a preprocessor for ISO Schematron, which implements abstract patterns.
7
+ It also
8
+ * extracts a particular schema using an ID, where there are multiple
9
+ schemas, such as when they are embedded in the same NVDL script
10
+ * allows parameter substitution inside @context, @test, @select, @path
11
+ * experimentally, allows parameter recognition and substitution inside
12
+ text (NOTE: to be removed, for compataibility with other implementations,
13
+ please do not use this)
14
+
15
+ This should be used after iso-dsdl-include.xsl and before the skeleton or
16
+ meta-stylesheet (e.g. iso-svrl.xsl) . It only requires XSLT 1.
17
+
18
+ Each kind of inclusion can be turned off (or on) on the command line.
19
+
20
+ -->
21
+
22
+ <!--
23
+ Open Source Initiative OSI - The MIT License:Licensing
24
+ [OSI Approved License]
25
+
26
+ This source code was previously available under the zlib/libpng license.
27
+ Attribution is polite.
28
+
29
+ The MIT License
30
+
31
+ Copyright (c) 2004-2010 Rick Jellife and Academia Sinica Computing Centre, Taiwan
32
+
33
+ Permission is hereby granted, free of charge, to any person obtaining a copy
34
+ of this software and associated documentation files (the "Software"), to deal
35
+ in the Software without restriction, including without limitation the rights
36
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
37
+ copies of the Software, and to permit persons to whom the Software is
38
+ furnished to do so, subject to the following conditions:
39
+
40
+ The above copyright notice and this permission notice shall be included in
41
+ all copies or substantial portions of the Software.
42
+
43
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
44
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
45
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
46
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
47
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
48
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
49
+ THE SOFTWARE.
50
+ -->
51
+
52
+ <!--
53
+ VERSION INFORMATION
54
+ 2013-09-19 RJ
55
+ * Allow macro expansion in @path attributes, eg. for sch:name/@path
56
+
57
+ 2010-07-10 RJ
58
+ * Move to MIT license
59
+
60
+ 2008-09-18 RJ
61
+ * move out param test from iso:schema template to work with XSLT 1. (Noah Fontes)
62
+
63
+ 2008-07-29 RJ
64
+ * Create. Pull out as distinct XSL in its own namespace from old iso_pre_pro.xsl
65
+ * Put everything in private namespace
66
+ * Rewrite replace_substring named template so that copyright is clear
67
+
68
+ 2008-07-24 RJ
69
+ * correct abstract patterns so for correct names: param/@name and
70
+ param/@value
71
+
72
+ 2007-01-12 RJ
73
+ * Use ISO namespace
74
+ * Use pattern/@id not pattern/@name
75
+ * Add Oliver Becker's suggests from old Schematron-love-in list for <copy>
76
+ * Add XT -ism?
77
+ 2003 RJ
78
+ * Original written for old namespace
79
+ * http://www.topologi.com/resources/iso-pre-pro.xsl
80
+ -->
81
+ <xslt:stylesheet version="1.0" xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
82
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
83
+ xmlns:iso="http://purl.oclc.org/dsdl/schematron"
84
+ xmlns:nvdl="http://purl.oclc.org/dsdl/nvdl"
85
+
86
+ xmlns:iae="http://www.schematron.com/namespace/iae"
87
+
88
+ >
89
+
90
+ <xslt:param name="schema-id"></xslt:param>
91
+
92
+
93
+ <!-- Driver for the mode -->
94
+ <xsl:template match="/">
95
+ <xsl:apply-templates select="." mode="iae:go" />
96
+ </xsl:template>
97
+
98
+
99
+ <!-- ================================================================================== -->
100
+ <!-- Normal processing rules -->
101
+ <!-- ================================================================================== -->
102
+ <!-- Output only the selected schema -->
103
+ <xslt:template match="iso:schema" >
104
+ <xsl:if test="string-length($schema-id) =0 or @id= $schema-id ">
105
+ <xslt:copy>
106
+ <xslt:copy-of select="@*" />
107
+ <xslt:apply-templates mode="iae:go" />
108
+ </xslt:copy>
109
+ </xsl:if>
110
+ </xslt:template>
111
+
112
+
113
+ <!-- Strip out any foreign elements above the Schematron schema .
114
+ -->
115
+ <xslt:template match="*[not(ancestor-or-self::iso:*)]" mode="iae:go" >
116
+ <xslt:apply-templates mode="iae:go" />
117
+ </xslt:template>
118
+
119
+
120
+ <!-- ================================================================================== -->
121
+ <!-- Handle Schematron abstract pattern preprocessing -->
122
+ <!-- abstract-to-real calls
123
+ do-pattern calls
124
+ macro-expand calls
125
+ multi-macro-expand
126
+ replace-substring -->
127
+ <!-- ================================================================================== -->
128
+
129
+ <!--
130
+ Abstract patterns allow you to say, for example
131
+
132
+ <pattern name="htmlTable" is-a="table">
133
+ <param name="row" value="html:tr"/>
134
+ <param name="cell" value="html:td" />
135
+ <param name="table" value="html:table" />
136
+ </pattern>
137
+
138
+ For a good introduction, see Uche Ogbujii's article for IBM DeveloperWorks
139
+ "Discover the flexibility of Schematron abstract patterns"
140
+ http://www-128.ibm.com/developerworks/xml/library/x-stron.html
141
+ However, note that ISO Schematron uses @name and @value attributes on
142
+ the iso:param element, and @id not @name on the pattern element.
143
+
144
+ -->
145
+
146
+ <!-- Suppress declarations of abstract patterns -->
147
+ <xslt:template match="iso:pattern[@abstract='true']" mode="iae:go" >
148
+ <xslt:comment>Suppressed abstract pattern <xslt:value-of select="@id"/> was here</xslt:comment>
149
+ </xslt:template>
150
+
151
+
152
+ <!-- Suppress uses of abstract patterns -->
153
+ <xslt:template match="iso:pattern[@is-a]" mode="iae:go" >
154
+
155
+ <xslt:comment>Start pattern based on abstract <xslt:value-of select="@is-a"/></xslt:comment>
156
+
157
+ <xslt:call-template name="iae:abstract-to-real" >
158
+ <xslt:with-param name="caller" select="@id" />
159
+ <xslt:with-param name="is-a" select="@is-a" />
160
+ </xslt:call-template>
161
+
162
+ </xslt:template>
163
+
164
+
165
+
166
+ <!-- output everything else unchanged -->
167
+ <xslt:template match="*" priority="-1" mode="iae:go" >
168
+ <xslt:copy>
169
+ <xslt:copy-of select="@*" />
170
+ <xslt:apply-templates mode="iae:go"/>
171
+ </xslt:copy>
172
+ </xslt:template>
173
+
174
+ <!-- Templates for macro expansion of abstract patterns -->
175
+ <!-- Sets up the initial conditions for the recursive call -->
176
+ <xslt:template name="iae:macro-expand">
177
+ <xslt:param name="caller"/>
178
+ <xslt:param name="text" />
179
+ <xslt:call-template name="iae:multi-macro-expand">
180
+ <xslt:with-param name="caller" select="$caller"/>
181
+ <xslt:with-param name="text" select="$text"/>
182
+ <xslt:with-param name="paramNumber" select="1"/>
183
+ </xslt:call-template>
184
+
185
+ </xslt:template>
186
+
187
+ <!-- Template to replace the current parameter and then
188
+ recurse to replace subsequent parameters. -->
189
+
190
+ <xslt:template name="iae:multi-macro-expand">
191
+ <xslt:param name="caller"/>
192
+ <xslt:param name="text" />
193
+ <xslt:param name="paramNumber" />
194
+
195
+
196
+ <xslt:choose>
197
+ <xslt:when test="//iso:pattern[@id=$caller]/iso:param[ $paramNumber]">
198
+
199
+ <xslt:call-template name="iae:multi-macro-expand">
200
+ <xslt:with-param name="caller" select="$caller"/>
201
+ <xslt:with-param name="paramNumber" select="$paramNumber + 1"/>
202
+ <xslt:with-param name="text" >
203
+ <xslt:call-template name="iae:replace-substring">
204
+ <xslt:with-param name="original" select="$text"/>
205
+ <xslt:with-param name="substring"
206
+ select="concat('$', //iso:pattern[@id=$caller]/iso:param[ $paramNumber ]/@name)"/>
207
+ <xslt:with-param name="replacement"
208
+ select="//iso:pattern[@id=$caller]/iso:param[ $paramNumber ]/@value"/>
209
+ </xslt:call-template>
210
+ </xslt:with-param>
211
+ </xslt:call-template>
212
+ </xslt:when>
213
+ <xslt:otherwise><xslt:value-of select="$text" /></xslt:otherwise>
214
+
215
+ </xslt:choose>
216
+ </xslt:template>
217
+
218
+
219
+ <!-- generate the real pattern from an abstract pattern + parameters-->
220
+ <xslt:template name="iae:abstract-to-real" >
221
+ <xslt:param name="caller"/>
222
+ <xslt:param name="is-a" />
223
+ <xslt:for-each select="//iso:pattern[@id= $is-a]">
224
+ <xslt:copy>
225
+
226
+ <xslt:choose>
227
+ <xslt:when test=" string-length( $caller ) = 0">
228
+ <xslt:attribute name="id"><xslt:value-of select="concat( generate-id(.) , $is-a)" /></xslt:attribute>
229
+ </xslt:when>
230
+ <xslt:otherwise>
231
+ <xslt:attribute name="id"><xslt:value-of select="$caller" /></xslt:attribute>
232
+ </xslt:otherwise>
233
+ </xslt:choose>
234
+
235
+ <xslt:apply-templates select="*|text()" mode="iae:do-pattern" >
236
+ <xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
237
+ </xslt:apply-templates>
238
+
239
+ </xslt:copy>
240
+ </xslt:for-each>
241
+ </xslt:template>
242
+
243
+
244
+ <!-- Generate a non-abstract pattern -->
245
+ <xslt:template mode="iae:do-pattern" match="*">
246
+ <xslt:param name="caller"/>
247
+ <xslt:copy>
248
+ <xslt:for-each select="@*[name()='test' or name()='context' or name()='select' or name()='path' ]">
249
+ <xslt:attribute name="{name()}">
250
+ <xslt:call-template name="iae:macro-expand">
251
+ <xslt:with-param name="text"><xslt:value-of select="."/></xslt:with-param>
252
+ <xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
253
+ </xslt:call-template>
254
+ </xslt:attribute>
255
+ </xslt:for-each>
256
+ <xslt:copy-of select="@*[name()!='test'][name()!='context'][name()!='select'][name()!='path']" />
257
+ <xsl:for-each select="node()">
258
+ <xsl:choose>
259
+ <!-- Experiment: replace macros in text as well, to allow parameterized assertions
260
+ and so on, without having to have spurious <iso:value-of> calls and multiple
261
+ delimiting.
262
+ NOTE: THIS FUNCTIONALITY WILL BE REMOVED IN THE FUTURE -->
263
+ <xsl:when test="self::text()">
264
+ <xslt:call-template name="iae:macro-expand">
265
+ <xslt:with-param name="text"><xslt:value-of select="."/></xslt:with-param>
266
+ <xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
267
+ </xslt:call-template>
268
+ </xsl:when>
269
+ <xsl:otherwise>
270
+ <xslt:apply-templates select="." mode="iae:do-pattern">
271
+ <xslt:with-param name="caller"><xslt:value-of select="$caller"/></xslt:with-param>
272
+ </xslt:apply-templates>
273
+ </xsl:otherwise>
274
+ </xsl:choose>
275
+ </xsl:for-each>
276
+ </xslt:copy>
277
+ </xslt:template>
278
+
279
+ <!-- UTILITIES -->
280
+ <!-- Simple version of replace-substring function -->
281
+ <xslt:template name="iae:replace-substring">
282
+ <xslt:param name="original" />
283
+ <xslt:param name="substring" />
284
+ <xslt:param name="replacement" select="''"/>
285
+
286
+ <xsl:choose>
287
+ <xsl:when test="not($original)" />
288
+ <xsl:when test="not(string($substring))">
289
+ <xsl:value-of select="$original" />
290
+ </xsl:when>
291
+ <xsl:when test="contains($original, $substring)">
292
+ <xsl:variable name="before" select="substring-before($original, $substring)" />
293
+ <xsl:variable name="after" select="substring-after($original, $substring)" />
294
+
295
+ <xsl:value-of select="$before" />
296
+ <xsl:value-of select="$replacement" />
297
+ <!-- recursion -->
298
+ <xsl:call-template name="iae:replace-substring">
299
+ <xsl:with-param name="original" select="$after" />
300
+ <xsl:with-param name="substring" select="$substring" />
301
+ <xsl:with-param name="replacement" select="$replacement" />
302
+ </xsl:call-template>
303
+ </xsl:when>
304
+ <xsl:otherwise>
305
+ <!-- no substitution -->
306
+ <xsl:value-of select="$original" />
307
+ </xsl:otherwise>
308
+ </xsl:choose>
309
+ </xslt:template>
310
+
311
+
312
+
313
+ </xslt:stylesheet>
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl ADDED
@@ -0,0 +1,1160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?><?xar XSLT?>
2
+
3
+ <!--
4
+ OVERVIEW : iso_dsdl_include.xsl
5
+
6
+ This is an inclusion preprocessor for the non-smart text inclusions
7
+ of ISO DSDL. It handles
8
+ <relax:extRef> for ISO RELAX NG
9
+ <sch:include> for ISO Schematron and Schematron 1.n
10
+ <sch:extends> for 2009 draft ISO Schematron
11
+ <xi:xinclude> simple W3C XIncludes for ISO NVRL and DSRL
12
+ <crdl:ref> for draft ISO CRDL
13
+ <dtll:include> for draft ISO DTLL
14
+ <* @xlink:href> for simple W3C XLink 1.1 embedded links
15
+
16
+
17
+ This should be the first in any chain of processing. It only requires
18
+ XSLT 1. Each kind of inclusion can be turned off (or on) on the command line.
19
+
20
+ Ids in fragment identifiers or xpointers will be sought in the following
21
+ order:
22
+ * @xml:id
23
+ * id() for typed schemas (e.g. from DTD) [NOTE: XInclude does not support this]
24
+ * untyped @id
25
+
26
+ The proposed behaviour for the update to ISO Schematron has been implemented. If an
27
+ include points to an element with the same name as the parent, then that element's
28
+ contents will be included. This supports the merge style of inclusion.
29
+
30
+ When an inclusion is made, it is preceded by a PI with target DSDL_INCLUDE_START
31
+ and the href and closed by a PI with target DSDL_INCLUDE_START and the href. This is
32
+ to allow better location of problems, though only to the file level.
33
+
34
+ Limitations:
35
+ * No rebasing: relative paths will be interpreted based on the initial document's
36
+ path, not the including document. (Severe limitation!)
37
+ * No checking for circular references
38
+ * Not full xpointers: only ID matching
39
+ * <relax:include> not implemented
40
+ * XInclude handling of xml:base and xml:lang not implemented
41
+ -->
42
+ <!--
43
+ VERSION INFORMATION
44
+ 2009-02-25
45
+ * Update DSDL namespace to use schematron.com
46
+ * Tested with SAXON9, Xalan 2.7.1, IE7,
47
+ * IE does not like multiple variables in same template with same name: rename.
48
+ 2008-09-18
49
+ * Remove new behaviour for include, because it conflicts with existing usage [KH]
50
+ * Add extends[@href] element with that merge functionality
51
+ * Generate PIs to notate source of inclusions for potential better diagnostics
52
+
53
+ 2008-09-16
54
+ * Fix for XSLT1
55
+
56
+ 2008-08-28
57
+ * New behaviour for schematron includes: if the pointed to element is the same as the current,
58
+ include the children.
59
+
60
+ 2008-08-20
61
+ * Fix bug: in XSLT1 cannot do $document/id('x') but need to use for-each
62
+
63
+ 2008-08-04
64
+ * Add support for inclusions in old namespace
65
+
66
+ 2008-08-03
67
+ * Fix wrong param name include-relaxng & include-crdl (KH, PH)
68
+ * Allow inclusion of XSLT and XHTML (KH)
69
+ * Fix inclusion of fragments (KH)
70
+
71
+ 2008-07-25
72
+ * Add selectable input parameter
73
+
74
+ 2008-07-24
75
+ * RJ New
76
+ -->
77
+ <!--
78
+ LEGAL INFORMATION
79
+
80
+ Copyright (c) 2008 Rick Jelliffe
81
+
82
+ This software is provided 'as-is', without any express or implied warranty.
83
+ In no event will the authors be held liable for any damages arising from
84
+ the use of this software.
85
+
86
+ Permission is granted to anyone to use this software for any purpose,
87
+ including commercial applications, and to alter it and redistribute it freely,
88
+ subject to the following restrictions:
89
+
90
+ 1. The origin of this software must not be misrepresented; you must not claim
91
+ that you wrote the original software. If you use this software in a product,
92
+ an acknowledgment in the product documentation would be appreciated but is
93
+ not required.
94
+
95
+ 2. Altered source versions must be plainly marked as such, and must not be
96
+ misrepresented as being the original software.
97
+
98
+ 3. This notice may not be removed or altered from any source distribution.
99
+ -->
100
+ <xslt:stylesheet version="1.0"
101
+ xmlns:xslt="http://www.w3.org/1999/XSL/Transform"
102
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
103
+ xmlns:iso="http://purl.oclc.org/dsdl/schematron"
104
+ xmlns:nvdl="http://purl.oclc.org/dsdl/nvdl"
105
+ xmlns:xhtml="http://www.w3.org/1999/xhtml"
106
+ xmlns:schold="http://www.ascc.net/xml/schematron"
107
+ xmlns:crdl="http://purl.oclc.org/dsdl/crepdl/ns/structure/1.0"
108
+ xmlns:xi="http://www.w3.org/2001/XInclude"
109
+ xmlns:dtll="http://www.jenitennison.com/datatypes"
110
+ xmlns:dsdl="http://www.schematron.com/namespace/dsdl"
111
+ xmlns:relax="http://relaxng.org/ns/structure/1.0"
112
+ xmlns:xlink="http://www.w3.org/1999/xlink">
113
+ <!-- Note: The URL for the dsdl namespace is not official -->
114
+
115
+
116
+ <xsl:param name="include-schematron">true</xsl:param>
117
+ <xsl:param name="include-crdl">true</xsl:param>
118
+ <xsl:param name="include-xinclude">true</xsl:param>
119
+ <xsl:param name="include-dtll">true</xsl:param>
120
+ <xsl:param name="include-relaxng">true</xsl:param>
121
+ <xsl:param name="include-xlink">true</xsl:param>
122
+
123
+ <xsl:template match="/">
124
+ <xsl:apply-templates select="." mode="dsdl:go" />
125
+ </xsl:template>
126
+
127
+ <!-- output everything else unchanged -->
128
+ <xslt:template match="node()" priority="-1" mode="dsdl:go">
129
+ <xslt:copy>
130
+ <xslt:copy-of select="@*" />
131
+ <xslt:apply-templates mode="dsdl:go" />
132
+ </xslt:copy>
133
+ </xslt:template>
134
+
135
+
136
+
137
+ <!-- =========================================================== -->
138
+ <!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
139
+ <!-- Part 2 - Regular grammar-based validation - RELAX NG -->
140
+ <!-- This only implements relax:extRef not relax:include which -->
141
+ <!-- is complex. -->
142
+ <!-- =========================================================== -->
143
+ <xslt:template match="relax:extRef" mode="dsdl:go">
144
+
145
+
146
+ <!-- Insert subschema -->
147
+
148
+ <xsl:variable name="document-uri"
149
+ select="substring-before(concat(@href,'#'), '#')" />
150
+ <xsl:variable name="fragment-id"
151
+ select="substring-after(@href, '#')" />
152
+
153
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
154
+ <xsl:value-of select="@href" />
155
+ </xsl:processing-instruction>
156
+ <xsl:choose>
157
+ <xsl:when test="not( $include-relaxng = 'true' )">
158
+ <xslt:copy>
159
+ <xslt:copy-of select="@*" />
160
+ <xslt:apply-templates mode="dsdl:go" />
161
+ </xslt:copy>
162
+ </xsl:when>
163
+ <xsl:otherwise>
164
+
165
+ <xsl:choose>
166
+
167
+ <xsl:when
168
+ test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
169
+ <xsl:message>
170
+ Error: Impossible URL in RELAX NG extRef
171
+ include
172
+ </xsl:message>
173
+ </xsl:when>
174
+
175
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
176
+ <xslt:when
177
+ test="string-length( $document-uri ) = 0">
178
+ <xslt:apply-templates mode="dsdl:go"
179
+ select="//*[@xml:id= $fragment-id ] | id( $fragment-id) | //*[@id= $fragment-id ]" />
180
+ </xslt:when>
181
+
182
+ <xsl:when
183
+ test="string-length( $fragment-id ) &gt; 0">
184
+ <xsl:variable name="theDocument_1"
185
+ select="document( $document-uri,/ )" />
186
+
187
+ <xsl:if test="not($theDocument_1)">
188
+ <xsl:message terminate="no">
189
+ <xsl:text>Unable to open referenced included file: </xsl:text>
190
+ <xsl:value-of select="@href" />
191
+ </xsl:message>
192
+ </xsl:if>
193
+ <!-- use a for-each so that the id() function works correctly on the external document -->
194
+ <xsl:for-each select="$theDocument_1">
195
+ <xsl:variable name="theFragment_1"
196
+ select="$theDocument_1//*[@xml:id= $fragment-id ]
197
+ | id( $fragment-id)
198
+ | $theDocument_1//*[@id= $fragment-id ]" />
199
+ <xsl:if test="not($theFragment_1)">
200
+ <xsl:message terminate="no">
201
+ <xsl:text>Unable to locate id attribute: </xsl:text>
202
+ <xsl:value-of select="@href" />
203
+ </xsl:message>
204
+ </xsl:if>
205
+ <xsl:apply-templates
206
+ select=" $theFragment_1[1]" mode="dsdl:go" />
207
+ </xsl:for-each>
208
+ </xsl:when>
209
+
210
+ <xsl:otherwise>
211
+ <xsl:variable name="theDocument_2"
212
+ select="document( $document-uri,/ )" />
213
+ <xsl:variable name="theFragment_2"
214
+ select="$theDocument_2/*" />
215
+ <xsl:if test="not($theDocument_2)">
216
+ <xsl:message terminate="no">
217
+ <xsl:text>Unable to open referenced included file: </xsl:text>
218
+ <xsl:value-of select="@href" />
219
+ </xsl:message>
220
+ </xsl:if>
221
+
222
+ <xsl:if test="not($theFragment_2)">
223
+ <xsl:message terminate="no">
224
+ <xsl:text>Unable to locate id attribute: </xsl:text>
225
+ <xsl:value-of select="@href" />
226
+ </xsl:message>
227
+ </xsl:if>
228
+ <xsl:apply-templates select="$theFragment_2 "
229
+ mode="dsdl:go" />
230
+ </xsl:otherwise>
231
+ </xsl:choose>
232
+
233
+ </xsl:otherwise>
234
+ </xsl:choose>
235
+
236
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
237
+ <xsl:value-of select="@href" />
238
+ </xsl:processing-instruction>
239
+ </xslt:template>
240
+
241
+
242
+
243
+ <!-- =========================================================== -->
244
+ <!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
245
+ <!-- Part 3 - Rule-based validation - Schematron -->
246
+ <!-- =========================================================== -->
247
+
248
+
249
+ <!-- Extend the URI syntax to allow # references -->
250
+ <!-- Add experimental support for simple containers like /xxx:xxx/iso:pattern to allow better includes -->
251
+ <xsl:template match="iso:include" mode="dsdl:go">
252
+
253
+ <xsl:variable name="document-uri"
254
+ select="substring-before(concat(@href,'#'), '#')" />
255
+ <xsl:variable name="fragment-id"
256
+ select="substring-after(@href, '#')" />
257
+
258
+
259
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
260
+ <xsl:value-of select="@href" />
261
+ </xsl:processing-instruction>
262
+
263
+ <xsl:choose>
264
+ <xsl:when test="not( $include-schematron = 'true' )">
265
+ <xslt:copy>
266
+ <xslt:copy-of select="@*" />
267
+ <xslt:apply-templates mode="dsdl:go" />
268
+ </xslt:copy>
269
+ </xsl:when>
270
+ <xsl:otherwise>
271
+
272
+ <xsl:choose>
273
+
274
+ <xsl:when
275
+ test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
276
+ <xsl:message>
277
+ Error: Impossible URL in Schematron include
278
+ </xsl:message>
279
+ </xsl:when>
280
+
281
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
282
+ <xslt:when
283
+ test="string-length( $document-uri ) = 0">
284
+ <xslt:apply-templates mode="dsdl:go"
285
+ select="//iso:*[@xml:id= $fragment-id ]
286
+ |id( $fragment-id)
287
+ | //iso:*[@id= $fragment-id ]" />
288
+ </xslt:when>
289
+
290
+ <!-- case where there is a fragment in another document (should be an iso: element) -->
291
+ <!-- There are three cases for includes with fragment:
292
+ 0) No href file or no matching id - error!
293
+ 1) REMOVED
294
+
295
+ 2) The linked-to element is sch:schema however the parent of the include
296
+ is not a schema. In this case, it is an error. (Actually, it should
297
+ be an error for other kinds of containment problems, but we won't
298
+ check for them in this version.)
299
+
300
+ 3) Otherwise, include the pointed-to element
301
+ -->
302
+
303
+ <xsl:when
304
+ test="string-length( $fragment-id ) &gt; 0">
305
+ <xsl:variable name="theDocument_1"
306
+ select="document( $document-uri,/ )" />
307
+ <xsl:variable name="originalParent" select=".." />
308
+
309
+ <!-- case 0 -->
310
+ <xsl:if test="not($theDocument_1)">
311
+ <xsl:message terminate="no">
312
+ <xsl:text>Unable to open referenced included file: </xsl:text>
313
+ <xsl:value-of select="@href" />
314
+ </xsl:message>
315
+ </xsl:if>
316
+ <!-- use for-each to rebase id() to external document -->
317
+ <xsl:for-each select="$theDocument_1">
318
+ <xsl:variable name="theFragment_1"
319
+ select=" $theDocument_1//iso:*[@xml:id= $fragment-id ] |
320
+ id($fragment-id) |
321
+ $theDocument_1//iso:*[@id= $fragment-id ]" />
322
+
323
+
324
+ <xsl:choose>
325
+ <!-- case 0 -->
326
+ <xsl:when test="not($theFragment_1)">
327
+ <xsl:message terminate="no">
328
+ <xsl:text>Unable to locate id attribute: </xsl:text>
329
+ <xsl:value-of select="@href" />
330
+ </xsl:message>
331
+ </xsl:when>
332
+
333
+
334
+ <!-- case 1 REMOVED -->
335
+
336
+ <!-- case 2 -->
337
+ <xsl:when
338
+ test=" $theFragment_1/self::iso:schema ">
339
+ <xsl:message>
340
+ Schema error: Use include to
341
+ include fragments, not a whole
342
+ schema
343
+ </xsl:message>
344
+ </xsl:when>
345
+
346
+ <!-- case 3 -->
347
+ <xsl:otherwise>
348
+ <xsl:apply-templates
349
+ select=" $theFragment_1[1]" mode="dsdl:go" />
350
+ </xsl:otherwise>
351
+ </xsl:choose>
352
+ </xsl:for-each>
353
+ </xsl:when>
354
+
355
+ <!-- Case where there is no ID so we include the whole document -->
356
+ <!-- Experimental addition: include fragments of children -->
357
+ <xsl:otherwise>
358
+ <xsl:variable name="theDocument_2"
359
+ select="document( $document-uri,/ )" />
360
+ <xsl:variable name="theFragment_2"
361
+ select="$theDocument_2/iso:*" />
362
+ <xsl:variable name="theContainedFragments"
363
+ select="$theDocument_2/*/iso:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
364
+ <xsl:if test="not($theDocument_2)">
365
+ <xsl:message terminate="no">
366
+ <xsl:text>Unable to open referenced included file: </xsl:text>
367
+ <xsl:value-of select="@href" />
368
+ </xsl:message>
369
+ </xsl:if>
370
+
371
+ <!-- There are three cases for includes:
372
+ 0) No text specified- error!
373
+
374
+ 1) REMOVED
375
+
376
+ 2) The linked-to element is sch:schema however the parent of the include
377
+ is not a schema. In this case, it is an error. (Actually, it should
378
+ be an error for other kinds of containment problems, but we won't
379
+ check for them in this version.)
380
+
381
+ 3) Otherwise, include the pointed-to element
382
+ -->
383
+ <xsl:choose>
384
+ <!-- case 0 -->
385
+ <xsl:when
386
+ test="not($theFragment_2) and not ($theContainedFragments)">
387
+ <xsl:message terminate="no">
388
+ <xsl:text>Unable to locate id attribute: </xsl:text>
389
+ <xsl:value-of select="@href" />
390
+ </xsl:message>
391
+ </xsl:when>
392
+
393
+ <!-- case 1 removed -->
394
+
395
+ <!-- case 2 -->
396
+ <xsl:when
397
+ test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
398
+ <xsl:message>
399
+ Schema error: Use include to include
400
+ fragments, not a whole schema
401
+ </xsl:message>
402
+ </xsl:when>
403
+
404
+ <!-- If this were XLST 2, we could use
405
+ if ($theFragment) then $theFragment else $theContainedFragments
406
+ here (thanks to KN)
407
+ -->
408
+ <!-- case 3 -->
409
+ <xsl:otherwise>
410
+ <xsl:apply-templates
411
+ select="$theFragment_2 " mode="dsdl:go" />
412
+ </xsl:otherwise>
413
+ </xsl:choose>
414
+ </xsl:otherwise>
415
+ </xsl:choose>
416
+ </xsl:otherwise>
417
+ </xsl:choose>
418
+
419
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
420
+ <xsl:value-of select="@href" />
421
+ </xsl:processing-instruction>
422
+ </xsl:template>
423
+
424
+
425
+ <!-- WARNING sch:extends[@href] is experimental and non standard -->
426
+ <!-- Basically, it adds the children of the selected element, not the element itself. -->
427
+ <xsl:template match="iso:extends[@href]" mode="dsdl:go">
428
+
429
+ <xsl:variable name="document-uri"
430
+ select="substring-before(concat(@href,'#'), '#')" />
431
+ <xsl:variable name="fragment-id"
432
+ select="substring-after(@href, '#')" />
433
+
434
+
435
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
436
+ <xsl:value-of select="@href" />
437
+ </xsl:processing-instruction>
438
+
439
+ <xsl:choose>
440
+ <xsl:when test="not( $include-schematron = 'true' )">
441
+ <xslt:copy>
442
+ <xslt:copy-of select="@*" />
443
+ <xslt:apply-templates mode="dsdl:go" />
444
+ </xslt:copy>
445
+ </xsl:when>
446
+ <xsl:otherwise>
447
+
448
+ <xsl:choose>
449
+
450
+ <xsl:when
451
+ test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
452
+ <xsl:message>
453
+ Error: Impossible URL in Schematron include
454
+ </xsl:message>
455
+ </xsl:when>
456
+
457
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
458
+ <xslt:when
459
+ test="string-length( $document-uri ) = 0">
460
+ <xslt:apply-templates mode="dsdl:go"
461
+ select="//iso:*[@xml:id= $fragment-id ]/*
462
+ |id( $fragment-id)/*
463
+ | //iso:*[@id= $fragment-id ]/*" />
464
+ </xslt:when>
465
+
466
+ <!-- case where there is a fragment in another document (should be an iso: element) -->
467
+ <!-- There are three cases for includes with fragment:
468
+ 0) No href file or no matching id - error!
469
+ 1) REMOVED
470
+
471
+ 2) REMOVED
472
+
473
+ 3) Otherwise, include the pointed-to element
474
+ -->
475
+
476
+ <xsl:when
477
+ test="string-length( $fragment-id ) &gt; 0">
478
+ <xsl:variable name="theDocument_1"
479
+ select="document( $document-uri,/ )" />
480
+ <xsl:variable name="originalParent" select=".." />
481
+
482
+ <!-- case 0 -->
483
+ <xsl:if test="not($theDocument_1)">
484
+ <xsl:message terminate="no">
485
+ <xsl:text>Unable to open referenced included file: </xsl:text>
486
+ <xsl:value-of select="@href" />
487
+ </xsl:message>
488
+ </xsl:if>
489
+ <!-- use for-each to rebase id() to external document -->
490
+ <xsl:for-each select="$theDocument_1">
491
+ <xsl:variable name="theFragment_1"
492
+ select=" $theDocument_1//iso:*[@xml:id= $fragment-id ] |
493
+ id($fragment-id) |
494
+ $theDocument_1//iso:*[@id= $fragment-id ]" />
495
+
496
+
497
+ <xsl:choose>
498
+ <!-- case 0 -->
499
+ <xsl:when test="not($theFragment_1)">
500
+ <xsl:message terminate="no">
501
+ <xsl:text>Unable to locate id attribute: </xsl:text>
502
+ <xsl:value-of select="@href" />
503
+ </xsl:message>
504
+ </xsl:when>
505
+
506
+
507
+ <!-- case 1 REMOVED -->
508
+
509
+ <!-- case 2 REMOVED -->
510
+
511
+
512
+ <!-- case 3 -->
513
+ <xsl:otherwise>
514
+
515
+ <xsl:apply-templates
516
+ select=" $theFragment_1[1]/*" mode="dsdl:go" />
517
+ </xsl:otherwise>
518
+ </xsl:choose>
519
+ </xsl:for-each>
520
+ </xsl:when>
521
+
522
+ <!-- Case where there is no ID so we include the whole document -->
523
+ <!-- Experimental addition: include fragments of children -->
524
+ <xsl:otherwise>
525
+ <xsl:variable name="theDocument_2"
526
+ select="document( $document-uri,/ )" />
527
+ <xsl:variable name="theFragment_2"
528
+ select="$theDocument_2/iso:*" />
529
+ <xsl:variable name="theContainedFragments"
530
+ select="$theDocument_2/*/iso:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
531
+ <xsl:if test="not($theDocument_2)">
532
+ <xsl:message terminate="no">
533
+ <xsl:text>Unable to open referenced included file: </xsl:text>
534
+ <xsl:value-of select="@href" />
535
+ </xsl:message>
536
+ </xsl:if>
537
+
538
+ <!-- There are three cases for includes:
539
+ 0) No text specified- error!
540
+
541
+ 1) REMOVED
542
+
543
+ 2) REMOVED
544
+
545
+ 3) Otherwise, include the pointed-to element
546
+ -->
547
+ <xsl:choose>
548
+ <!-- case 0 -->
549
+ <xsl:when
550
+ test="not($theFragment_2) and not ($theContainedFragments)">
551
+ <xsl:message terminate="no">
552
+ <xsl:text>Unable to locate id attribute: </xsl:text>
553
+ <xsl:value-of select="@href" />
554
+ </xsl:message>
555
+ </xsl:when>
556
+
557
+ <!-- case 1 removed -->
558
+
559
+ <!-- case 2 removed -->
560
+
561
+ <!-- If this were XLST 2, we could use
562
+ if ($theFragment) then $theFragment else $theContainedFragments
563
+ here (thanks to KN)
564
+ -->
565
+ <!-- case 3 -->
566
+ <xsl:otherwise>
567
+ <xsl:apply-templates
568
+ select="$theFragment_2/* " mode="dsdl:go" />
569
+ </xsl:otherwise>
570
+ </xsl:choose>
571
+ </xsl:otherwise>
572
+ </xsl:choose>
573
+ </xsl:otherwise>
574
+ </xsl:choose>
575
+
576
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
577
+ <xsl:value-of select="@href" />
578
+ </xsl:processing-instruction>
579
+ </xsl:template>
580
+
581
+
582
+
583
+ <!-- =========================================================== -->
584
+ <!-- Handle Schematron 1.6 inclusions: clone of ISO code above -->
585
+ <!-- =========================================================== -->
586
+
587
+
588
+ <!-- Extend the URI syntax to allow # references -->
589
+ <!-- Add experimental support for simple containers like /xxx:xxx/schold:pattern to allow better includes -->
590
+ <xsl:template match="schold:include" mode="dsdl:go">
591
+ <xsl:variable name="document-uri"
592
+ select="substring-before(concat(@href,'#'), '#')" />
593
+ <xsl:variable name="fragment-id"
594
+ select="substring-after(@href, '#')" />
595
+
596
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
597
+ <xsl:value-of select="@href" />
598
+ </xsl:processing-instruction>
599
+
600
+ <xsl:choose>
601
+ <xsl:when test="not( $include-schematron = 'true' )">
602
+ <xslt:copy>
603
+ <xslt:copy-of select="@*" />
604
+ <xslt:apply-templates mode="dsdl:go" />
605
+ </xslt:copy>
606
+ </xsl:when>
607
+ <xsl:otherwise>
608
+ <xsl:choose>
609
+
610
+ <xsl:when
611
+ test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
612
+ <xsl:message>
613
+ Error: Impossible URL in Schematron include
614
+ </xsl:message>
615
+ </xsl:when>
616
+
617
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
618
+ <xslt:when
619
+ test="string-length( $document-uri ) = 0">
620
+ <xslt:apply-templates mode="dsdl:go"
621
+ select="//schold:*[@xml:id= $fragment-id ]
622
+ |id( $fragment-id)
623
+ | //schold:*[@id= $fragment-id ]" />
624
+ </xslt:when>
625
+
626
+ <!-- case where there is a fragment in another document (should be an iso: element) -->
627
+ <xsl:when
628
+ test="string-length( $fragment-id ) &gt; 0">
629
+ <xsl:variable name="theDocument_1"
630
+ select="document( $document-uri,/ )" />
631
+ <xsl:if test="not($theDocument_1)">
632
+ <xsl:message terminate="no">
633
+ <xsl:text>Unable to open referenced included file: </xsl:text>
634
+ <xsl:value-of select="@href" />
635
+ </xsl:message>
636
+ </xsl:if>
637
+ <!-- use for-each to rebase id() to $theDocument -->
638
+ <xsl:for-each select="$theDocument_1">
639
+ <xsl:variable name="theFragment_1"
640
+ select=" $theDocument_1//schold:*[@xml:id= $fragment-id ] |
641
+ id($fragment-id) |
642
+ $theDocument_1//schold:*[@id= $fragment-id ]" />
643
+ <xsl:if
644
+ test=" $theFragment_1/self::schold:schema ">
645
+ <xsl:message>
646
+ Schema error: Use include to include
647
+ fragments, not a whole schema
648
+ </xsl:message>
649
+ </xsl:if>
650
+ <xsl:if test="not($theFragment_1)">
651
+ <xsl:message terminate="no">
652
+ <xsl:text>Unable to locate id attribute: </xsl:text>
653
+ <xsl:value-of select="@href" />
654
+ </xsl:message>
655
+ </xsl:if>
656
+ <xsl:apply-templates
657
+ select=" $theFragment_1[1]" mode="dsdl:go" />
658
+ </xsl:for-each>
659
+ </xsl:when>
660
+
661
+ <!-- Case where there is no ID so we include the whole document -->
662
+ <!-- Experimental addition: include fragments of children -->
663
+ <xsl:otherwise>
664
+ <xsl:variable name="theDocument_2"
665
+ select="document( $document-uri,/ )" />
666
+ <xsl:variable name="theFragment_2"
667
+ select="$theDocument_2/iso:*" />
668
+ <xsl:variable name="theContainedFragments"
669
+ select="$theDocument_2/*/schold:* | $theDocument_2/*/xsl:* | $theDocument_2/*/xhtml:*" />
670
+ <xsl:if test="not($theDocument_2)">
671
+ <xsl:message terminate="no">
672
+ <xsl:text>Unable to open referenced included file: </xsl:text>
673
+ <xsl:value-of select="@href" />
674
+ </xsl:message>
675
+ </xsl:if>
676
+
677
+ <xsl:if
678
+ test=" $theFragment_2/self::schold:schema or $theContainedFragments/self::schold:schema">
679
+ <xsl:message>
680
+ Schema error: Use include to include
681
+ fragments, not a whole schema
682
+ </xsl:message>
683
+ </xsl:if>
684
+ <xsl:if
685
+ test="not($theFragment_2) and not ($theContainedFragments)">
686
+ <xsl:message terminate="no">
687
+ <xsl:text>Unable to locate id attribute: </xsl:text>
688
+ <xsl:value-of select="@href" />
689
+ </xsl:message>
690
+ </xsl:if>
691
+ <!-- If this were XLST 2, we could use
692
+ if ($theFragment) then $theFragment else $theContainedFragments
693
+ here (thanks to KN)
694
+ -->
695
+ <xsl:choose>
696
+ <xsl:when test=" $theFragment_2 ">
697
+ <xsl:apply-templates
698
+ select="$theFragment_2 " mode="dsdl:go" />
699
+ </xsl:when>
700
+ <xsl:otherwise>
701
+ <!-- WARNING! EXPERIMENTAL! Use at your own risk. This may be discontinued! -->
702
+ <xsl:apply-templates
703
+ select=" $theContainedFragments " mode="dsdl:go" />
704
+ </xsl:otherwise>
705
+ </xsl:choose>
706
+ </xsl:otherwise>
707
+ </xsl:choose>
708
+
709
+ </xsl:otherwise>
710
+ </xsl:choose>
711
+
712
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
713
+ <xsl:value-of select="@href" />
714
+ </xsl:processing-instruction>
715
+ </xsl:template>
716
+ <!-- =========================================================== -->
717
+ <!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
718
+ <!-- Part 5 - DataType Library Language - DTLL -->
719
+ <!-- Committee Draft Experimental support only -->
720
+ <!-- The <include> element may well be replaced by XInclude in -->
721
+ <!-- any final version. -->
722
+ <!-- =========================================================== -->
723
+ <xslt:template match="dtll:include" mode="dsdl:go">
724
+ <!-- Insert subschema -->
725
+
726
+ <xsl:variable name="document-uri"
727
+ select="substring-before(concat(@href,'#'), '#')" />
728
+ <xsl:variable name="fragment-id"
729
+ select="substring-after(@href, '#')" />
730
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
731
+ <xsl:value-of select="@href" />
732
+ </xsl:processing-instruction>
733
+ <xsl:choose>
734
+ <xsl:when test="not( $include-dtll = 'true' )">
735
+ <xslt:copy>
736
+ <xslt:copy-of select="@*" />
737
+ <xslt:apply-templates mode="dsdl:go" />
738
+ </xslt:copy>
739
+ </xsl:when>
740
+ <xsl:otherwise>
741
+ <xsl:choose>
742
+
743
+ <xsl:when
744
+ test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
745
+ <xsl:message>
746
+ Error: Impossible URL in DTLL include
747
+ </xsl:message>
748
+ </xsl:when>
749
+
750
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
751
+ <xslt:when
752
+ test="string-length( $document-uri ) = 0">
753
+ <xslt:apply-templates mode="dsdl:go"
754
+ select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
755
+ | //*[@id= $fragment-id ]" />
756
+ </xslt:when>
757
+
758
+ <xsl:when
759
+ test="string-length( $fragment-id ) &gt; 0">
760
+ <xsl:variable name="theDocument_1"
761
+ select="document( $document-uri,/ )" />
762
+ <xsl:if test="not($theDocument_1)">
763
+ <xsl:message terminate="no">
764
+ <xsl:text>Unable to open referenced included file: </xsl:text>
765
+ <xsl:value-of select="@href" />
766
+ </xsl:message>
767
+ </xsl:if>
768
+ <!-- use for-each to rebase id() to $theDocument -->
769
+ <xsl:for-each select="$theDocument_1">
770
+ <xsl:variable name="theFragment_1"
771
+ select="$theDocument_1//*[@xml:id= $fragment-id ]
772
+ | id( $fragment-id )
773
+ | $theDocument_1//*[@id= $fragment-id ]" />
774
+ <xsl:if test="not($theFragment_1)">
775
+ <xsl:message terminate="no">
776
+ <xsl:text>Unable to locate id attribute: </xsl:text>
777
+ <xsl:value-of select="@href" />
778
+ </xsl:message>
779
+ </xsl:if>
780
+ <xsl:apply-templates
781
+ select=" $theFragment_1[1]" mode="dsdl:go" />
782
+ </xsl:for-each>
783
+ </xsl:when>
784
+
785
+ <xsl:otherwise>
786
+ <xsl:variable name="theDocument_2"
787
+ select="document( $document-uri,/ )" />
788
+ <xsl:variable name="theFragment_2"
789
+ select="$theDocument_2/*" />
790
+
791
+ <xsl:if test="not($theDocument_2)">
792
+ <xsl:message terminate="no">
793
+ <xsl:text>Unable to open referenced included file: </xsl:text>
794
+ <xsl:value-of select="@href" />
795
+ </xsl:message>
796
+ </xsl:if>
797
+
798
+ <xsl:if test="not($theFragment_2)">
799
+ <xsl:message terminate="no">
800
+ <xsl:text>Unable to locate id attribute: </xsl:text>
801
+ <xsl:value-of select="@href" />
802
+ </xsl:message>
803
+ </xsl:if>
804
+ <xsl:apply-templates select="$theFragment_2 "
805
+ mode="dsdl:go" />
806
+ </xsl:otherwise>
807
+ </xsl:choose>
808
+
809
+ </xsl:otherwise>
810
+ </xsl:choose>
811
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
812
+ <xsl:value-of select="@href" />
813
+ </xsl:processing-instruction>
814
+ </xslt:template>
815
+
816
+ <!-- =========================================================== -->
817
+ <!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
818
+ <!-- Part 7 - Character Repertoire Description Language - CRDL -->
819
+ <!-- Final Committee Draft 2008-01-11 Experimental support only -->
820
+ <!-- =========================================================== -->
821
+ <xslt:template match="crdl:ref" mode="dsdl:go">
822
+ <!-- Insert subschema -->
823
+
824
+ <xsl:variable name="document-uri"
825
+ select="substring-before(concat(@href,'#'), '#')" />
826
+ <xsl:variable name="fragment-id"
827
+ select="substring-after(@href, '#')" />
828
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
829
+ <xsl:value-of select="@href" />
830
+ </xsl:processing-instruction>
831
+ <xsl:choose>
832
+ <xsl:when test="not( $include-crdl = 'true' )">
833
+ <xslt:copy>
834
+ <xslt:copy-of select="@*" />
835
+ <xslt:apply-templates mode="dsdl:go" />
836
+ </xslt:copy>
837
+ </xsl:when>
838
+ <xsl:otherwise>
839
+ <xsl:choose>
840
+
841
+ <xsl:when
842
+ test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
843
+ <xsl:message>
844
+ Error: Impossible URL in CRDL include
845
+ </xsl:message>
846
+ </xsl:when>
847
+
848
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
849
+ <xslt:when
850
+ test="string-length( $document-uri ) = 0">
851
+
852
+ <xslt:apply-templates mode="dsdl:go"
853
+ select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
854
+ | //*[@id= $fragment-id ]" />
855
+ </xslt:when>
856
+
857
+ <xsl:when
858
+ test="string-length( $fragment-id ) &gt; 0">
859
+ <xsl:variable name="theDocument_1"
860
+ select="document( $document-uri,/ )" />
861
+ <xsl:if test="not($theDocument_1)">
862
+ <xsl:message terminate="no">
863
+ <xsl:text>Unable to open referenced included file: </xsl:text>
864
+ <xsl:value-of select="@href" />
865
+ </xsl:message>
866
+ </xsl:if>
867
+ <!-- use for-each to rebase id() to $theDocument -->
868
+ <xsl:for-each select="$theDocument_1">
869
+ <xsl:variable name="theFragment_1"
870
+ select="$theDocument_1//*[@xml:id= $fragment-id ]
871
+ | id( $fragment-id )
872
+ | $theDocument_1//*[@id= $fragment-id ]" />
873
+
874
+ <xsl:if test="not($theFragment_1)">
875
+ <xsl:message terminate="no">
876
+ <xsl:text>Unable to locate id attribute: </xsl:text>
877
+ <xsl:value-of select="@href" />
878
+ </xsl:message>
879
+ </xsl:if>
880
+ <xsl:apply-templates select=" $theFragment_1 "
881
+ mode="dsdl:go" />
882
+ </xsl:for-each>
883
+ </xsl:when>
884
+
885
+ <xsl:otherwise>
886
+ <xsl:variable name="theDocument_2"
887
+ select="document( $document-uri,/ )" />
888
+ <xsl:variable name="theFragment_2"
889
+ select="$theDocument_2/*" />
890
+
891
+ <xsl:if test="not($theDocument_2)">
892
+ <xsl:message terminate="no">
893
+ <xsl:text>Unable to open referenced included file: </xsl:text>
894
+ <xsl:value-of select="@href" />
895
+ </xsl:message>
896
+ </xsl:if>
897
+ <xsl:if test="not($theFragment_2)">
898
+ <xsl:message terminate="no">
899
+ <xsl:text>Unable to locate id attribute: </xsl:text>
900
+ <xsl:value-of select="@href" />
901
+ </xsl:message>
902
+ </xsl:if>
903
+
904
+ <xsl:apply-templates select="$theFragment_2"
905
+ mode="dsdl:go" />
906
+ </xsl:otherwise>
907
+ </xsl:choose>
908
+
909
+ </xsl:otherwise>
910
+ </xsl:choose>
911
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
912
+ <xsl:value-of select="@href" />
913
+ </xsl:processing-instruction>
914
+ </xslt:template>
915
+
916
+
917
+ <!-- =========================================================== -->
918
+ <!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
919
+ <!-- Part 4 - Namespace-based Validation Dispatching Language - NVDL -->
920
+ <!-- Note: This does not include schemas referenced for -->
921
+ <!-- validation, it merely handles any simple XIncludes -->
922
+ <!-- =========================================================== -->
923
+ <!-- ISO/IEC 19757 - DSDL Document Schema Definition Languages -->
924
+ <!-- Part 8 - Document Schema Renaming Language - DSRL -->
925
+ <!-- Note: Final? Committee Draft Experimental support only -->
926
+ <!-- =========================================================== -->
927
+ <!-- XInclude support for id based references only, with 1 level -->
928
+ <!-- of fallback. -->
929
+ <!-- =========================================================== -->
930
+
931
+ <xslt:template mode="dsdl:go"
932
+ match="xi:include[@href][not(@parseType) or @parseType ='xml']">
933
+ <!-- Simple inclusions only here -->
934
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
935
+ <xsl:value-of select="@href" />
936
+ </xsl:processing-instruction>
937
+ <xsl:choose>
938
+ <xsl:when test="not( $include-xinclude = 'true' )">
939
+ <xslt:copy>
940
+ <xslt:copy-of select="@*" />
941
+ <xslt:apply-templates mode="dsdl:go" />
942
+ </xslt:copy>
943
+ </xsl:when>
944
+ <xsl:otherwise>
945
+ <xsl:choose>
946
+
947
+ <xsl:when test="contains( @href, '#')">
948
+ <xsl:message terminate="yes">
949
+ Fatal error: Xinclude href contains fragment
950
+ identifier #
951
+ </xsl:message>
952
+ </xsl:when>
953
+
954
+
955
+ <xsl:when test="contains( @xpointer, '(')">
956
+ <xsl:message terminate="yes">
957
+ Fatal error: Sorry, this software only
958
+ supports simple ids in XInclude xpointers
959
+ </xsl:message>
960
+ </xsl:when>
961
+
962
+ <xsl:when
963
+ test="string-length( @href ) = 0 and string-length( @xpointer ) = 0">
964
+
965
+ <xsl:message terminate="yes">
966
+ Fatal Error: Impossible URL in XInclude
967
+ include
968
+ </xsl:message>
969
+ </xsl:when>
970
+
971
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
972
+ <xslt:when test="string-length( @href ) = 0">
973
+
974
+ <xslt:apply-templates mode="dsdl:go"
975
+ select="//*[@xml:id= current()/@xpointer ] | id( @xpointer)
976
+ | //*[@id= current()/@xpointer ]" />
977
+ </xslt:when>
978
+
979
+ <xsl:when
980
+ test="string-length( @xpointer ) &gt; 0">
981
+ <xsl:variable name="theDocument_1"
982
+ select="document( @href,/ )" />
983
+ <xsl:variable name="theFragment_1"
984
+ select="$theDocument_1//*[@xml:id= current()/@xpointer ]
985
+
986
+ | $theDocument_1//*[@id= current()/@xpointer ]" />
987
+ <!-- removed
988
+ | $theDocument_1/id( @xpointer)
989
+ because it requires rebasing in XSLT1 and that would mess up the use of current()
990
+ -->
991
+
992
+
993
+ <!-- Allow one level of fallback, to another XInclude -->
994
+ <xsl:if test="not($theDocument_1)">
995
+ <xsl:choose>
996
+ <xsl:when test="xi:fallback">
997
+ <xsl:variable name="theDocument_2"
998
+ select="document( xi:fallback[1]/xi:include[not(@parseType)
999
+ or @parseType='xml']/@href,/ )" />
1000
+ <xsl:variable name="theFragment_2"
1001
+ select="$theDocument_2//*[@xml:id= current()/xi:fallback[1]/xi:include/@xpointer ]
1002
+ | $theDocument_2//*[@id= current()/xi:fallback[1]/xi:include/@xpointer ]" />
1003
+ <!-- removed
1004
+ | $theDocument_2/id( xi:fallback[1]/xi:include/@xpointer)
1005
+ because it id() would need rebasing in XSLT1 and that would mess up use of current()
1006
+ -->
1007
+
1008
+ <xsl:if
1009
+ test="not($theDocument_2)">
1010
+
1011
+ <xsl:message terminate="no">
1012
+ <xsl:text>Unable to open referenced included file and fallback
1013
+ file: </xsl:text>
1014
+ <xsl:value-of
1015
+ select="@href" />
1016
+ </xsl:message>
1017
+ </xsl:if>
1018
+ </xsl:when>
1019
+ <xsl:otherwise>
1020
+ <xsl:message terminate="no">
1021
+ <xsl:text>Unable to open referenced included file: </xsl:text>
1022
+ <xsl:value-of select="@href" />
1023
+ </xsl:message>
1024
+ </xsl:otherwise>
1025
+ </xsl:choose>
1026
+ </xsl:if>
1027
+ <xsl:apply-templates select=" $theFragment_1"
1028
+ mode="dsdl:go" />
1029
+ </xsl:when>
1030
+
1031
+ <!-- Document but no fragment specified -->
1032
+ <xsl:otherwise>
1033
+ <xsl:variable name="theDocument_3"
1034
+ select="document( @href,/ )" />
1035
+ <xsl:variable name="theFragment_3"
1036
+ select="$theDocument_3/*" />
1037
+
1038
+ <xsl:if test="not($theDocument_3)">
1039
+ <xsl:message terminate="no">
1040
+ <xsl:text>Unable to open referenced included file: </xsl:text>
1041
+ <xsl:value-of select="@href" />
1042
+ </xsl:message>
1043
+ </xsl:if>
1044
+
1045
+ <xsl:apply-templates select="$theFragment_3 "
1046
+ mode="dsdl:go" />
1047
+ </xsl:otherwise>
1048
+ </xsl:choose>
1049
+
1050
+ </xsl:otherwise>
1051
+ </xsl:choose>
1052
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
1053
+ <xsl:value-of select="@href" />
1054
+ </xsl:processing-instruction>
1055
+ </xslt:template>
1056
+
1057
+ <!-- =========================================================== -->
1058
+ <!-- W3C XLink 1.1 embedded simple links -->
1059
+ <!-- =========================================================== -->
1060
+ <xslt:template
1061
+ match="*[@xlink:href][not(parent::*[@xlink:type='complex'])]
1062
+ [not(@xlink:type) or (@xlink:type='simple')]
1063
+ [@xlink:show='embed']
1064
+ [not(@xlink:actuate) or (@xlink:actuate='onLoad')]"
1065
+ mode="dsdl:go" priority="1">
1066
+
1067
+ <xsl:variable name="document-uri"
1068
+ select="substring-before(concat(@xlink:href,'#'), '#')" />
1069
+ <xsl:variable name="fragment-id"
1070
+ select="substring-after(@xlink:href, '#')" />
1071
+ <xsl:processing-instruction name="DSDL_INCLUDE_START">
1072
+ <xsl:value-of select="@xlink:href" />
1073
+ </xsl:processing-instruction>
1074
+ <xsl:choose>
1075
+ <xsl:when test="not( $include-xlink = 'true' )">
1076
+ <xslt:copy>
1077
+ <xslt:copy-of select="@*" />
1078
+ <xslt:apply-templates mode="dsdl:go" />
1079
+ </xslt:copy>
1080
+ </xsl:when>
1081
+ <xsl:otherwise>
1082
+ <xsl:choose>
1083
+
1084
+ <xsl:when
1085
+ test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0">
1086
+ <xsl:message>
1087
+ Error: Impossible URL in XLink embedding
1088
+ link
1089
+ </xsl:message>
1090
+ </xsl:when>
1091
+
1092
+ <!-- this case is when there is in embedded schema in the same document elsewhere -->
1093
+ <xslt:when
1094
+ test="string-length( $document-uri ) = 0">
1095
+ <xslt:apply-templates mode="dsdl:go"
1096
+ select="//*[@xml:id= $fragment-id ] | id( $fragment-id)
1097
+ | //*[@id= $fragment-id ]" />
1098
+ </xslt:when>
1099
+
1100
+ <xsl:when
1101
+ test="string-length( $fragment-id ) &gt; 0">
1102
+ <xsl:variable name="theDocument_1"
1103
+ select="document( $document-uri,/ )" />
1104
+ <xsl:if test="not($theDocument_1)">
1105
+ <xsl:message terminate="no">
1106
+ <xsl:text>Unable to open referenced included file: </xsl:text>
1107
+ <xsl:value-of select="@xlink:href" />
1108
+ </xsl:message>
1109
+ </xsl:if>
1110
+ <!-- use for-each to rebase id() to $theDocument -->
1111
+ <xsl:for-each select="$theDocument_1">
1112
+ <xsl:variable name="theFragment_1"
1113
+ select="$theDocument_1//*[@xml:id= $fragment-id ]
1114
+ | id( $fragment-id )
1115
+ | $theDocument_1//*[@id= $fragment-id ]" />
1116
+ <xsl:if test="not($theFragment_1)">
1117
+ <xsl:message terminate="no">
1118
+ <xsl:text>Unable to locate id attribute: </xsl:text>
1119
+ <xsl:value-of select="@xlink:href" />
1120
+ </xsl:message>
1121
+ </xsl:if>
1122
+ <xsl:apply-templates
1123
+ select=" $theFragment_1[1]" mode="dsdl:go" />
1124
+ </xsl:for-each>
1125
+ </xsl:when>
1126
+
1127
+ <xsl:otherwise>
1128
+ <xsl:variable name="theDocument_2"
1129
+ select="document( $document-uri,/ )" />
1130
+ <xsl:variable name="theFragment_2"
1131
+ select="$theDocument_2/*" />
1132
+
1133
+ <xsl:if test="not($theDocument_2)">
1134
+ <xsl:message terminate="no">
1135
+ <xsl:text>Unable to open referenced included file: </xsl:text>
1136
+ <xsl:value-of select="@xlink:href" />
1137
+ </xsl:message>
1138
+ </xsl:if>
1139
+
1140
+ <xsl:if test="not($theFragment_2)">
1141
+ <xsl:message terminate="no">
1142
+ <xsl:text>Unable to locate id attribute: </xsl:text>
1143
+ <xsl:value-of select="@xlink:href" />
1144
+ </xsl:message>
1145
+ </xsl:if>
1146
+ <xsl:apply-templates select="$theFragment_2 "
1147
+ mode="dsdl:go" />
1148
+ </xsl:otherwise>
1149
+ </xsl:choose>
1150
+
1151
+ </xsl:otherwise>
1152
+ </xsl:choose>
1153
+
1154
+ <xsl:processing-instruction name="DSDL_INCLUDE_END">
1155
+ <xsl:value-of select="@xlink:href" />
1156
+ </xsl:processing-instruction>
1157
+ </xslt:template>
1158
+
1159
+
1160
+ </xslt:stylesheet>
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" ?><?xar XSLT?>
2
+ <!-- Implmentation for the Schematron XML Schema Language.
3
+ http://www.ascc.net/xml/resource/schematron/schematron.html
4
+
5
+ Copyright (c) 2000,2001 Rick Jelliffe and Academia Sinica Computing Center, Taiwan
6
+
7
+ This software is provided 'as-is', without any express or implied warranty.
8
+ In no event will the authors be held liable for any damages arising from
9
+ the use of this software.
10
+
11
+ Permission is granted to anyone to use this software for any purpose,
12
+ including commercial applications, and to alter it and redistribute it freely,
13
+ subject to the following restrictions:
14
+
15
+ 1. The origin of this software must not be misrepresented; you must not claim
16
+ that you wrote the original software. If you use this software in a product,
17
+ an acknowledgment in the product documentation would be appreciated but is
18
+ not required.
19
+
20
+ 2. Altered source versions must be plainly marked as such, and must not be
21
+ misrepresented as being the original software.
22
+
23
+ 3. This notice may not be removed or altered from any source distribution.
24
+ -->
25
+
26
+ <!-- Schematron message -->
27
+
28
+ <xsl:stylesheet
29
+ version="1.0"
30
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
31
+ xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias">
32
+
33
+ <xsl:import href="iso_schematron_skeleton_for_xslt1.xsl"/>
34
+
35
+ <xsl:template name="process-prolog">
36
+ <axsl:output method="text" />
37
+ </xsl:template>
38
+
39
+ <!-- use default rule for process-root: copy contens / ignore title -->
40
+ <!-- use default rule for process-pattern: ignore name and see -->
41
+ <!-- use default rule for process-name: output name -->
42
+ <!-- use default rule for process-assert and process-report:
43
+ call process-message -->
44
+
45
+ <xsl:template name="process-message">
46
+ <xsl:param name="pattern" />
47
+ <xsl:param name="role" />
48
+ <axsl:message>
49
+ <xsl:apply-templates mode="text"
50
+ /> (<xsl:value-of select="$pattern" />
51
+ <xsl:if test="$role"> / <xsl:value-of select="$role" />
52
+ </xsl:if>)</axsl:message>
53
+ </xsl:template>
54
+
55
+ </xsl:stylesheet>
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl ADDED
@@ -0,0 +1,1796 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?><?xar XSLT?>
2
+
3
+ <!--
4
+ OVERVIEW
5
+
6
+ ASCC/Schematron.com Skeleton Module for ISO Schematron (for XSLT1 systems)
7
+
8
+ ISO Schematron is a language for making assertion about the presence or absence
9
+ of patterns in XML documents. It is typically used for as a schema language, or
10
+ to augment existing schema languages, and to check business rules. It is very
11
+ powerful, yet quite simple: a developer only need know XPath and about five other
12
+ elements.
13
+
14
+ This is an open source implementation of ISO Schematron in XSLT. Although ISO does
15
+ not allow reference implementations which might compete with the text of the
16
+ standard, this code has been compiled by Rick Jelliffe, inventor of Schematron
17
+ and editor of the ISO standard; so developers can certainly use it as an
18
+ unofficial reference implementation for clarification.
19
+
20
+ This implementation is based on one by Oliver Becker. API documentation is
21
+ available separately; try www.schematron.com for this. Funding for this
22
+ stylesheet over the years has come from Topologi Pty. Ltd., Geotempo Ltd.,
23
+ and ASCC, Tapei.
24
+
25
+ There are two versions of this skeleton: one is tailored for XSLT1 processors
26
+ and the other is tailored for XSLT2 processors. Future versions of the
27
+ XSLT2 skeleton may support more features than that the XSLT 1 skeleton.
28
+ -->
29
+ <!--
30
+ TIPS
31
+
32
+ A tip for new users of Schematron: make your assertions contain positive messages
33
+ about what is expected, rather than error messages. For example, use the form
34
+ "An X should have a Y, because Z".
35
+
36
+ Another tip is that Schematron provides an
37
+ element <sch:ns> for declaring the namespaces and prefixes used in Xpaths in
38
+ attribute values; it does not extend the XML Namespaces mechanism: if a name
39
+ in an XPath has a prefix, there must be an <sch:ns> element for that prefix; if
40
+ a name in an XPath does not have a prefix, it is always in no namespace.
41
+
42
+ A tip for implementers of Schematron, either using this API or re-implementing it:
43
+ make the value of the diagnostics, flags and richer features available if possible;
44
+ Schematron has many of the optional richer features which, if implemented, provide
45
+ a compelling alternative approach to validation and business-rules checking compared
46
+ to other schema languages and programs.
47
+
48
+ If you create your own meta-stylesheet to override this one, it is a
49
+ good idea to have both in the same directory and to run the stylesheet
50
+ from that directory, as many XSLT implementations have ideosyncratic
51
+ handling of URLs: keep it simple.
52
+ -->
53
+
54
+
55
+ <!--
56
+ INVOCATION INFORMATION
57
+
58
+ The following parameters are available
59
+
60
+ phase NMTOKEN | "#ALL" (default) Select the phase for validation
61
+ allow-foreign "true" | "false" (default) Pass non-Schematron elements to the generated stylesheet
62
+ sch.exslt.imports semi-colon delimited string of filenames for some EXSLT implementations
63
+ message-newline "true" (default) | "false" Generate an extra newline at the end of messages
64
+ optimize "visit-no-attributes"
65
+ debug "true" | "false" (default) Debug mode lets compilation continue despite problems
66
+ attributes "true" | "false" (Autodetecting) Use only when the schema has no attributes as the context nodes
67
+ only-child-elements "true" | "false" (Autodetecting) Use only when the schema has no comments
68
+ or PI as the context nodes
69
+
70
+ The following parameters can be specified as Schematron variables in diagnostics, assertions and so on.
71
+ fileNameParameter string
72
+ fileDirParameter string
73
+ archiveNameParameter string In case of ZIP files
74
+ archiveDirParameter string In case of ZIP files
75
+ output-encoding Use when outputting to XML
76
+
77
+ Experimental: USE AT YOUR OWN RISK
78
+ visit-text "true" "false" Also visist text nodes for context. WARNING: NON_STARDARD.
79
+ select-contents '' | 'key' | '//' Select different implementation strategies
80
+
81
+ Conventions: Meta-stylesheets that override this may use the following parameters
82
+ generate-paths=true|false generate the @location attribute with XPaths
83
+ diagnose= yes | no Add the diagnostics to the assertion test in reports
84
+ terminate= yes | no Terminate on the first failed assertion or successful report
85
+ -->
86
+
87
+ <!--
88
+ XSLT VERSION SUPPORT
89
+
90
+ XSLT 1:
91
+ A schema using the standard XSLT 1 query binding will have a /schema/@queryBinding='xslt' or
92
+ nothing.
93
+
94
+ * Note: XT does not implement key() and will die if given it.
95
+ * Add all formal parameters to default templates
96
+ * Fix missing apply-templates from process-ns and add params back
97
+
98
+ EXSLT: Experimental support
99
+ A schema using the EXSLT query binding will have a /schema/@queryBinding='exslt'.
100
+ It is built on XSLT 1. After experience is gained, this binding is expected to be
101
+ formalized as part of ISO Schematron, which currently reserves the "exslt" name for this purpose.
102
+
103
+ Some EXSLT engines have the extra functions built-in. For these, there is no need to
104
+ provide library locations. For engines that require the functions, either hard code
105
+ them in this script or provide them on the command-line argument.
106
+
107
+ -->
108
+ <!--
109
+ PROCESS INFORMATION
110
+
111
+ This stylesheet compiles a Schematron schema (*.sch) into XSLT code (*.xsl).
112
+ The generated XSLT code can then be run against an XML file (*.xml, etc) and
113
+ will produce validation results.
114
+
115
+ The output of validation results is performed using named templates (process-*).
116
+ These can be overridden easily by making a new XSLT stylesheet that imports this
117
+ stylesheet but has its own version of the relevant process-* templates. Several
118
+ of these invoking stylesheets are available: "iso_svrl.xsl", for example generates
119
+ ISO Schematron Validation Report Language format results.
120
+
121
+ In this version of the stylesheet, the ISO feature called "abstract patterns" is
122
+ implemented using macro processing: a prior XSLT stage to which converts uses
123
+ of abstract patterns into normal patterns. If you do not use abstract patterns,
124
+ it is not necessary to preprocess the schema.
125
+
126
+ To summarize, a basic process flow for some commandline processor is like this:
127
+ XSLT -input=xxx.sch -output=xxx.xsl -stylesheet=iso_schematron_skeleton.xsl
128
+ XSLT -input=document.xml -output=xxx-document.results -stylesheet=xxx.xsl
129
+
130
+ iso_svrl.xslt is an implementation of Schematron that can use this skeleton and
131
+ generate ISO SVRL reports. A process flow for some commandline processor would
132
+ be like this:
133
+ XSLT -input=xxx.sch -output=xxx.xsl -stylesheet=iso_svrl.xsl
134
+ XSLT -input=document.xml -output=xxx-document.results -stylesheet=xxx.xsl
135
+
136
+ It is not impossible that ultimately a third stage, to handle macro-preprocessing
137
+ and inclusion, might be necessary. (The trade-off is in making this XSLT more
138
+ complex compared to making the outer process more complex.)
139
+
140
+ This version has so far been tested with
141
+ Saxon 8
142
+ MSXML 4 (or 6?)
143
+
144
+ Please note that if you are using SAXON and JAXP, then you should use
145
+ System.setProperty("javax.xml.transform.TransformerFactory",
146
+ "net.sf.saxon.TransformerFactoryImpl");
147
+ rather than
148
+ System.setProperty("javax.xml.xpath.TransformerFactory",
149
+ "net.sf.saxon.TransformerFactoryImpl");
150
+ which is does not work, at least for the versions of SAXON we tried.
151
+ -->
152
+ <!--
153
+ LEGAL INFORMATION
154
+
155
+ Copyright (c) 2000-2008 Rick Jelliffe and Academia Sinica Computing Center, Taiwan
156
+
157
+ This software is provided 'as-is', without any express or implied warranty.
158
+ In no event will the authors be held liable for any damages arising from
159
+ the use of this software.
160
+
161
+ Permission is granted to anyone to use this software for any purpose,
162
+ including commercial applications, and to alter it and redistribute it freely,
163
+ subject to the following restrictions:
164
+
165
+ 1. The origin of this software must not be misrepresented; you must not claim
166
+ that you wrote the original software. If you use this software in a product,
167
+ an acknowledgment in the product documentation would be appreciated but is
168
+ not required.
169
+
170
+ 2. Altered source versions must be plainly marked as such, and must not be
171
+ misrepresented as being the original software.
172
+
173
+ 3. This notice may not be removed or altered from any source distribution.
174
+ -->
175
+ <!--
176
+ NOTE: Compared to the iso_schematron_skeleton_for_saxon.xsl code, this version is currently missing
177
+ 1) localization
178
+ 2) properties
179
+ 3) pattern/@documents
180
+
181
+ VERSION INFORMATION
182
+ 2009-02-25 RJ
183
+ * Fix up variable names so none are used twice in same template
184
+ * Tested on SAXON 9, Xalan 2.7.1. Partly tested MSXML.
185
+ 2008-09-19 RJ
186
+ * Add mode schematron-select-full-path and param full-path-notation
187
+
188
+ 2008-08-11
189
+ * TT report/@flag was missing
190
+ 2008-08-06
191
+ * TT Top-level lets need to be implemented using xsl:param not xsl:variable
192
+ * TT xsl:param/@select must have XPath or not be specified
193
+
194
+ Version: 2008-07-28
195
+ * KH schematron-get-full-path-3 has [index] even on top step
196
+ * RJ fix schematron-get-full-path to have namespace predicate, I don't know why this was removed
197
+
198
+ Version: 2008-07-24
199
+ * RJ clean out commented out namespace handling code
200
+ * RJ add support for experimental non-standard attribute report/@action
201
+ and assert/@action, and add parameter not in the published API (should
202
+ not break anything, it is XSLT1)
203
+ * RJ Remove remaining XSLT2 code for ease of reading
204
+
205
+ Version: 2008-07-14 minor update for inclusion experiments
206
+ * RJ Clean up zero-length fragment test on include
207
+ * RJ Add experimental support for include containers
208
+ * RJ For path generation, test for //iso:schema not just /iso:schema, for potential embedded Schematron support
209
+ * RJ Don't generate double error messages for old namespace elements
210
+ * RJ Experimental iso:rule/iso:title just kept as comment (bigger request Uche Ogbuji)
211
+ * RJ Remove spurious debug messages
212
+ * RJ Fix bug that prevented including patterns in this (report Roger
213
+ Costello)
214
+
215
+ Version: 2007-10-17
216
+ From this version on I am forking XSLT2 support to a different version of the script.
217
+ This is due to the increasingly horrible state of the namespace handling code as well
218
+ as other inconsistencies between the major implementations of different versions.
219
+ The intent is that future versions of this will have XSLT2 isms removed and be simplified
220
+ to cope with only XSLT1 and EXLST. Note that though this version is called
221
+ iso_schematron_skeleton_for_xslt1, the various meta-stylesheets will continue to just call
222
+ iso_schematron_skeleton: it is up to you to rename the stylesheet to the one you want to
223
+ use.
224
+
225
+ * RJ fix FULL-PATH problem with attribute names
226
+
227
+
228
+ Version: 2007-07-19
229
+ Accept most changes in David Carlisle's fork, but continue as XSLT1 script:
230
+ http://dpcarlisle.blogspot.com/search/label/schematron
231
+ * DPC Remove "optimize" parameter
232
+ * DPC Add autodetecting optimize parameter attribute to skip checking attribute
233
+ context
234
+ * DPC Add autodetecting optimize parameter only-child-elements turn off checking for
235
+ comments and PIs
236
+ * DPC (Experimental: NON_STANDARD DANGER!) Add param visit-text to viist text
237
+ nodes too for context
238
+ * DPC Fix inclusion syntax to allow #
239
+ * DPC Priorities count up from 1000 not down from 4000 to allow more rules
240
+ * RJ Add new template for titles of schemas, with existing behaviour.
241
+ Override process-schema-title for custom processing of title
242
+
243
+
244
+ Version: 2007-04-04
245
+ * RJ debug mode param
246
+ * RJ alter mixed test to only test mixed branches, so the same document
247
+ could have old and new namespaces schemas in it, but each schema must
248
+ be distinct, just so as not to overconstrain things.
249
+ * KH zero-length include/@href is fatal error, but allow debug mode
250
+ * SB add hint on SAXON and JAXP
251
+ * DC generate-full-path-1 generates XLST1 code by default
252
+ Version: 2007-03-05
253
+ * AS Typo for EXSLT randome, improve comment
254
+ * KH get-schematron-full-path-2 needs to apply to attributes too
255
+ * DP document policy on extensions better
256
+ * DC use copy-of not copy for foreign elements
257
+ * DC add generate-path-2
258
+ * DC don't try to apply templates to attribute axis on attribute nodes, to
259
+ stop SAXON warning.
260
+ * RJ improve reporting of typos
261
+
262
+ Version: 2007-02-08
263
+ * KH Schematron fullpath implementation: @* handled twice and / missing
264
+ * KH Change stylesheetbody from named template to mode to allow implementers more flexibility.
265
+ Move process-ns to outside the stylesheet body.
266
+ * DP, FG, fix handling of xslt:key
267
+ * FG no iso:title/@class
268
+ * Experimental optimization 'visit-no-attributes'
269
+ * KH Experimental added schematron-get-full-path-2 which gives prefixed version for humans
270
+ * DC Move stylesheet/@version generation to after namespace handling
271
+ * DC, FG EXSLT namespace handling code
272
+ * FG add ref and commented code from FG's page on namespaces
273
+ * Start adding normalize-space() to parameter code
274
+ * Add a space between diagnostics
275
+
276
+ Version: 2007-01-22
277
+ * DP change = ($start) to = $start and =($phase) to =$phase
278
+ to run under Saxon 8.8j
279
+ * FG better title section using ( @id | sch:title)[last()]
280
+ * Default query language binding is "xslt" not "xslt1"
281
+
282
+ Version: 2007-01-19
283
+ * Simplify message newline code
284
+ * Remove termination and xpath appending to message options:
285
+ factor out as iso_schematron_terminator.xsl
286
+ * Comment out XSLT2 namespace fix temporarily
287
+
288
+ Version: 2007-01-18 (First beta candidate for comment)
289
+ * DC remove xml:space="preserve"
290
+ * FG improve comment on import statement
291
+ * DC improve comments on invocation section
292
+ * Add exploratory support for sch:schema[@queryBinding='xpath']
293
+ by allowing it and warning as lets are found
294
+ * Be strict about queryBinding spelling errors
295
+ * Extra comments on the different queryBindings
296
+ * KH Add option "message-paths" to generate XPath from output
297
+ * KH Add option "terminate" to halt with an error after the first assertion
298
+ * KH refactor paths in schematron-full-path
299
+ * Improve (?) namespace handling: no dummy attributes for prefix "xsl" generated
300
+
301
+ Version: 2007-01-15
302
+ * FG fix for calling templates
303
+ * Add formal parameters to default templates: may help XSLT 2
304
+ * Fix get-schematron-full-path
305
+ * Include skeleton1-6 is commented out by default
306
+
307
+ Version:2007-01-12 (Pre-beta release to Schematron-love-in maillist)
308
+ * Add many extra parameters to the process-* calls, so that almost
309
+ all the information in the schema can be provided to client programs.
310
+ Also, rearrange the parameters to fit in with the ISO schema, which
311
+ has "rich" and "linkable" attribute groups.
312
+ * Warn on diagnostics with no ID once only
313
+ * Improved path reporting, to handle for namespaces
314
+ * Add process-title dummy template for API
315
+ * Add command-line parameter allow-foreign (true|false) to suppress
316
+ warnings one foreign elements and pass them through to the generated
317
+ stylesheet
318
+ * remove legacy templates for the old ASCC namespace and no namespace,
319
+ and use an import statement instead. Much cleaner now!
320
+ * patterns use @id not @name
321
+ * titles can contain sub-elements
322
+ * start change sch:rule to allow attributes, PIs and comments
323
+ * the default process-* for inline elements add a leading and trailing
324
+ space, to reduce the chance of concatenation.
325
+ * add comments to make the generated code clearer
326
+
327
+ Version:2006-11-07 (ISO: first release private to schematron-love-in maillist for review)
328
+ * Duplicate pattern templates, for handling ISO namespace
329
+ * Add priority onto default and paragraph templates
330
+ * Add namespace checks
331
+ * Handle key in xsl namespace not iso
332
+ * Add include
333
+ * Improve namespace handling
334
+ * Preliminary XSLT2 and EXSLT support
335
+ * Refactor iso:schema for clarity
336
+
337
+ Version: 2003-05-26
338
+ * Fix bug with key
339
+ Version: 2003-04-16
340
+ * handle 1.6 let expressions
341
+ * make key use XSLT names, and allow anywhere
342
+ Version: 2001-06-13
343
+ * same skeleton now supports namespace or no namespace
344
+ * parameters to handlers updated for all 1.5 attributes
345
+ * diagnostic hints supported: command-line option diagnose=yes|no
346
+ * phases supported: command-line option phase=#ALL|...
347
+ * abstract rules
348
+ * compile-time error messages
349
+ * add utility routine generate-id-from-path
350
+
351
+ Contributors: Rick Jelliffe (original), Oliver Becker (architecture, XSLT2),
352
+ Miloslav Nic (diagnostic, phase, options), Ludwig Svenonius (abstract)
353
+ Uche Ogbuji (misc. bug fixes), Jim Ancona (SAXON workaround),
354
+ Francis Norton (generate-id-from-path), Robert Leftwich, Bryan Rasmussen,
355
+ Dave Pawson (include, fallback), Florent Georges (namespaces, exslt, attribute
356
+ context), Benoit Maisonny (attribute context), John Dumps (process-message newline),
357
+ Cliff Stanford (diagnostics and other newlines)
358
+
359
+
360
+ KNOWN TYPICAL LIMITATIONS:
361
+ * Don't use <sch:ns prefix="xsl" .../> with a namespace other than the standard
362
+ XSLT one. This would be a bizarre thing to do anyway.
363
+ * Don't use other prefixes for the XSLT namespace either; some implementations will
364
+ not handle it correctly.
365
+
366
+ EXTENSIONS:
367
+ ISO Schematron is designed as a framework with some standard query language
368
+ bindings. If you need to support other features, please do so safely by making
369
+ up your own @queryLanguage name: this makes it clear that your schema requires
370
+ special features. For example, default ISO Schematron does not support user
371
+ defined functions; so if you want to use the user defined function feature
372
+ in XSLT, you need to have a schema with some queryBinding attribute name like
373
+ "XSLT-with-my-functions" or whatever.
374
+ -->
375
+
376
+
377
+
378
+
379
+ <xsl:stylesheet version="1.0"
380
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
381
+ xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias"
382
+ xmlns:sch="http://www.ascc.net/xml/schematron"
383
+ xmlns:iso="http://purl.oclc.org/dsdl/schematron"
384
+ xmlns:exsl="http://exslt.org/common"
385
+ xmlns:msxsl="urn:schemas-microsoft-com:xslt"
386
+ extension-element-prefixes="exsl msxsl"
387
+ >
388
+ <!-- This program implements ISO Schematron, except for abstract patterns which require a preprocess. -->
389
+
390
+
391
+ <xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>
392
+
393
+
394
+ <!-- Category: top-level-element -->
395
+ <xsl:output method="xml" omit-xml-declaration="no" standalone="yes" indent="yes"/>
396
+
397
+
398
+ <xsl:param name="phase">
399
+ <xsl:choose>
400
+ <xsl:when test="//sch:schema/@defaultPhase">
401
+ <xsl:value-of select="//sch:schema/@defaultPhase"/>
402
+ </xsl:when>
403
+ <xsl:when test="//iso:schema/@defaultPhase">
404
+ <xsl:value-of select="//iso:schema/@defaultPhase"/>
405
+ </xsl:when>
406
+ <xsl:otherwise>#ALL</xsl:otherwise>
407
+ </xsl:choose>
408
+ </xsl:param>
409
+
410
+ <xsl:param name="allow-foreign">false</xsl:param>
411
+
412
+ <xsl:param name="message-newline">true</xsl:param>
413
+
414
+ <!-- DPC set to true if contexts should be checked on attribute nodes
415
+ defaults to true if there is any possibility that a context could match an attribute,
416
+ err on the side if caution, a context of *[.='@'] would cause this param to defualt to true
417
+ even though @ is in a string
418
+ -->
419
+ <xsl:param name="attributes">
420
+ <xsl:choose>
421
+ <xsl:when test="//iso:rule[contains(@context,'@') or contains(@context,'attribute')]">true</xsl:when>
422
+ <xsl:otherwise>false</xsl:otherwise>
423
+ </xsl:choose>
424
+ </xsl:param>
425
+
426
+ <!-- DPC set to true if contexts should be checked on just elements in the child axis
427
+ defaults to true if there is any possibility that a context could match an comment or PI
428
+ err on the side if caution, a context of *[.='('] would cause this param to defualt to true
429
+ even though ( is in a string, but node() comment() and processing-instruction() all have a (
430
+ -->
431
+ <xsl:param name="only-child-elements">
432
+ <xsl:choose>
433
+ <xsl:when test="//iso:rule[contains(@context,'(')]">true</xsl:when>
434
+ <xsl:otherwise>false</xsl:otherwise>
435
+ </xsl:choose>
436
+ </xsl:param>
437
+
438
+ <!-- DPC set to true if contexts should be checked on text nodes nodes (if only-child-elements is false)
439
+ THIS IS NON CONFORMANT BEHAVIOUR JUST FOR DISCUSSION OF A POSSIBLE CHANGE TO THE
440
+ SPECIFICATION. THIS PARAM SHOULD GO IF THE FINAL DECISION IS THAT THE SPEC DOES NOT CHANGE.
441
+ Always defaults to false
442
+ -->
443
+ <xsl:param name="visit-text" select="'false'"/>
444
+
445
+ <!-- DPC
446
+ When selecting contexts the specified behaviour is
447
+ @*|node()[not(self::text())]
448
+ The automatic settings may use
449
+ node()[not(self::text())]
450
+ @*|*
451
+ *
452
+ instead for schema for which they are equivalent.
453
+ If the params are set explictly the above may be used, and also either if
454
+ @*
455
+ @*|node()
456
+ in all cases the result may not be equivalent, for example if you specify no attributes and the schema
457
+ does have attribute contexts they will be silently ignored.
458
+
459
+ after testing it turns out that
460
+ node()[not(self::text())] is slower in saxon than *|comment()|processing-instruction()
461
+ which I find a bit surprising but anyway I'll use the longr faster version.
462
+ -->
463
+ <xsl:variable name="context-xpath">
464
+ <xsl:if test="$attributes='true'">@*|</xsl:if>
465
+ <xsl:choose>
466
+ <xsl:when test="$only-child-elements='true'">*</xsl:when>
467
+ <xsl:when test="$visit-text='true'">node()</xsl:when>
468
+ <xsl:otherwise>*|comment()|processing-instruction()</xsl:otherwise>
469
+ </xsl:choose>
470
+ </xsl:variable>
471
+
472
+ <!-- DPC if this is set to
473
+ '' use recursive templates to iterate over document tree,
474
+ 'key' select all contexts with a key rather than walking the tree explictly in each mode
475
+ '//' select all contexts with // a key rather than walking the tree explictly in each mode (XSLT2 only)
476
+ -->
477
+ <xsl:param name="select-contexts" select="''"/>
478
+
479
+
480
+ <xsl:param name="output-encoding"/>
481
+ <!-- e.g. saxon file.xml file.xsl "sch.exslt.imports=.../string.xsl;.../math.xsl" -->
482
+ <xsl:param name="sch.exslt.imports"/>
483
+
484
+ <!-- Set the language code for messages -->
485
+ <xsl:param name="langCode">default</xsl:param>
486
+
487
+ <xsl:param name="debug">false</xsl:param>
488
+
489
+
490
+ <!-- Set the default for schematron-select-full-path, i.e. the notation for svrl's @location-->
491
+ <xsl:param name="full-path-notation">1</xsl:param>
492
+
493
+ <!-- Simple namespace check -->
494
+ <xsl:template match="/">
495
+ <xsl:if test="//sch:*[ancestor::iso:* or descendant::iso:*]">
496
+ <xsl:message>Schema error: Schematron elements in old and new namespaces found</xsl:message>
497
+ <xsl:if test=" $debug = 'false' " />
498
+ </xsl:if>
499
+
500
+ <xsl:apply-templates />
501
+ </xsl:template>
502
+
503
+
504
+ <!-- ============================================================== -->
505
+ <!-- ISO SCHEMATRON SCHEMA ELEMENT -->
506
+ <!-- Not handled: Abstract patterns. A pre-processor is assumed. -->
507
+ <!-- ============================================================== -->
508
+
509
+ <!-- SCHEMA -->
510
+ <!-- Default uses XSLT 1 -->
511
+ <xsl:template match="iso:schema[not(@queryBinding) or @queryBinding='xslt'
512
+ or @queryBinding='xslt1' or @queryBinding='XSLT' or @queryBinding='XSLT1'
513
+ or @queryBinding='xpath']">
514
+ <xsl:if test="
515
+ @queryBinding='xslt1' or @queryBinding='XSLT' or @queryBinding='XSLT1'">
516
+ <xsl:message>Schema error: in the queryBinding attribute, use 'xslt'</xsl:message>
517
+ </xsl:if>
518
+ <axsl:stylesheet>
519
+ <xsl:apply-templates select="iso:ns"/>
520
+ <!-- Handle the namespaces before the version attribute: reported to help SAXON -->
521
+ <xsl:attribute name="version">1.0</xsl:attribute>
522
+
523
+ <xsl:apply-templates select="." mode="stylesheetbody"/>
524
+ <!-- was xsl:call-template name="stylesheetbody"/ -->
525
+ </axsl:stylesheet>
526
+ </xsl:template>
527
+
528
+ <!-- Using EXSLT with all modeles (except function module: not applicable) -->
529
+ <xsl:template match="iso:schema[@queryBinding='exslt']" priority="10">
530
+ <xsl:comment>This XSLT was automatically generated from a Schematron schema.</xsl:comment>
531
+ <axsl:stylesheet
532
+ xmlns:date="http://exslt.org/dates-and-times"
533
+ xmlns:dyn="http://exslt.org/dynamic"
534
+ xmlns:exsl="http://exslt.org/common"
535
+ xmlns:math="http://exslt.org/math"
536
+ xmlns:random="http://exslt.org/random"
537
+ xmlns:regexp="http://exslt.org/regular-expressions"
538
+ xmlns:set="http://exslt.org/sets"
539
+ xmlns:str="http://exslt.org/strings"
540
+ extension-element-prefixes="date dyn exsl math random regexp set str" >
541
+
542
+ <xsl:apply-templates select="iso:ns"/>
543
+ <!-- Handle the namespaces before the version attribute: reported to help SAXON -->
544
+ <xsl:attribute name="version">1.0</xsl:attribute>
545
+
546
+ <xsl:apply-templates select="." mode="stylesheetbody"/>
547
+ <!-- was xsl:call-template name="stylesheetbody"/ -->
548
+ </axsl:stylesheet>
549
+ </xsl:template>
550
+
551
+
552
+ <!-- Default uses XSLT 1 -->
553
+ <xsl:template match="iso:schema" priority="-1">
554
+ <xsl:message terminate="yes" >Fail: This implementation of ISO Schematron does not work with
555
+ schemas using the "<xsl:value-of select="@queryBinding"/>" query language.</xsl:message>
556
+ </xsl:template>
557
+
558
+ <xsl:template match="*" mode="stylesheetbody">
559
+ <!--xsl:template name="stylesheetbody"-->
560
+ <xsl:comment>Implementers: please note that overriding process-prolog or process-root is
561
+ the preferred method for meta-stylesheets to use where possible. </xsl:comment><xsl:text>&#10;</xsl:text>
562
+
563
+ <!-- These parameters may contain strings with the name and directory of the file being
564
+ validated. For convenience, if the caller only has the information in a single string,
565
+ that string could be put in fileDirParameter. The archives parameters are available
566
+ for ZIP archives.
567
+ -->
568
+
569
+ <axsl:param name="archiveDirParameter" />
570
+ <axsl:param name="archiveNameParameter" />
571
+ <axsl:param name="fileNameParameter" />
572
+ <axsl:param name="fileDirParameter" />
573
+
574
+ <xsl:call-template name="iso:exslt.add.imports" />
575
+ <xsl:text>&#10;&#10;</xsl:text><xsl:comment>PHASES</xsl:comment><xsl:text>&#10;</xsl:text>
576
+ <xsl:call-template name="handle-phase"/>
577
+ <xsl:text>&#10;&#10;</xsl:text><xsl:comment>PROLOG</xsl:comment><xsl:text>&#10;</xsl:text>
578
+ <xsl:call-template name="process-prolog"/>
579
+ <xsl:text>&#10;&#10;</xsl:text><xsl:comment>KEYS</xsl:comment><xsl:text>&#10;</xsl:text>
580
+ <xsl:apply-templates mode="do-keys" select="xsl:key "/>
581
+ <xsl:text>&#10;&#10;</xsl:text><xsl:comment>DEFAULT RULES</xsl:comment><xsl:text>&#10;</xsl:text>
582
+ <xsl:call-template name="generate-default-rules" />
583
+ <xsl:text>&#10;&#10;</xsl:text><xsl:comment>SCHEMA METADATA</xsl:comment><xsl:text>&#10;</xsl:text>
584
+ <xsl:call-template name="handle-root"/>
585
+ <xsl:text>&#10;&#10;</xsl:text><xsl:comment>SCHEMATRON PATTERNS</xsl:comment><xsl:text>&#10;</xsl:text>
586
+
587
+ <xsl:apply-templates select="*[not(self::iso:ns)] " />
588
+ </xsl:template>
589
+
590
+ <xsl:template name="iso:exslt.add.imports">
591
+ <xsl:param name="imports" select="$sch.exslt.imports"/>
592
+ <xsl:choose>
593
+ <xsl:when test="contains($imports, ';')">
594
+ <axsl:import href="{ substring-before($imports, ';') }"/>
595
+ <xsl:call-template name="iso:exslt.add.imports">
596
+ <xsl:with-param name="imports" select="substring-after($imports, ';')"/>
597
+ </xsl:call-template>
598
+ </xsl:when>
599
+ <xsl:when test="$imports">
600
+ <axsl:import href="{ $imports }"/>
601
+ </xsl:when>
602
+ </xsl:choose>
603
+ </xsl:template>
604
+
605
+ <xsl:template name="handle-phase" >
606
+ <xsl:if test="not(normalize-space( $phase ) = '#ALL')">
607
+ <xsl:if test="not(iso:phase[@id = normalize-space( $phase )])">
608
+ <xsl:message>Phase Error: no phase with name <xsl:value-of select="normalize-space( $phase )"
609
+ /> has been defined.</xsl:message>
610
+ </xsl:if>
611
+ </xsl:if>
612
+ </xsl:template>
613
+
614
+ <xsl:template name="generate-default-rules">
615
+ <xsl:text>&#10;&#10;</xsl:text>
616
+ <xsl:comment>MODE: SCHEMATRON-SELECT-FULL-PATH</xsl:comment><xsl:text>&#10;</xsl:text>
617
+ <xsl:comment>This mode can be used to generate an ugly though full XPath for locators</xsl:comment><xsl:text>&#10;</xsl:text>
618
+ <axsl:template match="*" mode="schematron-select-full-path">
619
+ <xsl:choose>
620
+ <xsl:when test=" $full-path-notation = '1' ">
621
+ <!-- Use for computers, but rather unreadable for humans -->
622
+ <axsl:apply-templates select="." mode="schematron-get-full-path"/>
623
+ </xsl:when>
624
+ <xsl:when test=" $full-path-notation = '2' ">
625
+ <!-- Use for humans, but no good for paths unless namespaces are known out-of-band -->
626
+ <axsl:apply-templates select="." mode="schematron-get-full-path-2"/>
627
+ </xsl:when>
628
+ <xsl:when test=" $full-path-notation = '3' ">
629
+ <!-- Obsolescent. Use for humans, but no good for paths unless namespaces are known out-of-band -->
630
+ <axsl:apply-templates select="." mode="schematron-get-full-path-3"/>
631
+ </xsl:when>
632
+
633
+ <xsl:otherwise >
634
+ <!-- Use for computers, but rather unreadable for humans -->
635
+ <axsl:apply-templates select="." mode="schematron-get-full-path"/>
636
+ </xsl:otherwise>
637
+ </xsl:choose>
638
+ </axsl:template>
639
+
640
+
641
+ <xsl:text>&#10;&#10;</xsl:text>
642
+ <xsl:comment>MODE: SCHEMATRON-FULL-PATH</xsl:comment><xsl:text>&#10;</xsl:text>
643
+ <xsl:comment>This mode can be used to generate an ugly though full XPath for locators</xsl:comment><xsl:text>&#10;</xsl:text>
644
+ <axsl:template match="*" mode="schematron-get-full-path">
645
+ <axsl:apply-templates select="parent::*" mode="schematron-get-full-path"/>
646
+
647
+ <!-- XSLT1 syntax -->
648
+
649
+ <axsl:text>/</axsl:text>
650
+ <axsl:choose>
651
+ <axsl:when test="namespace-uri()=''">
652
+ <axsl:value-of select="name()"/>
653
+ <axsl:variable name="p_1" select="1+
654
+ count(preceding-sibling::*[name()=name(current())])" />
655
+ <axsl:if test="$p_1&gt;1 or following-sibling::*[name()=name(current())]">
656
+ <xsl:text/>[<axsl:value-of select="$p_1"/>]<xsl:text/>
657
+ </axsl:if>
658
+ </axsl:when>
659
+ <axsl:otherwise>
660
+ <axsl:text>*[local-name()='</axsl:text>
661
+ <axsl:value-of select="local-name()"/><axsl:text>' and namespace-uri()='</axsl:text>
662
+ <axsl:value-of select="namespace-uri()"/>
663
+ <axsl:text>']</axsl:text>
664
+ <axsl:variable name="p_2" select="1+
665
+ count(preceding-sibling::*[local-name()=local-name(current())])" />
666
+ <axsl:if test="$p_2&gt;1 or following-sibling::*[local-name()=local-name(current())]">
667
+ <xsl:text/>[<axsl:value-of select="$p_2"/>]<xsl:text/>
668
+ </axsl:if>
669
+ </axsl:otherwise>
670
+ </axsl:choose>
671
+ </axsl:template>
672
+
673
+
674
+ <axsl:template match="@*" mode="schematron-get-full-path">
675
+
676
+ <!-- XSLT1 syntax -->
677
+ <axsl:text>/</axsl:text>
678
+ <axsl:choose>
679
+ <axsl:when test="namespace-uri()=''">@<axsl:value-of
680
+ select="name()"/></axsl:when>
681
+ <axsl:otherwise>
682
+ <axsl:text>@*[local-name()='</axsl:text>
683
+ <axsl:value-of select="local-name()"/>
684
+ <axsl:text>' and namespace-uri()='</axsl:text>
685
+ <axsl:value-of select="namespace-uri()"/>
686
+ <axsl:text>']</axsl:text>
687
+ </axsl:otherwise>
688
+ </axsl:choose>
689
+
690
+ </axsl:template>
691
+
692
+
693
+ <xsl:text>&#10;&#10;</xsl:text>
694
+
695
+ <xsl:comment>MODE: SCHEMATRON-FULL-PATH-2</xsl:comment>
696
+ <xsl:text>&#10;</xsl:text>
697
+ <xsl:comment>This mode can be used to generate prefixed XPath for humans</xsl:comment>
698
+ <xsl:text>&#10;</xsl:text>
699
+ <!--simplify the error messages by using the namespace prefixes of the
700
+ instance rather than the generic namespace-uri-styled qualification-->
701
+ <axsl:template match="node() | @*" mode="schematron-get-full-path-2">
702
+ <!--report the element hierarchy-->
703
+ <axsl:for-each select="ancestor-or-self::*">
704
+ <axsl:text>/</axsl:text>
705
+ <axsl:value-of select="name(.)"/>
706
+ <axsl:if test="preceding-sibling::*[name(.)=name(current())]">
707
+ <axsl:text>[</axsl:text>
708
+ <axsl:value-of
709
+ select="count(preceding-sibling::*[name(.)=name(current())])+1"/>
710
+ <axsl:text>]</axsl:text>
711
+ </axsl:if>
712
+ </axsl:for-each>
713
+ <!--report the attribute-->
714
+ <axsl:if test="not(self::*)">
715
+ <axsl:text/>/@<axsl:value-of select="name(.)"/>
716
+ </axsl:if>
717
+ </axsl:template>
718
+
719
+ <xsl:text>&#10;&#10;</xsl:text>
720
+ <xsl:comment>MODE: GENERATE-ID-FROM-PATH </xsl:comment><xsl:text>&#10;</xsl:text>
721
+ <!-- repeatable-id maker derived from Francis Norton's. -->
722
+ <!-- use this if you need generate ids in separate passes,
723
+ because generate-id() is not guaranteed to produce the same
724
+ results each time. These ids are not XML names but closer to paths. -->
725
+ <axsl:template match="/" mode="generate-id-from-path"/>
726
+ <axsl:template match="text()" mode="generate-id-from-path">
727
+ <axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
728
+ <axsl:value-of select="concat('.text-', 1+count(preceding-sibling::text()), '-')"/>
729
+ </axsl:template>
730
+ <axsl:template match="comment()" mode="generate-id-from-path">
731
+ <axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
732
+ <axsl:value-of select="concat('.comment-', 1+count(preceding-sibling::comment()), '-')"/>
733
+ </axsl:template>
734
+ <axsl:template match="processing-instruction()" mode="generate-id-from-path">
735
+ <axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
736
+ <axsl:value-of
737
+ select="concat('.processing-instruction-', 1+count(preceding-sibling::processing-instruction()), '-')"/>
738
+ </axsl:template>
739
+ <axsl:template match="@*" mode="generate-id-from-path">
740
+ <axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
741
+ <axsl:value-of select="concat('.@', name())"/>
742
+ </axsl:template>
743
+ <axsl:template match="*" mode="generate-id-from-path" priority="-0.5">
744
+ <axsl:apply-templates select="parent::*" mode="generate-id-from-path"/>
745
+ <axsl:text>.</axsl:text>
746
+ <!--
747
+ <axsl:choose>
748
+ <axsl:when test="count(. | ../namespace::*) = count(../namespace::*)">
749
+ <axsl:value-of select="concat('.namespace::-',1+count(namespace::*),'-')"/>
750
+ </axsl:when>
751
+ <axsl:otherwise>
752
+ -->
753
+ <axsl:value-of
754
+ select="concat('.',name(),'-',1+count(preceding-sibling::*[name()=name(current())]),'-')"/>
755
+ <!--
756
+ </axsl:otherwise>
757
+ </axsl:choose>
758
+ -->
759
+ </axsl:template>
760
+
761
+
762
+ <xsl:comment>MODE: SCHEMATRON-FULL-PATH-3</xsl:comment>
763
+
764
+ <xsl:text>&#10;</xsl:text>
765
+ <xsl:comment>This mode can be used to generate prefixed XPath for humans
766
+ (Top-level element has index)</xsl:comment>
767
+ <xsl:text>&#10;</xsl:text>
768
+ <!--simplify the error messages by using the namespace prefixes of the
769
+ instance rather than the generic namespace-uri-styled qualification-->
770
+ <axsl:template match="node() | @*" mode="schematron-get-full-path-3">
771
+ <!--report the element hierarchy-->
772
+ <axsl:for-each select="ancestor-or-self::*">
773
+ <axsl:text>/</axsl:text>
774
+ <axsl:value-of select="name(.)"/>
775
+ <axsl:if test="parent::*">
776
+ <axsl:text>[</axsl:text>
777
+ <axsl:value-of
778
+ select="count(preceding-sibling::*[name(.)=name(current())])+1"/>
779
+ <axsl:text>]</axsl:text>
780
+ </axsl:if>
781
+ </axsl:for-each>
782
+ <!--report the attribute-->
783
+ <axsl:if test="not(self::*)">
784
+ <axsl:text/>/@<axsl:value-of select="name(.)"/>
785
+ </axsl:if>
786
+ </axsl:template>
787
+
788
+ <xsl:text>&#10;&#10;</xsl:text>
789
+ <xsl:comment>MODE: GENERATE-ID-2 </xsl:comment><xsl:text>&#10;</xsl:text>
790
+ <!-- repeatable-id maker from David Carlisle. -->
791
+ <!-- use this if you need generate IDs in separate passes,
792
+ because generate-id() is not guaranteed to produce the same
793
+ results each time. These IDs are well-formed XML NMTOKENS -->
794
+ <axsl:template match="/" mode="generate-id-2">U</axsl:template>
795
+
796
+ <axsl:template match="*" mode="generate-id-2" priority="2">
797
+ <axsl:text>U</axsl:text>
798
+ <axsl:number level="multiple" count="*"/>
799
+ </axsl:template>
800
+
801
+ <axsl:template match="node()" mode="generate-id-2">
802
+ <axsl:text>U.</axsl:text>
803
+ <axsl:number level="multiple" count="*"/>
804
+ <axsl:text>n</axsl:text>
805
+ <axsl:number count="node()"/>
806
+ </axsl:template>
807
+
808
+ <axsl:template match="@*" mode="generate-id-2">
809
+ <axsl:text>U.</axsl:text>
810
+ <axsl:number level="multiple" count="*"/>
811
+ <axsl:text>_</axsl:text>
812
+ <axsl:value-of select="string-length(local-name(.))"/>
813
+ <axsl:text>_</axsl:text>
814
+ <axsl:value-of select="translate(name(),':','.')"/>
815
+ </axsl:template>
816
+
817
+
818
+ <xsl:comment>Strip characters</xsl:comment>
819
+ <axsl:template match="text()" priority="-1" />
820
+
821
+ </xsl:template>
822
+
823
+ <xsl:template name="handle-root">
824
+ <!-- Process the top-level element -->
825
+ <axsl:template match="/">
826
+ <xsl:call-template name="process-root">
827
+ <xsl:with-param
828
+ name="title" select="(@id | iso:title)[last()]"/>
829
+ <xsl:with-param name="version" select="'iso'" />
830
+ <xsl:with-param name="schemaVersion" select="@schemaVersion" />
831
+ <xsl:with-param name="queryBinding" select="@queryBinding" />
832
+ <xsl:with-param name="contents">
833
+ <xsl:apply-templates mode="do-all-patterns"/>
834
+ </xsl:with-param>
835
+
836
+ <!-- "Rich" properties -->
837
+ <xsl:with-param name="fpi" select="@fpi"/>
838
+ <xsl:with-param name="icon" select="@icon"/>
839
+ <xsl:with-param name="id" select="@id"/>
840
+ <xsl:with-param name="lang" select="@xml:lang"/>
841
+ <xsl:with-param name="see" select="@see" />
842
+ <xsl:with-param name="space" select="@xml:space" />
843
+
844
+
845
+ <!-- Non-standard extensions not part of the API yet -->
846
+ <xsl:with-param name="action" select="@action" />
847
+ </xsl:call-template>
848
+ </axsl:template>
849
+
850
+
851
+ </xsl:template>
852
+
853
+ <!-- ============================================================== -->
854
+ <!-- ISO SCHEMATRON ELEMENTS -->
855
+ <!-- ============================================================== -->
856
+
857
+ <!-- ISO ACTIVE -->
858
+ <xsl:template match="iso:active">
859
+ <xsl:if test="not(@pattern)">
860
+ <xsl:message>Markup Error: no pattern attribute in &lt;active></xsl:message>
861
+ </xsl:if>
862
+
863
+ <xsl:if test="not(../../iso:pattern[@id = current()/@pattern])
864
+ and not(../../iso:include)">
865
+ <xsl:message>Reference Error: the pattern "<xsl:value-of select="@pattern"
866
+ />" has been activated but is not declared</xsl:message>
867
+ </xsl:if>
868
+ </xsl:template>
869
+
870
+ <!-- ISO ASSERT and REPORT -->
871
+ <xsl:template match="iso:assert">
872
+
873
+ <xsl:if test="not(@test)">
874
+ <xsl:message>Markup Error: no test attribute in &lt;assert</xsl:message>
875
+ </xsl:if>
876
+ <xsl:text>&#10;&#10; </xsl:text>
877
+ <xsl:comment>ASSERT <xsl:value-of select="@role" /> </xsl:comment><xsl:text>&#10;</xsl:text>
878
+
879
+ <axsl:choose>
880
+ <axsl:when test="{@test}"/>
881
+ <axsl:otherwise>
882
+ <xsl:call-template name="process-assert">
883
+ <xsl:with-param name="test" select="normalize-space(@test)" />
884
+ <xsl:with-param name="diagnostics" select="@diagnostics"/>
885
+ <xsl:with-param name="flag" select="@flag"/>
886
+
887
+ <!-- "Rich" properties -->
888
+ <xsl:with-param name="fpi" select="@fpi"/>
889
+ <xsl:with-param name="icon" select="@icon"/>
890
+ <xsl:with-param name="id" select="@id"/>
891
+ <xsl:with-param name="lang" select="@xml:lang"/>
892
+ <xsl:with-param name="see" select="@see" />
893
+ <xsl:with-param name="space" select="@xml:space" />
894
+
895
+ <!-- "Linking" properties -->
896
+ <xsl:with-param name="role" select="@role" />
897
+ <xsl:with-param name="subject" select="@subject" />
898
+ </xsl:call-template>
899
+
900
+ </axsl:otherwise>
901
+ </axsl:choose>
902
+ </xsl:template>
903
+ <xsl:template match="iso:report">
904
+
905
+ <xsl:if test="not(@test)">
906
+ <xsl:message>Markup Error: no test attribute in &lt;report></xsl:message>
907
+ </xsl:if>
908
+
909
+ <xsl:text>&#10;&#10; </xsl:text>
910
+ <xsl:comment>REPORT <xsl:value-of select="@role" /> </xsl:comment><xsl:text>&#10;</xsl:text>
911
+
912
+ <axsl:if test="{@test}">
913
+
914
+ <xsl:call-template name="process-report">
915
+ <xsl:with-param name="test" select="normalize-space(@test)" />
916
+ <xsl:with-param name="diagnostics" select="@diagnostics"/>
917
+ <xsl:with-param name="flag" select="@flag"/>
918
+
919
+ <!-- "Rich" properties -->
920
+ <xsl:with-param name="fpi" select="@fpi"/>
921
+ <xsl:with-param name="icon" select="@icon"/>
922
+ <xsl:with-param name="id" select="@id"/>
923
+ <xsl:with-param name="lang" select="@xml:lang"/>
924
+ <xsl:with-param name="see" select="@see" />
925
+ <xsl:with-param name="space" select="@xml:space" />
926
+
927
+ <!-- "Linking" properties -->
928
+ <xsl:with-param name="role" select="@role" />
929
+ <xsl:with-param name="subject" select="@subject" />
930
+ </xsl:call-template>
931
+
932
+ </axsl:if>
933
+ </xsl:template>
934
+
935
+
936
+ <!-- ISO DIAGNOSTIC -->
937
+ <!-- We use a mode here to maintain backwards compatability, instead of adding it
938
+ to the other mode.
939
+ -->
940
+ <xsl:template match="iso:diagnostic" mode="check-diagnostics">
941
+ <xsl:if test="not(@id)">
942
+ <xsl:message>Markup Error: no id attribute in &lt;diagnostic></xsl:message>
943
+ </xsl:if>
944
+ </xsl:template>
945
+
946
+ <xsl:template match="iso:diagnostic" >
947
+ <xsl:call-template name="process-diagnostic">
948
+
949
+ <!-- "Rich" properties -->
950
+ <xsl:with-param name="fpi" select="@fpi"/>
951
+ <xsl:with-param name="icon" select="@icon"/>
952
+ <xsl:with-param name="id" select="@id"/>
953
+ <xsl:with-param name="lang" select="@xml:lang"/>
954
+ <xsl:with-param name="see" select="@see" />
955
+ <xsl:with-param name="space" select="@xml:space" />
956
+ </xsl:call-template>
957
+ </xsl:template>
958
+
959
+ <!-- ISO DIAGNOSTICS -->
960
+ <xsl:template match="iso:diagnostics" >
961
+ <xsl:apply-templates mode="check-diagnostics" select="*" />
962
+ </xsl:template>
963
+
964
+ <!-- ISO DIR -->
965
+ <xsl:template match="iso:dir" mode="text" >
966
+ <xsl:call-template name="process-dir">
967
+ <xsl:with-param name="value" select="@value"/>
968
+ </xsl:call-template>
969
+ </xsl:template>
970
+
971
+ <!-- ISO EMPH -->
972
+ <xsl:template match="iso:emph" mode="text">
973
+
974
+ <xsl:call-template name="process-emph"/>
975
+
976
+ </xsl:template>
977
+
978
+ <!-- ISO EXTENDS -->
979
+ <xsl:template match="iso:extends">
980
+ <xsl:if test="not(@rule)">
981
+ <xsl:message>Markup Error: no rule attribute in &lt;extends></xsl:message>
982
+ </xsl:if>
983
+ <xsl:if test="not(//iso:rule[@abstract='true'][@id= current()/@rule] )">
984
+ <xsl:message>Reference Error: the abstract rule "<xsl:value-of select="@rule"
985
+ />" has been referenced but is not declared</xsl:message>
986
+ </xsl:if>
987
+ <xsl:call-template name="IamEmpty" />
988
+
989
+ <xsl:if test="//iso:rule[@id=current()/@rule]">
990
+ <xsl:apply-templates select="//iso:rule[@id=current()/@rule]"
991
+ mode="extends"/>
992
+ </xsl:if>
993
+
994
+ </xsl:template>
995
+
996
+ <!-- KEY: ISO has no KEY -->
997
+ <!-- NOTE:
998
+ Key has had a checkered history. Schematron 1.0 allowed it in certain places, but
999
+ users came up with a different location, which has now been adopted.
1000
+
1001
+ XT, the early XSLT processor, did not implement key and died when it was present.
1002
+ So there are some versions of the Schematron skeleton for XT that strip out all
1003
+ key elements.
1004
+
1005
+ Xalan (e.g. Xalan4C 1.0 and a Xalan4J) also had a funny. A fix involved making
1006
+ a top-level parameter called $hiddenKey and then using that instead of matching
1007
+ "key". This has been removed.
1008
+ -->
1009
+ <xsl:template match="xsl:key" mode="do-keys" >
1010
+ <xsl:if test="not(@name)">
1011
+ <xsl:message>Markup Error: no name attribute in &lt;key></xsl:message>
1012
+ </xsl:if>
1013
+ <xsl:if test="not(@path) and not(@use)">
1014
+ <xsl:message>Markup Error: no path or use attribute in &lt;key></xsl:message>
1015
+ </xsl:if>
1016
+ <xsl:choose>
1017
+ <xsl:when test="parent::iso:rule ">
1018
+ <xsl:call-template name="IamEmpty" />
1019
+ <xsl:choose>
1020
+ <xsl:when test="@path">
1021
+ <axsl:key match="{../@context}" name="{@name}" use="{@path}"/>
1022
+ </xsl:when>
1023
+ <xsl:otherwise>
1024
+ <axsl:key match="{../@context}" name="{@name}" use="{@use}"/>
1025
+ </xsl:otherwise>
1026
+ </xsl:choose>
1027
+ </xsl:when>
1028
+ <xsl:otherwise>
1029
+ <xsl:if test="not(@match) ">
1030
+ <xsl:message>Markup Error: no path or use attribute in &lt;key></xsl:message>
1031
+ </xsl:if>
1032
+ <axsl:key>
1033
+ <xsl:copy-of select="@*"/>
1034
+ </axsl:key>
1035
+ </xsl:otherwise>
1036
+ </xsl:choose>
1037
+ </xsl:template>
1038
+
1039
+ <xsl:template match="xsl:key " /><!-- swallow -->
1040
+
1041
+ <xsl:template match="iso:key " >
1042
+ <xsl:message>Schema error: The key element is not in the ISO Schematron namespace. Use the XSLT namespace.</xsl:message>
1043
+ </xsl:template>
1044
+
1045
+ <!-- ISO INCLUDE -->
1046
+ <!-- This is only a fallback. Include really needs to have been done before this as a separate pass.-->
1047
+
1048
+ <xsl:template match="iso:include[not(normalize-space(@href))]"
1049
+ priority="1">
1050
+ <xsl:if test=" $debug = 'false' ">
1051
+ <xsl:message terminate="yes">Schema error: Empty href= attribute for include directive.</xsl:message>
1052
+ </xsl:if>
1053
+
1054
+ </xsl:template>
1055
+
1056
+ <!-- Extend the URI syntax to allow # refererences -->
1057
+ <!-- Add experimental support for simple containers like /xxx:xxx/iso:pattern to allow better includes -->
1058
+ <xsl:template match="iso:include">
1059
+ <xsl:variable name="document-uri" select="substring-before(concat(@href,'#'), '#')"/>
1060
+ <xsl:variable name="fragment-id" select="substring-after(@href, '#')"/>
1061
+
1062
+ <xsl:choose>
1063
+
1064
+ <xsl:when test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0" >
1065
+ <xsl:message>Error: Impossible URL in Schematron include</xsl:message>
1066
+ </xsl:when>
1067
+
1068
+ <xsl:when test="string-length( $fragment-id ) &gt; 0">
1069
+ <xsl:variable name="theDocument_1" select="document( $document-uri,/ )" />
1070
+ <xsl:variable name="theFragment_1" select="$theDocument_1//iso:*[@id= $fragment-id ]" />
1071
+ <xsl:if test=" $theFragment_1/self::iso:schema ">
1072
+ <xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
1073
+ </xsl:if>
1074
+ <xsl:apply-templates select=" $theFragment_1"/>
1075
+ </xsl:when>
1076
+
1077
+ <xsl:otherwise>
1078
+ <xsl:variable name="theDocument_2" select="document( $document-uri,/ )" />
1079
+ <xsl:variable name="theFragment_2" select="$theDocument_2/iso:*" />
1080
+ <xsl:variable name="theContainedFragments" select="$theDocument_2/*/iso:*" />
1081
+ <xsl:if test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
1082
+ <xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
1083
+ </xsl:if>
1084
+ <xsl:apply-templates select="$theFragment_2 | $theContainedFragments "/>
1085
+ </xsl:otherwise>
1086
+ </xsl:choose>
1087
+ </xsl:template>
1088
+
1089
+ <!-- This is to handle the particular case of including patterns -->
1090
+ <xsl:template match="iso:include" mode="do-all-patterns">
1091
+ <xsl:variable name="document-uri" select="substring-before(concat(@href,'#'), '#')"/>
1092
+ <xsl:variable name="fragment-id" select="substring-after(@href, '#')"/>
1093
+
1094
+ <xsl:choose>
1095
+
1096
+ <xsl:when test="string-length( $document-uri ) = 0 and string-length( $fragment-id ) = 0" >
1097
+ <xsl:message>Error: Impossible URL in Schematron include</xsl:message>
1098
+ </xsl:when>
1099
+
1100
+ <xsl:when test="string-length( $fragment-id ) &gt; 0">
1101
+ <xsl:variable name="theDocument_1" select="document( $document-uri,/ )" />
1102
+ <xsl:variable name="theFragment_1" select="$theDocument_1//iso:*[@id= $fragment-id ]" />
1103
+ <xsl:if test=" $theFragment_1/self::iso:schema ">
1104
+ <xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
1105
+ </xsl:if>
1106
+ <xsl:apply-templates select=" $theFragment_1" mode="do-all-patterns"/>
1107
+ </xsl:when>
1108
+
1109
+ <xsl:otherwise>
1110
+ <!-- Import the top-level element if it is in schematron namespace,
1111
+ or its children otherwise, to allow a simple containment mechanism. -->
1112
+ <xsl:variable name="theDocument_2" select="document( $document-uri,/ )" />
1113
+ <xsl:variable name="theFragment_2" select="$theDocument_2/iso:*" />
1114
+ <xsl:variable name="theContainedFragments" select="$theDocument_2/*/iso:*" />
1115
+ <xsl:if test=" $theFragment_2/self::iso:schema or $theContainedFragments/self::iso:schema">
1116
+ <xsl:message>Schema error: Use include to include fragments, not a whole schema</xsl:message>
1117
+ </xsl:if>
1118
+ <xsl:apply-templates select="$theFragment_2 | $theContainedFragments "
1119
+ mode="do-all-patterns" />
1120
+ </xsl:otherwise>
1121
+ </xsl:choose>
1122
+ </xsl:template>
1123
+
1124
+ <!-- ISO LET -->
1125
+ <xsl:template match="iso:let" >
1126
+ <xsl:if test="ancestor::iso:schema[@queryBinding='xpath']">
1127
+ <xsl:message>Warning: Variables should not be used with the "xpath" query language binding.</xsl:message>
1128
+ </xsl:if>
1129
+
1130
+ <!-- lets at the top-level are implemented as parameters -->
1131
+
1132
+ <xsl:choose>
1133
+ <xsl:when test="parent::iso:schema">
1134
+ <!-- it is an error to have an empty param/@select because an XPath is expected -->
1135
+ <axsl:param name="{@name}" select="{@value}">
1136
+ <xsl:if test="string-length(@value) &gt; 0">
1137
+ <xsl:attribute name="select"><xsl:value-of select="@value"/></xsl:attribute>
1138
+ </xsl:if>
1139
+ </axsl:param>
1140
+ </xsl:when>
1141
+ <xsl:otherwise>
1142
+ <axsl:variable name="{@name}" select="{@value}"/>
1143
+ </xsl:otherwise>
1144
+ </xsl:choose>
1145
+
1146
+ </xsl:template>
1147
+
1148
+ <!-- ISO NAME -->
1149
+ <xsl:template match="iso:name" mode="text">
1150
+
1151
+ <xsl:if test="@path">
1152
+ <xsl:call-template name="process-name">
1153
+ <xsl:with-param name="name" select="concat('name(',@path,')')"/>
1154
+ </xsl:call-template>
1155
+ </xsl:if>
1156
+ <xsl:if test="not(@path)">
1157
+ <xsl:call-template name="process-name">
1158
+ <xsl:with-param name="name" select="'name(.)'"/>
1159
+ </xsl:call-template>
1160
+ </xsl:if>
1161
+ <xsl:call-template name="IamEmpty" />
1162
+ </xsl:template>
1163
+
1164
+ <!-- ISO NS -->
1165
+ <!-- Namespace handling is XSLT is quite tricky and implementation dependent -->
1166
+ <xsl:template match="iso:ns">
1167
+ <xsl:call-template name="handle-namespace" />
1168
+ </xsl:template>
1169
+
1170
+ <!-- This template is just to provide the API hook -->
1171
+ <xsl:template match="iso:ns" mode="do-all-patterns" >
1172
+ <xsl:if test="not(@uri)">
1173
+ <xsl:message>Markup Error: no uri attribute in &lt;ns></xsl:message>
1174
+ </xsl:if>
1175
+ <xsl:if test="not(@prefix)">
1176
+ <xsl:message>Markup Error: no prefix attribute in &lt;ns></xsl:message>
1177
+ </xsl:if>
1178
+ <xsl:call-template name="IamEmpty" />
1179
+ <xsl:call-template name="process-ns" >
1180
+ <xsl:with-param name="prefix" select="@prefix"/>
1181
+ <xsl:with-param name="uri" select="@uri"/>
1182
+ </xsl:call-template>
1183
+ </xsl:template>
1184
+
1185
+ <!-- ISO P -->
1186
+ <xsl:template match="iso:schema/iso:p " mode="do-schema-p" >
1187
+ <xsl:call-template name="process-p">
1188
+ <xsl:with-param name="class" select="@class"/>
1189
+ <xsl:with-param name="icon" select="@icon"/>
1190
+ <xsl:with-param name="id" select="@id"/>
1191
+ <xsl:with-param name="lang" select="@xml:lang"/>
1192
+ </xsl:call-template>
1193
+ </xsl:template>
1194
+ <xsl:template match="iso:pattern/iso:p " mode="do-pattern-p" >
1195
+ <xsl:call-template name="process-p">
1196
+ <xsl:with-param name="class" select="@class"/>
1197
+ <xsl:with-param name="icon" select="@icon"/>
1198
+ <xsl:with-param name="id" select="@id"/>
1199
+ <xsl:with-param name="lang" select="@xml:lang"/>
1200
+ </xsl:call-template>
1201
+ </xsl:template>
1202
+
1203
+ <!-- Currently, iso:p in other position are not passed through to the API -->
1204
+ <xsl:template match="iso:phase/iso:p" />
1205
+ <xsl:template match="iso:p " priority="-1" />
1206
+
1207
+ <!-- ISO PATTERN -->
1208
+ <xsl:template match="iso:pattern" mode="do-all-patterns">
1209
+ <xsl:if test="($phase = '#ALL')
1210
+ or (../iso:phase[@id= $phase]/iso:active[@pattern= current()/@id])">
1211
+ <xsl:call-template name="process-pattern">
1212
+ <!-- the following select statement assumes that
1213
+ @id | sch:title returns node-set in document order:
1214
+ we want the title if it is there, otherwise the @id attribute -->
1215
+ <xsl:with-param name="name" select="(@id | iso:title )[last()]"/>
1216
+ <xsl:with-param name="is-a" select="''"/>
1217
+
1218
+ <!-- "Rich" properties -->
1219
+ <xsl:with-param name="fpi" select="@fpi"/>
1220
+ <xsl:with-param name="icon" select="@icon"/>
1221
+ <xsl:with-param name="id" select="@id"/>
1222
+ <xsl:with-param name="lang" select="@xml:lang"/>
1223
+ <xsl:with-param name="see" select="@see" />
1224
+ <xsl:with-param name="space" select="@xml:space" />
1225
+ </xsl:call-template>
1226
+ <xsl:choose>
1227
+ <xsl:when test="$select-contexts='key'">
1228
+ <axsl:apply-templates select="key('M','M{count(preceding-sibling::*)}')" mode="M{count(preceding-sibling::*)}"/>
1229
+ </xsl:when>
1230
+ <xsl:when test="$select-contexts='//'">
1231
+ <axsl:apply-templates mode="M{count(preceding-sibling::*)}">
1232
+ <xsl:attribute name="select">
1233
+ <xsl:text>//(</xsl:text>
1234
+ <xsl:for-each select="iso:rule/@context">
1235
+ <xsl:text>(</xsl:text>
1236
+ <xsl:value-of select="."/>
1237
+ <xsl:text>)</xsl:text>
1238
+ <xsl:if test="position()!=last()">|</xsl:if>
1239
+ </xsl:for-each>
1240
+ <xsl:text>)</xsl:text>
1241
+ <xsl:if test="$visit-text='false'">[not(self::text())]</xsl:if>
1242
+ </xsl:attribute>
1243
+ </axsl:apply-templates>
1244
+ </xsl:when>
1245
+ <xsl:otherwise>
1246
+ <axsl:apply-templates select="/" mode="M{count(preceding-sibling::*)}"/>
1247
+ </xsl:otherwise>
1248
+ </xsl:choose>
1249
+ </xsl:if>
1250
+ </xsl:template>
1251
+
1252
+ <xsl:template match="iso:pattern[@abstract='true']">
1253
+
1254
+ <xsl:message>Schema implementation error: This schema has abstract patterns, yet they are supposed to be preprocessed out already
1255
+ </xsl:message>
1256
+ </xsl:template>
1257
+
1258
+ <!-- Here is the template for the normal case of patterns -->
1259
+ <xsl:template match="iso:pattern[not(@abstract='true')]">
1260
+
1261
+ <xsl:if test="($phase = '#ALL')
1262
+ or (../iso:phase[@id= $phase]/iso:active[@pattern= current()/@id])">
1263
+
1264
+ <xsl:text>&#10;&#10;</xsl:text>
1265
+ <xsl:comment>PATTERN <xsl:value-of select="@id" /> <xsl:value-of select="iso:title" /> </xsl:comment><xsl:text>&#10;</xsl:text>
1266
+ <xsl:apply-templates />
1267
+
1268
+ <!-- DPC select-contexts test -->
1269
+ <xsl:if test="not($select-contexts)">
1270
+ <axsl:template match="text()" priority="-1" mode="M{count(preceding-sibling::*)}">
1271
+ <!-- strip characters -->
1272
+ </axsl:template>
1273
+
1274
+ <!-- DPC introduce context-xpath variable -->
1275
+ <axsl:template match="@*|node()"
1276
+ priority="-2"
1277
+ mode="M{ count(preceding-sibling::*) }">
1278
+ <axsl:apply-templates select="{$context-xpath}" mode="M{count(preceding-sibling::*)}"/>
1279
+ </axsl:template>
1280
+ </xsl:if>
1281
+ </xsl:if>
1282
+ </xsl:template>
1283
+
1284
+ <!-- ISO PHASE -->
1285
+ <xsl:template match="iso:phase" >
1286
+ <xsl:if test="not(@id)">
1287
+ <xsl:message>Markup Error: no id attribute in &lt;phase></xsl:message>
1288
+ </xsl:if>
1289
+ <xsl:apply-templates/>
1290
+ </xsl:template>
1291
+
1292
+ <!-- ISO RULE -->
1293
+ <xsl:template match="iso:rule[not(@abstract='true')] ">
1294
+ <xsl:if test="not(@context)">
1295
+ <xsl:message>Markup Error: no context attribute in &lt;rule></xsl:message>
1296
+ </xsl:if>
1297
+ <xsl:text>&#10;&#10; </xsl:text>
1298
+ <xsl:comment>RULE <xsl:value-of select="@id" /> </xsl:comment><xsl:text>&#10;</xsl:text>
1299
+ <xsl:if test="iso:title">
1300
+ <xsl:comment><xsl:value-of select="iso:title" /></xsl:comment>
1301
+ </xsl:if>
1302
+ <!-- DPC select-contexts -->
1303
+ <xsl:if test="$select-contexts='key'">
1304
+ <axsl:key name="M"
1305
+ match="{@context}"
1306
+ use="'M{count(../preceding-sibling::*)}'"/>
1307
+ </xsl:if>
1308
+
1309
+
1310
+ <!-- DPC priorities count up from 1000 not down from 4000 (templates in same priority order as before) -->
1311
+ <axsl:template match="{@context}"
1312
+ priority="{1000 + count(following-sibling::*)}" mode="M{count(../preceding-sibling::*)}">
1313
+ <xsl:call-template name="process-rule">
1314
+ <xsl:with-param name="context" select="@context"/>
1315
+
1316
+ <!-- "Rich" properties -->
1317
+ <xsl:with-param name="fpi" select="@fpi"/>
1318
+ <xsl:with-param name="icon" select="@icon"/>
1319
+ <xsl:with-param name="id" select="@id"/>
1320
+ <xsl:with-param name="lang" select="@xml:lang"/>
1321
+ <xsl:with-param name="see" select="@see" />
1322
+ <xsl:with-param name="space" select="@xml:space" />
1323
+
1324
+ <!-- "Linking" properties -->
1325
+ <xsl:with-param name="role" select="@role" />
1326
+ <xsl:with-param name="subject" select="@subject" />
1327
+ </xsl:call-template>
1328
+ <xsl:apply-templates/>
1329
+ <!-- DPC introduce context-xpath and select-contexts variables -->
1330
+ <xsl:if test="not($select-contexts)">
1331
+ <axsl:apply-templates select="{$context-xpath}" mode="M{count(../preceding-sibling::*)}"/>
1332
+ </xsl:if>
1333
+ </axsl:template>
1334
+ </xsl:template>
1335
+
1336
+
1337
+ <!-- ISO ABSTRACT RULE -->
1338
+ <xsl:template match="iso:rule[@abstract='true'] " >
1339
+ <xsl:if test=" not(@id)">
1340
+ <xsl:message>Markup Error: no id attribute on abstract &lt;rule></xsl:message>
1341
+ </xsl:if>
1342
+ <xsl:if test="@context">
1343
+ <xsl:message>Markup Error: (2) context attribute on abstract &lt;rule></xsl:message>
1344
+ </xsl:if>
1345
+ </xsl:template>
1346
+
1347
+ <xsl:template match="iso:rule[@abstract='true']"
1348
+ mode="extends" >
1349
+ <xsl:if test="@context">
1350
+ <xsl:message>Markup Error: context attribute on abstract &lt;rule></xsl:message>
1351
+ </xsl:if>
1352
+ <xsl:apply-templates/>
1353
+ </xsl:template>
1354
+
1355
+ <!-- ISO SPAN -->
1356
+ <xsl:template match="iso:span" mode="text">
1357
+ <xsl:call-template name="process-span">
1358
+ <xsl:with-param name="class" select="@class"/>
1359
+ </xsl:call-template>
1360
+ </xsl:template>
1361
+
1362
+ <!-- ISO TITLE -->
1363
+
1364
+ <xsl:template match="iso:schema/iso:title" priority="1">
1365
+ <xsl:call-template name="process-schema-title" />
1366
+ </xsl:template>
1367
+
1368
+
1369
+ <xsl:template match="iso:title" >
1370
+ <xsl:call-template name="process-title" />
1371
+ </xsl:template>
1372
+
1373
+
1374
+ <!-- ISO VALUE-OF -->
1375
+ <xsl:template match="iso:value-of" mode="text" >
1376
+ <xsl:if test="not(@select)">
1377
+ <xsl:message>Markup Error: no select attribute in &lt;value-of></xsl:message>
1378
+ </xsl:if>
1379
+ <xsl:call-template name="IamEmpty" />
1380
+
1381
+ <xsl:choose>
1382
+ <xsl:when test="@select">
1383
+ <xsl:call-template name="process-value-of">
1384
+ <xsl:with-param name="select" select="@select"/>
1385
+ </xsl:call-template>
1386
+ </xsl:when>
1387
+ <xsl:otherwise >
1388
+ <xsl:call-template name="process-value-of">
1389
+ <xsl:with-param name="select" select="'.'"/>
1390
+ </xsl:call-template>
1391
+ </xsl:otherwise>
1392
+ </xsl:choose>
1393
+
1394
+ </xsl:template>
1395
+
1396
+
1397
+ <!-- ============================================================== -->
1398
+ <!-- DEFAULT TEXT HANDLING -->
1399
+ <!-- ============================================================== -->
1400
+ <xsl:template match="text()" priority="-1" mode="do-keys">
1401
+ <!-- strip characters -->
1402
+ </xsl:template>
1403
+ <xsl:template match="text()" priority="-1" mode="do-all-patterns">
1404
+ <!-- strip characters -->
1405
+ </xsl:template>
1406
+ <xsl:template match="text()" priority="-1" mode="do-schema-p">
1407
+ <!-- strip characters -->
1408
+ </xsl:template>
1409
+ <xsl:template match="text()" priority="-1" mode="do-pattern-p">
1410
+ <!-- strip characters -->
1411
+ </xsl:template>
1412
+
1413
+ <xsl:template match="text()" priority="-1">
1414
+ <!-- Strip characters -->
1415
+ </xsl:template>
1416
+
1417
+ <xsl:template match="text()" mode="text">
1418
+ <xsl:value-of select="."/>
1419
+ </xsl:template>
1420
+
1421
+ <xsl:template match="text()" mode="inline-text">
1422
+ <xsl:value-of select="."/>
1423
+ </xsl:template>
1424
+
1425
+ <!-- ============================================================== -->
1426
+ <!-- UTILITY TEMPLATES -->
1427
+ <!-- ============================================================== -->
1428
+ <xsl:template name="IamEmpty">
1429
+ <xsl:if test="count( * )">
1430
+ <xsl:message>
1431
+ <xsl:text>Warning: </xsl:text>
1432
+ <xsl:value-of select="name(.)"/>
1433
+ <xsl:text> must not contain any child elements</xsl:text>
1434
+ </xsl:message>
1435
+ </xsl:if>
1436
+ </xsl:template>
1437
+
1438
+ <xsl:template name="diagnosticsSplit">
1439
+ <!-- Process at the current point the first of the <diagnostic> elements
1440
+ referred to parameter str, and then recurse -->
1441
+ <xsl:param name="str"/>
1442
+ <xsl:variable name="start">
1443
+ <xsl:choose>
1444
+ <xsl:when test="contains($str,' ')">
1445
+ <xsl:value-of select="substring-before($str,' ')"/>
1446
+ </xsl:when>
1447
+ <xsl:otherwise><xsl:value-of select="$str"/></xsl:otherwise>
1448
+ </xsl:choose>
1449
+ </xsl:variable>
1450
+
1451
+ <xsl:variable name="end">
1452
+ <xsl:if test="contains($str,' ')">
1453
+ <xsl:value-of select="substring-after($str,' ')"/>
1454
+ </xsl:if>
1455
+ </xsl:variable>
1456
+
1457
+ <!-- This works with all namespaces -->
1458
+ <xsl:if test="not(string-length(normalize-space($start)) = 0)
1459
+ and not(//iso:diagnostic[@id = $start])
1460
+ and not(//sch:diagnostic[@id = $start])
1461
+ and not(//diagnostic[@id = $start])">
1462
+ <xsl:message>Reference error: A diagnostic "<xsl:value-of select="string($start)"
1463
+ />" has been referenced but is not declared</xsl:message>
1464
+ </xsl:if>
1465
+
1466
+ <xsl:if test="string-length(normalize-space($start)) > 0">
1467
+ <xsl:text> </xsl:text>
1468
+ <xsl:apply-templates
1469
+ select="//iso:diagnostic[@id = $start ]
1470
+ | //sch:diagnostic[@id = $start ]
1471
+ | //diagnostic[@id= $start ]"/>
1472
+ </xsl:if>
1473
+
1474
+ <xsl:if test="not($end='')">
1475
+ <xsl:call-template name="diagnosticsSplit">
1476
+ <xsl:with-param name="str" select="$end"/>
1477
+ </xsl:call-template>
1478
+ </xsl:if>
1479
+ </xsl:template>
1480
+
1481
+ <!-- It would be nice to use this but xsl:namespace does not
1482
+ allow a fallback -->
1483
+ <!--xsl:template name="handle-namespace" version="2.0">
1484
+ <xsl:namespace name="{@prefix}" select="@uri">
1485
+ </xsl:template-->
1486
+
1487
+ <xsl:template name="handle-namespace">
1488
+ <!-- experimental code from http://eccnet.eccnet.com/pipermail/schematron-love-in/2006-June/000104.html -->
1489
+ <!-- Handle namespaces differently for exslt systems, msxml, and default, only using XSLT1 syntax -->
1490
+ <!-- For more info see http://fgeorges.blogspot.com/2007/01/creating-namespace-nodes-in-xslt-10.html -->
1491
+ <xsl:choose>
1492
+ <!-- The following code works for XSLT1 -->
1493
+ <xsl:when test="function-available('exsl:node-set')">
1494
+ <xsl:variable name="ns-dummy-elements">
1495
+ <xsl:element name="{@prefix}:dummy" namespace="{@uri}"/>
1496
+ </xsl:variable>
1497
+ <xsl:variable name="p" select="@prefix"/>
1498
+ <xsl:copy-of select="exsl:node-set($ns-dummy-elements)
1499
+ /*/namespace::*[local-name()=$p]"/>
1500
+ </xsl:when>
1501
+
1502
+ <!-- End XSLT1 code -->
1503
+
1504
+ <!-- Not tested yet
1505
+ <xsl:when test="function-available('msxsl:node-set')">
1506
+ <xsl:variable name="ns-dummy-elements">
1507
+ <xsl:element name="{ $prefix }:e" namespace="{ $uri }"/>
1508
+ </xsl:variable>
1509
+ <xsl:copy-of select="msxsl:node-set($ns-dummy-elements)/*/namespace::*"/>
1510
+ </xsl:when>
1511
+ -->
1512
+
1513
+ <xsl:when test="@prefix = 'xsl' ">
1514
+ <!-- Do not generate dummy attributes with the xsl: prefix, as these
1515
+ are errors against XSLT, because we presume that the output
1516
+ stylesheet uses the xsl prefix. In any case, there would already
1517
+ be a namespace declaration for the XSLT namespace generated
1518
+ automatically, presumably using "xsl:".
1519
+ -->
1520
+ </xsl:when>
1521
+
1522
+ <xsl:when test="@uri = 'http://www.w3.org/1999/XSL/Transform'">
1523
+ <xsl:message terminate="yes">
1524
+ <xsl:text>Using the XSLT namespace with a prefix other than "xsl" in </xsl:text>
1525
+ <xsl:text>Schematron rules is not supported </xsl:text>
1526
+ <xsl:text>in this processor: </xsl:text>
1527
+ <xsl:value-of select="system-property('xsl:vendor')"/>
1528
+ </xsl:message>
1529
+ </xsl:when>
1530
+
1531
+ <xsl:otherwise>
1532
+ <xsl:attribute name="{concat(@prefix,':dummy-for-xmlns')}" namespace="{@uri}" />
1533
+
1534
+ </xsl:otherwise>
1535
+ </xsl:choose>
1536
+
1537
+
1538
+ </xsl:template>
1539
+
1540
+ <!-- ============================================================== -->
1541
+ <!-- UNEXPECTED ELEMENTS -->
1542
+ <!-- ============================================================== -->
1543
+
1544
+ <xsl:template match="iso:*" priority="-2">
1545
+ <xsl:message>
1546
+ <xsl:text>Error: unrecognized element in ISO Schematron namespace: check spelling
1547
+ and capitalization</xsl:text>
1548
+ <xsl:value-of select="name(.)"/>
1549
+ </xsl:message>
1550
+ </xsl:template>
1551
+
1552
+
1553
+ <!-- Swallow old namespace elements: there is an upfront test for them elsewhere -->
1554
+ <xsl:template match="sch:*" priority="-2" />
1555
+
1556
+ <xsl:template match="*" priority="-3">
1557
+ <xsl:choose>
1558
+ <xsl:when test=" $allow-foreign = 'false' ">
1559
+ <xsl:message>
1560
+ <xsl:text>Warning: unrecognized element </xsl:text>
1561
+ <xsl:value-of select="name(.)"/>
1562
+ </xsl:message>
1563
+ </xsl:when>
1564
+ <xsl:otherwise>
1565
+ <xsl:copy-of select="." />
1566
+ </xsl:otherwise>
1567
+ </xsl:choose>
1568
+ </xsl:template>
1569
+
1570
+ <xsl:template match="iso:*" mode="text" priority="-2" />
1571
+ <xsl:template match="*" mode="text" priority="-3">
1572
+ <xsl:choose>
1573
+ <xsl:when test=" $allow-foreign = 'false' ">
1574
+ <xsl:message>
1575
+ <xsl:text>Warning: unrecognized element </xsl:text>
1576
+ <xsl:value-of select="name(.)"/>
1577
+ </xsl:message>
1578
+ </xsl:when>
1579
+ <xsl:otherwise>
1580
+ <xsl:copy-of select="." />
1581
+ </xsl:otherwise>
1582
+ </xsl:choose>
1583
+ </xsl:template>
1584
+
1585
+ <!-- ============================================================== -->
1586
+ <!-- DEFAULT NAMED TEMPLATES -->
1587
+ <!-- These are the actions that are performed unless overridden -->
1588
+ <!-- ============================================================== -->
1589
+
1590
+ <xsl:template name="process-prolog"/>
1591
+ <!-- no params -->
1592
+
1593
+ <xsl:template name="process-root">
1594
+ <xsl:param name="contents"/>
1595
+ <xsl:param name="id" />
1596
+ <xsl:param name="version" />
1597
+ <xsl:param name="schemaVersion" />
1598
+ <xsl:param name="queryBinding" />
1599
+ <xsl:param name="title" />
1600
+
1601
+
1602
+ <!-- "Rich" parameters -->
1603
+ <xsl:param name="fpi" />
1604
+ <xsl:param name="icon" />
1605
+ <xsl:param name="lang" />
1606
+ <xsl:param name="see" />
1607
+ <xsl:param name="space" />
1608
+
1609
+ <xsl:copy-of select="$contents"/>
1610
+ </xsl:template>
1611
+
1612
+ <xsl:template name="process-assert">
1613
+
1614
+ <xsl:param name="test"/>
1615
+ <xsl:param name="diagnostics" />
1616
+ <xsl:param name="id" />
1617
+ <xsl:param name="flag" />
1618
+
1619
+ <!-- "Linkable" parameters -->
1620
+ <xsl:param name="role"/>
1621
+ <xsl:param name="subject"/>
1622
+
1623
+ <!-- "Rich" parameters -->
1624
+ <xsl:param name="fpi" />
1625
+ <xsl:param name="icon" />
1626
+ <xsl:param name="lang" />
1627
+ <xsl:param name="see" />
1628
+ <xsl:param name="space" />
1629
+
1630
+
1631
+ <xsl:call-template name="process-message">
1632
+ <xsl:with-param name="pattern" select="$test"/>
1633
+ <xsl:with-param name="role" select="$role"/>
1634
+ </xsl:call-template>
1635
+
1636
+
1637
+ </xsl:template>
1638
+
1639
+ <xsl:template name="process-report">
1640
+ <xsl:param name="test"/>
1641
+ <xsl:param name="diagnostics" />
1642
+ <xsl:param name="id" />
1643
+ <xsl:param name="flag" />
1644
+
1645
+ <!-- "Linkable" parameters -->
1646
+ <xsl:param name="role"/>
1647
+ <xsl:param name="subject"/>
1648
+
1649
+ <!-- "Rich" parameters -->
1650
+ <xsl:param name="fpi" />
1651
+ <xsl:param name="icon" />
1652
+ <xsl:param name="lang" />
1653
+ <xsl:param name="see" />
1654
+ <xsl:param name="space" />
1655
+
1656
+ <xsl:call-template name="process-message">
1657
+ <xsl:with-param name="pattern" select="$test"/>
1658
+ <xsl:with-param name="role" select="$role"/>
1659
+ </xsl:call-template>
1660
+ </xsl:template>
1661
+
1662
+ <xsl:template name="process-diagnostic">
1663
+ <xsl:param name="id" />
1664
+
1665
+ <!-- "Rich" parameters -->
1666
+ <xsl:param name="fpi" />
1667
+ <xsl:param name="icon" />
1668
+ <xsl:param name="lang" />
1669
+ <xsl:param name="see" />
1670
+ <xsl:param name="space" />
1671
+
1672
+ <!-- We generate too much whitespace rather than risking concatenation -->
1673
+ <axsl:text> </axsl:text>
1674
+ <xsl:apply-templates mode="text"/>
1675
+ <axsl:text> </axsl:text>
1676
+ </xsl:template>
1677
+
1678
+ <xsl:template name="process-dir">
1679
+ <xsl:param name="value" />
1680
+
1681
+ <!-- We generate too much whitespace rather than risking concatenation -->
1682
+ <axsl:text> </axsl:text>
1683
+ <xsl:apply-templates mode="inline-text"/>
1684
+ <axsl:text> </axsl:text>
1685
+ </xsl:template>
1686
+
1687
+ <xsl:template name="process-emph">
1688
+ <!-- We generate too much whitespace rather than risking concatenation -->
1689
+ <axsl:text> </axsl:text>
1690
+ <xsl:apply-templates mode="inline-text"/>
1691
+ <axsl:text> </axsl:text>
1692
+ </xsl:template>
1693
+
1694
+ <xsl:template name="process-name">
1695
+ <xsl:param name="name"/>
1696
+
1697
+ <!-- We generate too much whitespace rather than risking concatenation -->
1698
+ <axsl:text> </axsl:text>
1699
+ <axsl:value-of select="{$name}"/>
1700
+ <axsl:text> </axsl:text>
1701
+
1702
+ </xsl:template>
1703
+
1704
+ <xsl:template name="process-ns" >
1705
+ <!-- Note that process-ns is for reporting. The sch:ns elements are
1706
+ independently used in the sch:schema template to provide namespace bindings -->
1707
+ <xsl:param name="prefix"/>
1708
+ <xsl:param name="uri" />
1709
+ </xsl:template>
1710
+
1711
+ <xsl:template name="process-p">
1712
+ <xsl:param name="id" />
1713
+ <xsl:param name="class" />
1714
+ <xsl:param name="icon" />
1715
+ <xsl:param name="lang" />
1716
+ </xsl:template>
1717
+
1718
+ <xsl:template name="process-pattern">
1719
+ <xsl:param name="id" />
1720
+ <xsl:param name="name" />
1721
+ <xsl:param name="is-a" />
1722
+
1723
+ <!-- "Rich" parameters -->
1724
+ <xsl:param name="fpi" />
1725
+ <xsl:param name="icon" />
1726
+ <xsl:param name="lang" />
1727
+ <xsl:param name="see" />
1728
+ <xsl:param name="space" />
1729
+ </xsl:template>
1730
+
1731
+
1732
+ <xsl:template name="process-rule">
1733
+ <xsl:param name="context" />
1734
+
1735
+ <xsl:param name="id" />
1736
+ <xsl:param name="flag" />
1737
+
1738
+ <!-- "Linkable" parameters -->
1739
+ <xsl:param name="role"/>
1740
+ <xsl:param name="subject"/>
1741
+
1742
+ <!-- "Rich" parameters -->
1743
+ <xsl:param name="fpi" />
1744
+ <xsl:param name="icon" />
1745
+ <xsl:param name="lang" />
1746
+ <xsl:param name="see" />
1747
+ <xsl:param name="space" />
1748
+ </xsl:template>
1749
+
1750
+ <xsl:template name="process-span" >
1751
+ <xsl:param name="class" />
1752
+
1753
+ <!-- We generate too much whitespace rather than risking concatenation -->
1754
+ <axsl:text> </axsl:text>
1755
+ <xsl:apply-templates mode="inline-text"/>
1756
+ <axsl:text> </axsl:text>
1757
+ </xsl:template>
1758
+
1759
+ <xsl:template name="process-title" >
1760
+ <xsl:param name="class" />
1761
+ <xsl:call-template name="process-p">
1762
+ <xsl:with-param name="class">title</xsl:with-param>
1763
+ </xsl:call-template>
1764
+ </xsl:template>
1765
+
1766
+ <xsl:template name="process-schema-title" >
1767
+ <xsl:param name="class" />
1768
+ <xsl:call-template name="process-title">
1769
+ <xsl:with-param name="class">schema-title</xsl:with-param>
1770
+ </xsl:call-template>
1771
+ </xsl:template>
1772
+
1773
+ <xsl:template name="process-value-of">
1774
+ <xsl:param name="select"/>
1775
+
1776
+ <!-- We generate too much whitespace rather than risking concatenation -->
1777
+ <axsl:text> </axsl:text>
1778
+ <axsl:value-of select="{$select}"/>
1779
+ <axsl:text> </axsl:text>
1780
+ </xsl:template>
1781
+
1782
+ <!-- default output action: the simplest customization is to just override this -->
1783
+ <xsl:template name="process-message">
1784
+ <xsl:param name="pattern" />
1785
+ <xsl:param name="role" />
1786
+
1787
+ <xsl:apply-templates mode="text"/>
1788
+ <xsl:if test=" $message-newline = 'true'" >
1789
+ <axsl:value-of select="string('&#10;')"/>
1790
+ </xsl:if>
1791
+
1792
+ </xsl:template>
1793
+ </xsl:stylesheet>
1794
+
1795
+
1796
+
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl ADDED
@@ -0,0 +1,588 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" ?>
2
+ <!--
3
+ ISO_SVRL.xsl
4
+
5
+ Implementation of Schematron Validation Report Language from ISO Schematron
6
+ ISO/IEC 19757 Document Schema Definition Languages (DSDL)
7
+ Part 3: Rule-based validation Schematron
8
+ Annex D: Schematron Validation Report Language
9
+
10
+ This ISO Standard is available free as a Publicly Available Specification in PDF from ISO.
11
+ Also see www.schematron.com for drafts and other information.
12
+
13
+ This implementation of SVRL is designed to run with the "Skeleton" implementation
14
+ of Schematron which Oliver Becker devised. The skeleton code provides a
15
+ Schematron implementation but with named templates for handling all output;
16
+ the skeleton provides basic templates for output using this API, but client
17
+ validators can be written to import the skeleton and override the default output
18
+ templates as required. (In order to understand this, you must understand that
19
+ a named template such as "process-assert" in this XSLT stylesheet overrides and
20
+ replaces any template with the same name in the imported skeleton XSLT file.)
21
+
22
+ The other important thing to understand in this code is that there are different
23
+ versions of the Schematron skeleton. These track the development of Schematron through
24
+ Schematron 1.5, Schematron 1.6 and now ISO Schematron. One only skeleton must be
25
+ imported. The code has templates for the different skeletons commented out for
26
+ convenience. ISO Schematron has a different namespace than Schematron 1.5 and 1.6;
27
+ so the ISO Schematron skeleton has been written itself with an optional import
28
+ statement to in turn import the Schematron 1.6 skeleton. This will allow you to
29
+ validate with schemas from either namespace.
30
+
31
+
32
+ History:
33
+ 2009-03-18
34
+ * Fix atrribute with space "see " which generates wrong name in some processors
35
+ 2008-08-11
36
+ * RJ Fix attribute/@select which saxon allows in XSLT 1
37
+ 2008-08-07
38
+ * RJ Add output-encoding attribute to specify final encoding to use
39
+ * Alter allow-foreign functionality so that Schematron span, emph and dir elements make
40
+ it to the output, for better formatting and because span can be used to mark up
41
+ semantically interesting information embedded in diagnostics, which reduces the
42
+ need to extend SVRL itself
43
+ * Diagnostic-reference had an invalid attribute @id that duplicated @diagnostic: removed
44
+ 2008-08-06
45
+ * RJ Fix invalid output: svrl:diagnostic-reference is not contained in an svrl:text
46
+ * Output comment to SVRL file giving filename if available (from command-line parameter)
47
+ 2008-08-04
48
+ * RJ move sch: prefix to schold: prefix to prevent confusion (we want people to
49
+ be able to switch from old namespace to new namespace without changing the
50
+ sch: prefix, so it is better to keep that prefix completely out of the XSLT)
51
+ * Extra signature fixes (PH)
52
+ 2008-08-03
53
+ * Repair missing class parameter on process-p
54
+ 2008-07-31
55
+ * Update skeleton names
56
+ 2007-04-03
57
+ * Add option generate-fired-rule (RG)
58
+ 2007-02-07
59
+ * Prefer true|false for parameters. But allow yes|no on some old for compatability
60
+ * DP Diagnostics output to svrl:text. Diagnosis put out after assertion text.
61
+ * Removed non-SVRL elements and attributes: better handled as an extra layer that invokes this one
62
+ * Add more formal parameters
63
+ * Correct confusion between $schemaVersion and $queryBinding
64
+ * Indent
65
+ * Validate against RNC schemas for XSLT 1 and 2 (with regex tests removed)
66
+ * Validate output with UniversalTest.sch against RNC schema for ISO SVRL
67
+
68
+ 2007-02-01
69
+ * DP. Update formal parameters of overriding named templates to handle more attributes.
70
+ * DP. Refactor handling of rich and linkable parameters to a named template.
71
+
72
+ 2007-01-22
73
+ * DP change svrl:ns to svrl:ns-in-attribute-value
74
+ * Change default when no queryBinding from "unknown" to "xslt"
75
+
76
+ 2007-01-18:
77
+ * Improve documentation
78
+ * KH Add command-line options to generate paths or not
79
+ * Use axsl:attribute rather than xsl:attribute to shut XSLT2 up
80
+ * Add extra command-line options to pass to the iso_schematron_skeleton
81
+
82
+ 2006-12-01: iso_svrl.xsl Rick Jelliffe,
83
+ * update namespace,
84
+ * update phase handling,
85
+ * add flag param to process-assert and process-report & @ flag on output
86
+
87
+ 2001: Conformance1-5.xsl Rick Jelliffe,
88
+ * Created, using the skeleton code contributed by Oliver Becker
89
+ -->
90
+ <!--
91
+ Derived from Conformance1-5.xsl.
92
+
93
+ Copyright (c) 2001, 2006 Rick Jelliffe and Academia Sinica Computing Center, Taiwan
94
+
95
+ This software is provided 'as-is', without any express or implied warranty.
96
+ In no event will the authors be held liable for any damages arising from
97
+ the use of this software.
98
+
99
+ Permission is granted to anyone to use this software for any purpose,
100
+ including commercial applications, and to alter it and redistribute it freely,
101
+ subject to the following restrictions:
102
+
103
+ 1. The origin of this software must not be misrepresented; you must not claim
104
+ that you wrote the original software. If you use this software in a product,
105
+ an acknowledgment in the product documentation would be appreciated but is
106
+ not required.
107
+
108
+ 2. Altered source versions must be plainly marked as such, and must not be
109
+ misrepresented as being the original software.
110
+
111
+ 3. This notice may not be removed or altered from any source distribution.
112
+ -->
113
+
114
+ <!-- Ideas nabbed from schematrons by Francis N., Miloslav N. and David C. -->
115
+
116
+ <!-- The command-line parameters are:
117
+ phase NMTOKEN | "#ALL" (default) Select the phase for validation
118
+ allow-foreign "true" | "false" (default) Pass non-Schematron elements and rich markup to the generated stylesheet
119
+ diagnose= true | false|yes|no Add the diagnostics to the assertion test in reports (yes|no are obsolete)
120
+ generate-paths=true|false|yes|no generate the @location attribute with XPaths (yes|no are obsolete)
121
+ sch.exslt.imports semi-colon delimited string of filenames for some EXSLT implementations
122
+ optimize "visit-no-attributes" Use only when the schema has no attributes as the context nodes
123
+ generate-fired-rule "true"(default) | "false" Generate fired-rule elements
124
+
125
+ -->
126
+
127
+ <xsl:stylesheet
128
+ version="1.0"
129
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
130
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
131
+ xmlns:axsl="http://www.w3.org/1999/XSL/TransformAlias"
132
+ xmlns:schold="http://www.ascc.net/xml/schematron"
133
+ xmlns:iso="http://purl.oclc.org/dsdl/schematron"
134
+ xmlns:svrl="http://purl.oclc.org/dsdl/svrl"
135
+ >
136
+
137
+ <!-- Select the import statement and adjust the path as
138
+ necessary for your system.
139
+ If not XSLT2 then also remove svrl:active-pattern/@document="{document-uri()}" from process-pattern()
140
+ -->
141
+ <!--
142
+ <xsl:import href="iso_schematron_skeleton_for_saxon.xsl"/>
143
+ -->
144
+
145
+ <xsl:import href="iso_schematron_skeleton_for_xslt1.xsl"/>
146
+ <!--
147
+ <xsl:import href="iso_schematron_skeleton.xsl"/>
148
+ <xsl:import href="skeleton1-5.xsl"/>
149
+ <xsl:import href="skeleton1-6.xsl"/>
150
+ -->
151
+
152
+ <xsl:param name="diagnose" >true</xsl:param>
153
+ <xsl:param name="phase" >
154
+ <xsl:choose>
155
+ <!-- Handle Schematron 1.5 and 1.6 phases -->
156
+ <xsl:when test="//schold:schema/@defaultPhase">
157
+ <xsl:value-of select="//schold:schema/@defaultPhase"/>
158
+ </xsl:when>
159
+ <!-- Handle ISO Schematron phases -->
160
+ <xsl:when test="//iso:schema/@defaultPhase">
161
+ <xsl:value-of select="//iso:schema/@defaultPhase"/>
162
+ </xsl:when>
163
+ <xsl:otherwise>#ALL</xsl:otherwise>
164
+ </xsl:choose>
165
+ </xsl:param>
166
+ <xsl:param name="allow-foreign" >false</xsl:param>
167
+ <xsl:param name="generate-paths" >true</xsl:param>
168
+ <xsl:param name="generate-fired-rule" >true</xsl:param>
169
+ <xsl:param name="optimize"/>
170
+
171
+ <xsl:param name="output-encoding" ></xsl:param>
172
+
173
+ <!-- e.g. saxon file.xml file.xsl "sch.exslt.imports=.../string.xsl;.../math.xsl" -->
174
+ <xsl:param name="sch.exslt.imports" />
175
+
176
+
177
+
178
+ <!-- Experimental: If this file called, then must be generating svrl -->
179
+ <xsl:variable name="svrlTest" select="true()" />
180
+
181
+
182
+
183
+ <!-- ================================================================ -->
184
+
185
+ <xsl:template name="process-prolog">
186
+ <axsl:output method="xml" omit-xml-declaration="no" standalone="yes"
187
+ indent="yes">
188
+ <xsl:if test=" string-length($output-encoding) &gt; 0">
189
+ <xsl:attribute name="encoding"><xsl:value-of select=" $output-encoding" /></xsl:attribute>
190
+ </xsl:if>
191
+ </axsl:output>
192
+
193
+ </xsl:template>
194
+
195
+ <!-- Overrides skeleton.xsl -->
196
+ <xsl:template name="process-root">
197
+ <xsl:param name="title"/>
198
+ <xsl:param name="contents" />
199
+ <xsl:param name="queryBinding" >xslt1</xsl:param>
200
+ <xsl:param name="schemaVersion" />
201
+ <xsl:param name="id" />
202
+ <xsl:param name="version"/>
203
+ <!-- "Rich" parameters -->
204
+ <xsl:param name="fpi" />
205
+ <xsl:param name="icon" />
206
+ <xsl:param name="lang" />
207
+ <xsl:param name="see" />
208
+ <xsl:param name="space" />
209
+
210
+ <svrl:schematron-output title="{$title}" schemaVersion="{$schemaVersion}" >
211
+ <xsl:if test=" string-length( normalize-space( $phase )) &gt; 0 and
212
+ not( normalize-space( $phase ) = '#ALL') ">
213
+ <axsl:attribute name="phase">
214
+ <xsl:value-of select=" $phase " />
215
+ </axsl:attribute>
216
+ </xsl:if>
217
+ <xsl:if test=" $allow-foreign = 'true'">
218
+ </xsl:if>
219
+ <xsl:if test=" $allow-foreign = 'true'">
220
+
221
+ <xsl:call-template name='richParms'>
222
+ <xsl:with-param name="fpi" select="$fpi" />
223
+ <xsl:with-param name="icon" select="$icon"/>
224
+ <xsl:with-param name="lang" select="$lang"/>
225
+ <xsl:with-param name="see" select="$see" />
226
+ <xsl:with-param name="space" select="$space" />
227
+ </xsl:call-template>
228
+ </xsl:if>
229
+
230
+ <axsl:comment><axsl:value-of select="$archiveDirParameter"/> &#xA0;
231
+ <axsl:value-of select="$archiveNameParameter"/> &#xA0;
232
+ <axsl:value-of select="$fileNameParameter"/> &#xA0;
233
+ <axsl:value-of select="$fileDirParameter"/></axsl:comment>
234
+
235
+
236
+ <xsl:apply-templates mode="do-schema-p" />
237
+ <xsl:copy-of select="$contents" />
238
+ </svrl:schematron-output>
239
+ </xsl:template>
240
+
241
+
242
+ <xsl:template name="process-assert">
243
+ <xsl:param name="test"/>
244
+ <xsl:param name="diagnostics" />
245
+ <xsl:param name="id" />
246
+ <xsl:param name="flag" />
247
+ <!-- "Linkable" parameters -->
248
+ <xsl:param name="role"/>
249
+ <xsl:param name="subject"/>
250
+ <!-- "Rich" parameters -->
251
+ <xsl:param name="fpi" />
252
+ <xsl:param name="icon" />
253
+ <xsl:param name="lang" />
254
+ <xsl:param name="see" />
255
+ <xsl:param name="space" />
256
+ <svrl:failed-assert test="{$test}" >
257
+ <xsl:if test="string-length( $id ) &gt; 0">
258
+ <axsl:attribute name="id">
259
+ <xsl:value-of select=" $id " />
260
+ </axsl:attribute>
261
+ </xsl:if>
262
+ <xsl:if test=" string-length( $flag ) &gt; 0">
263
+ <axsl:attribute name="flag">
264
+ <xsl:value-of select=" $flag " />
265
+ </axsl:attribute>
266
+ </xsl:if>
267
+ <!-- Process rich attributes. -->
268
+ <xsl:call-template name="richParms">
269
+ <xsl:with-param name="fpi" select="$fpi"/>
270
+ <xsl:with-param name="icon" select="$icon"/>
271
+ <xsl:with-param name="lang" select="$lang"/>
272
+ <xsl:with-param name="see" select="$see" />
273
+ <xsl:with-param name="space" select="$space" />
274
+ </xsl:call-template>
275
+ <xsl:call-template name='linkableParms'>
276
+ <xsl:with-param name="role" select="$role" />
277
+ <xsl:with-param name="subject" select="$subject"/>
278
+ </xsl:call-template>
279
+ <xsl:if test=" $generate-paths = 'true' or $generate-paths= 'yes' ">
280
+ <!-- true/false is the new way -->
281
+ <axsl:attribute name="location">
282
+ <axsl:apply-templates select="." mode="schematron-get-full-path"/>
283
+ </axsl:attribute>
284
+ </xsl:if>
285
+
286
+ <svrl:text>
287
+ <xsl:apply-templates mode="text" />
288
+
289
+ </svrl:text>
290
+ <xsl:if test="$diagnose = 'yes' or $diagnose= 'true' ">
291
+ <!-- true/false is the new way -->
292
+ <xsl:call-template name="diagnosticsSplit">
293
+ <xsl:with-param name="str" select="$diagnostics"/>
294
+ </xsl:call-template>
295
+ </xsl:if>
296
+ </svrl:failed-assert>
297
+ </xsl:template>
298
+
299
+ <xsl:template name="process-report">
300
+ <xsl:param name="id"/>
301
+ <xsl:param name="test"/>
302
+ <xsl:param name="diagnostics"/>
303
+ <xsl:param name="flag" />
304
+ <!-- "Linkable" parameters -->
305
+ <xsl:param name="role"/>
306
+ <xsl:param name="subject"/>
307
+ <!-- "Rich" parameters -->
308
+ <xsl:param name="fpi" />
309
+ <xsl:param name="icon" />
310
+ <xsl:param name="lang" />
311
+ <xsl:param name="see" />
312
+ <xsl:param name="space" />
313
+ <svrl:successful-report test="{$test}" >
314
+ <xsl:if test=" string-length( $id ) &gt; 0">
315
+ <axsl:attribute name="id">
316
+ <xsl:value-of select=" $id " />
317
+ </axsl:attribute>
318
+ </xsl:if>
319
+ <xsl:if test=" string-length( $flag ) &gt; 0">
320
+ <axsl:attribute name="flag">
321
+ <xsl:value-of select=" $flag " />
322
+ </axsl:attribute>
323
+ </xsl:if>
324
+
325
+ <!-- Process rich attributes. -->
326
+ <xsl:call-template name="richParms">
327
+ <xsl:with-param name="fpi" select="$fpi"/>
328
+ <xsl:with-param name="icon" select="$icon"/>
329
+ <xsl:with-param name="lang" select="$lang"/>
330
+ <xsl:with-param name="see" select="$see" />
331
+ <xsl:with-param name="space" select="$space" />
332
+ </xsl:call-template>
333
+ <xsl:call-template name='linkableParms'>
334
+ <xsl:with-param name="role" select="$role" />
335
+ <xsl:with-param name="subject" select="$subject"/>
336
+ </xsl:call-template>
337
+ <xsl:if test=" $generate-paths = 'yes' or $generate-paths = 'true' ">
338
+ <!-- true/false is the new way -->
339
+ <axsl:attribute name="location">
340
+ <axsl:apply-templates select="." mode="schematron-get-full-path"/>
341
+ </axsl:attribute>
342
+ </xsl:if>
343
+
344
+ <svrl:text>
345
+ <xsl:apply-templates mode="text" />
346
+
347
+ </svrl:text>
348
+ <xsl:if test="$diagnose = 'yes' or $diagnose='true' ">
349
+ <!-- true/false is the new way -->
350
+ <xsl:call-template name="diagnosticsSplit">
351
+ <xsl:with-param name="str" select="$diagnostics"/>
352
+ </xsl:call-template>
353
+ </xsl:if>
354
+ </svrl:successful-report>
355
+ </xsl:template>
356
+
357
+
358
+ <!-- Overrides skeleton -->
359
+ <xsl:template name="process-dir" >
360
+ <xsl:param name="value" />
361
+ <xsl:choose>
362
+ <xsl:when test=" $allow-foreign = 'true'">
363
+ <xsl:copy-of select="."/>
364
+ </xsl:when>
365
+
366
+ <xsl:otherwise>
367
+ <!-- We generate too much whitespace rather than risking concatenation -->
368
+ <axsl:text> </axsl:text>
369
+ <xsl:apply-templates mode="inline-text"/>
370
+ <axsl:text> </axsl:text>
371
+ </xsl:otherwise>
372
+ </xsl:choose>
373
+ </xsl:template>
374
+
375
+ <xsl:template name="process-diagnostic">
376
+ <xsl:param name="id"/>
377
+ <!-- Rich parameters -->
378
+ <xsl:param name="fpi" />
379
+ <xsl:param name="icon" />
380
+ <xsl:param name="lang" />
381
+ <xsl:param name="see" />
382
+ <xsl:param name="space" />
383
+ <svrl:diagnostic-reference diagnostic="{$id}" >
384
+
385
+ <xsl:call-template name="richParms">
386
+ <xsl:with-param name="fpi" select="$fpi"/>
387
+ <xsl:with-param name="icon" select="$icon"/>
388
+ <xsl:with-param name="lang" select="$lang"/>
389
+ <xsl:with-param name="see" select="$see" />
390
+ <xsl:with-param name="space" select="$space" />
391
+ </xsl:call-template>
392
+ <xsl:text>
393
+ </xsl:text>
394
+
395
+ <xsl:apply-templates mode="text"/>
396
+
397
+ </svrl:diagnostic-reference>
398
+ </xsl:template>
399
+
400
+
401
+ <!-- Overrides skeleton -->
402
+ <xsl:template name="process-emph" >
403
+ <xsl:param name="class" />
404
+ <xsl:choose>
405
+ <xsl:when test=" $allow-foreign = 'true'">
406
+ <xsl:copy-of select="."/>
407
+ </xsl:when>
408
+ <xsl:otherwise>
409
+ <!-- We generate too much whitespace rather than risking concatenation -->
410
+ <axsl:text> </axsl:text>
411
+ <xsl:apply-templates mode="inline-text"/>
412
+ <axsl:text> </axsl:text>
413
+ </xsl:otherwise>
414
+ </xsl:choose>
415
+ </xsl:template>
416
+
417
+ <xsl:template name="process-rule">
418
+ <xsl:param name="id"/>
419
+ <xsl:param name="context"/>
420
+ <xsl:param name="flag"/>
421
+ <!-- "Linkable" parameters -->
422
+ <xsl:param name="role"/>
423
+ <xsl:param name="subject"/>
424
+ <!-- "Rich" parameters -->
425
+ <xsl:param name="fpi" />
426
+ <xsl:param name="icon" />
427
+ <xsl:param name="lang" />
428
+ <xsl:param name="see" />
429
+ <xsl:param name="space" />
430
+ <xsl:if test=" $generate-fired-rule = 'true'">
431
+ <svrl:fired-rule context="{$context}" >
432
+ <!-- Process rich attributes. -->
433
+ <xsl:call-template name="richParms">
434
+ <xsl:with-param name="fpi" select="$fpi"/>
435
+ <xsl:with-param name="icon" select="$icon"/>
436
+ <xsl:with-param name="lang" select="$lang"/>
437
+ <xsl:with-param name="see" select="$see" />
438
+ <xsl:with-param name="space" select="$space" />
439
+ </xsl:call-template>
440
+ <xsl:if test=" string( $id )">
441
+ <xsl:attribute name="id">
442
+ <xsl:value-of select=" $id " />
443
+ </xsl:attribute>
444
+ </xsl:if>
445
+ <xsl:if test=" string-length( $role ) &gt; 0">
446
+ <xsl:attribute name="role">
447
+ <xsl:value-of select=" $role " />
448
+ </xsl:attribute>
449
+ </xsl:if>
450
+ </svrl:fired-rule>
451
+ </xsl:if>
452
+ </xsl:template>
453
+
454
+ <xsl:template name="process-ns">
455
+ <xsl:param name="prefix"/>
456
+ <xsl:param name="uri"/>
457
+ <svrl:ns-prefix-in-attribute-values uri="{$uri}" prefix="{$prefix}" />
458
+ </xsl:template>
459
+
460
+ <xsl:template name="process-p">
461
+ <xsl:param name="icon"/>
462
+ <xsl:param name="class"/>
463
+ <xsl:param name="id"/>
464
+ <xsl:param name="lang"/>
465
+
466
+ <svrl:text>
467
+ <xsl:apply-templates mode="text"/>
468
+ </svrl:text>
469
+ </xsl:template>
470
+
471
+ <xsl:template name="process-pattern">
472
+ <xsl:param name="name"/>
473
+ <xsl:param name="id"/>
474
+ <xsl:param name="is-a"/>
475
+
476
+ <!-- "Rich" parameters -->
477
+ <xsl:param name="fpi" />
478
+ <xsl:param name="icon" />
479
+ <xsl:param name="lang" />
480
+ <xsl:param name="see" />
481
+ <xsl:param name="space" />
482
+ <svrl:active-pattern >
483
+ <xsl:if test=" string( $id )">
484
+ <axsl:attribute name="id">
485
+ <xsl:value-of select=" $id " />
486
+ </axsl:attribute>
487
+ </xsl:if>
488
+ <xsl:if test=" string( $name )">
489
+ <axsl:attribute name="name">
490
+ <xsl:value-of select=" $name " />
491
+ </axsl:attribute>
492
+ </xsl:if>
493
+
494
+ <xsl:call-template name='richParms'>
495
+ <xsl:with-param name="fpi" select="$fpi"/>
496
+ <xsl:with-param name="icon" select="$icon"/>
497
+ <xsl:with-param name="lang" select="$lang"/>
498
+ <xsl:with-param name="see" select="$see" />
499
+ <xsl:with-param name="space" select="$space" />
500
+ </xsl:call-template>
501
+
502
+ <!-- ?? report that this screws up iso:title processing -->
503
+ <xsl:apply-templates mode="do-pattern-p"/>
504
+ <!-- ?? Seems that this apply-templates is never triggered DP -->
505
+ <axsl:apply-templates />
506
+ </svrl:active-pattern>
507
+ </xsl:template>
508
+
509
+ <!-- Overrides skeleton -->
510
+ <xsl:template name="process-message" >
511
+ <xsl:param name="pattern"/>
512
+ <xsl:param name="role"/>
513
+ </xsl:template>
514
+
515
+
516
+ <!-- Overrides skeleton -->
517
+ <xsl:template name="process-span" >
518
+ <xsl:param name="class" />
519
+ <xsl:choose>
520
+ <xsl:when test=" $allow-foreign = 'true'">
521
+ <xsl:copy-of select="."/>
522
+ </xsl:when>
523
+ <xsl:otherwise>
524
+ <!-- We generate too much whitespace rather than risking concatenation -->
525
+ <axsl:text> </axsl:text>
526
+ <xsl:apply-templates mode="inline-text"/>
527
+ <axsl:text> </axsl:text>
528
+ </xsl:otherwise>
529
+ </xsl:choose>
530
+ </xsl:template>
531
+
532
+ <!-- =========================================================================== -->
533
+ <!-- processing rich parameters. -->
534
+ <xsl:template name='richParms'>
535
+ <!-- "Rich" parameters -->
536
+ <xsl:param name="fpi" />
537
+ <xsl:param name="icon" />
538
+ <xsl:param name="lang" />
539
+ <xsl:param name="see" />
540
+ <xsl:param name="space" />
541
+ <!-- Process rich attributes. -->
542
+ <xsl:if test=" $allow-foreign = 'true'">
543
+ <xsl:if test="string($fpi)">
544
+ <axsl:attribute name="fpi">
545
+ <xsl:value-of select="$fpi"/>
546
+ </axsl:attribute>
547
+ </xsl:if>
548
+ <xsl:if test="string($icon)">
549
+ <axsl:attribute name="icon">
550
+ <xsl:value-of select="$icon"/>
551
+ </axsl:attribute>
552
+ </xsl:if>
553
+ <xsl:if test="string($see)">
554
+ <axsl:attribute name="see">
555
+ <xsl:value-of select="$see"/>
556
+ </axsl:attribute>
557
+ </xsl:if>
558
+ </xsl:if>
559
+ <xsl:if test="string($space)">
560
+ <axsl:attribute name="xml:space">
561
+ <xsl:value-of select="$space"/>
562
+ </axsl:attribute>
563
+ </xsl:if>
564
+ <xsl:if test="string($lang)">
565
+ <axsl:attribute name="xml:lang">
566
+ <xsl:value-of select="$lang"/>
567
+ </axsl:attribute>
568
+ </xsl:if>
569
+ </xsl:template>
570
+
571
+ <!-- processing linkable parameters. -->
572
+ <xsl:template name='linkableParms'>
573
+ <xsl:param name="role"/>
574
+ <xsl:param name="subject"/>
575
+
576
+ <!-- ISO SVRL has a role attribute to match the Schematron role attribute -->
577
+ <xsl:if test=" string($role )">
578
+ <axsl:attribute name="role">
579
+ <xsl:value-of select=" $role " />
580
+ </axsl:attribute>
581
+ </xsl:if>
582
+ <!-- ISO SVRL does not have a subject attribute to match the Schematron subject attribute.
583
+ Instead, the Schematron subject attribute is folded into the location attribute -->
584
+ </xsl:template>
585
+
586
+
587
+ </xsl:stylesheet>
588
+
.venv/lib/python3.12/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ISO SCHEMATRON 2010
2
+
3
+ XSLT implementation by Rick Jelliffe with assistance from members of Schematron-love-in maillist.
4
+
5
+ 2010-04-21
6
+
7
+ Two distributions are available. One is for XSLT1 engines.
8
+ The other is for XSLT2 engines, such as SAXON 9.
9
+
10
+
11
+ This version of Schematron splits the process into a pipeline of several different XSLT stages.
12
+
13
+ 1) First, preprocess your Schematron schema with iso_dsdl_include.xsl.
14
+ This is a macro processor to assemble the schema from various parts.
15
+ If your schema is not in separate parts, you can skip this stage.
16
+ This stage also generates error messages for some common XPath syntax problems.
17
+
18
+ 2) Second, preprocess the output from stage 1 with iso_abstract_expand.xsl.
19
+ This is a macro processor to convert abstract patterns to real patterns.
20
+ If your schema does not use abstract patterns, you can skip this
21
+ stage.
22
+
23
+ 3) Third, compile the Schematron schema into an XSLT script.
24
+ This will typically use iso_svrl_for_xslt1.xsl or iso_svrl_for_xslt2.xsl
25
+ (which in turn invoke iso_schematron_skeleton_for_xslt1.xsl or iso_schematron_skeleton_for_saxon.xsl)
26
+ However, other "meta-stylesheets" are also in common use; the principle of operation is the same.
27
+ If your schema uses Schematron phases, supply these as command line/invocation parameters
28
+ to this process.
29
+
30
+ 4) Fourth, run the script generated by stage 3 against the document being validated.
31
+ If you are using the SVRL script, then the output of validation will be an XML document.
32
+ If your schema uses Schematron parameters, supply these as command line/invocation parameters
33
+ to this process.
34
+
35
+
36
+ The XSLT2 distribution also features several next generation features,
37
+ such as validating multiple documents. See the source code for details.
38
+
39
+ Schematron assertions can be written in any language, of course; the file
40
+ sch-messages-en.xhtml contains the diagnostics messages from the XSLT2 skeleton
41
+ in English, and this can be used as template to localize the skeleton's
42
+ error messages. Note that typically programming errors in Schematron are XPath
43
+ errors, which requires localized messages from the XSLT engine.
44
+
45
+ ANT
46
+ ---
47
+ To give an example of how to process a document, here is a sample ANT task.
48
+
49
+ <target name="schematron-compile-test" >
50
+
51
+ <!-- expand inclusions -->
52
+ <xslt basedir="test/schematron"
53
+ style="iso_dsdl_include.xsl" in="test.sch" out="test1.sch">
54
+ <classpath>
55
+ <pathelement location="${lib.dir}/saxon9.jar"/>
56
+ </classpath>
57
+ </xslt>
58
+
59
+ <!-- expand abstract patterns -->
60
+ <xslt basedir="test/schematron"
61
+ style="iso_abstract_expand.xsl" in="test1.sch" out="test2.sch">
62
+ <classpath>
63
+ <pathelement location="${lib.dir}/saxon9.jar"/>
64
+ </classpath>
65
+ </xslt>
66
+
67
+
68
+
69
+ <!-- compile it -->
70
+ <xslt basedir="test/schematron"
71
+ style="iso_svrl_for_xslt2.xsl" in="test2.sch" out="test.xsl">
72
+ <classpath>
73
+ <pathelement location="${lib.dir}/saxon9.jar"/>
74
+ </classpath>
75
+ </xslt>
76
+
77
+ <!-- validate -->
78
+ <xslt basedir="test/schematron"
79
+ style="test.xsl" in="instance.xml" out="instance.svrlt">
80
+ <classpath>
81
+ <pathelement location="${lib.dir}/saxon9.jar"/>
82
+ </classpath>
83
+ </xslt>
84
+ </target>
.venv/lib/python3.12/site-packages/lxml/iterparse.pxi ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iterparse -- event-driven parsing
2
+
3
+ cdef class iterparse:
4
+ """iterparse(self, source, events=("end",), tag=None, \
5
+ attribute_defaults=False, dtd_validation=False, \
6
+ load_dtd=False, no_network=True, remove_blank_text=False, \
7
+ compact=True, resolve_entities='internal', remove_comments=False, \
8
+ remove_pis=False, strip_cdata=True, encoding=None, \
9
+ html=False, recover=None, huge_tree=False, schema=None, \
10
+ chunk_size=32768)
11
+
12
+ Incremental parser.
13
+
14
+ Parses XML into a tree and generates tuples (event, element) in a
15
+ SAX-like fashion. ``event`` is any of 'start', 'end', 'start-ns',
16
+ 'end-ns'.
17
+
18
+ For 'start' and 'end', ``element`` is the Element that the parser just
19
+ found opening or closing. For 'start-ns', it is a tuple (prefix, URI) of
20
+ a new namespace declaration. For 'end-ns', it is simply None. Note that
21
+ all start and end events are guaranteed to be properly nested.
22
+
23
+ The keyword argument ``events`` specifies a sequence of event type names
24
+ that should be generated. By default, only 'end' events will be
25
+ generated.
26
+
27
+ The additional ``tag`` argument restricts the 'start' and 'end' events to
28
+ those elements that match the given tag. The ``tag`` argument can also be
29
+ a sequence of tags to allow matching more than one tag. By default,
30
+ events are generated for all elements. Note that the 'start-ns' and
31
+ 'end-ns' events are not impacted by this restriction.
32
+
33
+ The other keyword arguments in the constructor are mainly based on the
34
+ libxml2 parser configuration. A DTD will also be loaded if validation or
35
+ attribute default values are requested.
36
+
37
+ Available boolean keyword arguments:
38
+ - attribute_defaults: read default attributes from DTD
39
+ - dtd_validation: validate (if DTD is available)
40
+ - load_dtd: use DTD for parsing
41
+ - no_network: prevent network access for related files
42
+ - remove_blank_text: discard blank text nodes
43
+ - remove_comments: discard comments
44
+ - remove_pis: discard processing instructions
45
+ - strip_cdata: replace CDATA sections by normal text content (default:
46
+ True for XML, ignored otherwise)
47
+ - compact: safe memory for short text content (default: True)
48
+ - resolve_entities: replace entities by their text value
49
+ (default: 'internal' only; True before lxml 6.1)
50
+ - huge_tree: disable security restrictions and support very deep trees
51
+ and very long text content (only affects libxml2 2.7+)
52
+ - html: parse input as HTML (default: XML)
53
+ - recover: try hard to parse through broken input (default: True for HTML,
54
+ False otherwise)
55
+
56
+ Other keyword arguments:
57
+ - encoding: override the document encoding
58
+ - schema: an XMLSchema to validate against
59
+ - chunk_size: the number of bytes to read from the 'source' in one chunk
60
+ (default: 32768)
61
+ """
62
+ cdef _FeedParser _parser
63
+ cdef object _tag
64
+ cdef object _events
65
+ cdef readonly object root
66
+ cdef object _source
67
+ cdef object _filename
68
+ cdef object _error
69
+ cdef object _chunk_size
70
+ cdef bint _close_source_after_read
71
+
72
+ def __init__(self, source, events=("end",), *, tag=None,
73
+ attribute_defaults=False, dtd_validation=False,
74
+ load_dtd=False, no_network=True, remove_blank_text=False,
75
+ compact=True, resolve_entities='internal', remove_comments=False,
76
+ remove_pis=False, strip_cdata=True, encoding=None,
77
+ html=False, recover=None, huge_tree=False, collect_ids=True,
78
+ XMLSchema schema=None, int chunk_size=32768):
79
+ if not hasattr(source, 'read'):
80
+ source = _getFSPathOrObject(source)
81
+ self._filename = source
82
+ self._source = open(source, 'rb')
83
+ self._close_source_after_read = True
84
+ else:
85
+ self._filename = _getFilenameForFile(source)
86
+ self._source = source
87
+ self._close_source_after_read = False
88
+
89
+ if recover is None:
90
+ recover = html
91
+
92
+ if html:
93
+ # make sure we're not looking for namespaces
94
+ events = [event for event in events
95
+ if event not in ('start-ns', 'end-ns')]
96
+ parser = HTMLPullParser(
97
+ events,
98
+ tag=tag,
99
+ recover=recover,
100
+ base_url=self._filename,
101
+ encoding=encoding,
102
+ remove_blank_text=remove_blank_text,
103
+ remove_comments=remove_comments,
104
+ remove_pis=remove_pis,
105
+ no_network=no_network,
106
+ target=None, # TODO
107
+ schema=schema,
108
+ compact=compact)
109
+ else:
110
+ parser = XMLPullParser(
111
+ events,
112
+ tag=tag,
113
+ recover=recover,
114
+ base_url=self._filename,
115
+ encoding=encoding,
116
+ attribute_defaults=attribute_defaults,
117
+ dtd_validation=dtd_validation,
118
+ load_dtd=load_dtd,
119
+ no_network=no_network,
120
+ schema=schema,
121
+ huge_tree=huge_tree,
122
+ remove_blank_text=remove_blank_text,
123
+ resolve_entities=resolve_entities,
124
+ remove_comments=remove_comments,
125
+ remove_pis=remove_pis,
126
+ strip_cdata=strip_cdata,
127
+ collect_ids=True,
128
+ target=None, # TODO
129
+ compact=compact)
130
+
131
+ self._chunk_size = chunk_size
132
+ self._events = parser.read_events()
133
+ self._parser = parser
134
+
135
+ @property
136
+ def error_log(self):
137
+ """The error log of the last (or current) parser run.
138
+ """
139
+ return self._parser.feed_error_log
140
+
141
+ @property
142
+ def resolvers(self):
143
+ """The custom resolver registry of the last (or current) parser run.
144
+ """
145
+ return self._parser.resolvers
146
+
147
+ @property
148
+ def version(self):
149
+ """The version of the underlying XML parser."""
150
+ return self._parser.version
151
+
152
+ def set_element_class_lookup(self, ElementClassLookup lookup = None):
153
+ """set_element_class_lookup(self, lookup = None)
154
+
155
+ Set a lookup scheme for element classes generated from this parser.
156
+
157
+ Reset it by passing None or nothing.
158
+ """
159
+ self._parser.set_element_class_lookup(lookup)
160
+
161
+ def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
162
+ """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
163
+
164
+ Creates a new element associated with this parser.
165
+ """
166
+ self._parser.makeelement(
167
+ _tag, attrib=None, nsmap=None, **_extra)
168
+
169
+ @cython.final
170
+ cdef _close_source(self):
171
+ if self._source is None:
172
+ return
173
+ if not self._close_source_after_read:
174
+ self._source = None
175
+ return
176
+ try:
177
+ close = self._source.close
178
+ except AttributeError:
179
+ close = None
180
+ finally:
181
+ self._source = None
182
+ if close is not None:
183
+ close()
184
+
185
+ def __iter__(self):
186
+ return self
187
+
188
+ def __next__(self):
189
+ try:
190
+ return next(self._events)
191
+ except StopIteration:
192
+ pass
193
+ context = <_SaxParserContext>self._parser._getPushParserContext()
194
+ if self._source is not None:
195
+ done = False
196
+ while not done:
197
+ try:
198
+ done = self._read_more_events(context)
199
+ return next(self._events)
200
+ except StopIteration:
201
+ pass # no events yet
202
+ except Exception as e:
203
+ self._error = e
204
+ self._close_source()
205
+ try:
206
+ return next(self._events)
207
+ except StopIteration:
208
+ break
209
+ # nothing left to read or return
210
+ if self._error is not None:
211
+ error = self._error
212
+ self._error = None
213
+ raise error
214
+ if (context._validator is not None
215
+ and not context._validator.isvalid()):
216
+ _raiseParseError(context._c_ctxt, self._filename,
217
+ context._error_log)
218
+ # no errors => all done
219
+ raise StopIteration
220
+
221
+ @cython.final
222
+ cdef bint _read_more_events(self, _SaxParserContext context) except -123:
223
+ data = self._source.read(self._chunk_size)
224
+ if not isinstance(data, bytes):
225
+ self._close_source()
226
+ raise TypeError("reading file objects must return bytes objects")
227
+ if not data:
228
+ try:
229
+ self.root = self._parser.close()
230
+ finally:
231
+ self._close_source()
232
+ return True
233
+ self._parser.feed(data)
234
+ return False
235
+
236
+
237
+ cdef enum _IterwalkSkipStates:
238
+ IWSKIP_NEXT_IS_START
239
+ IWSKIP_SKIP_NEXT
240
+ IWSKIP_CAN_SKIP
241
+ IWSKIP_CANNOT_SKIP
242
+
243
+
244
+ cdef class iterwalk:
245
+ """iterwalk(self, element_or_tree, events=("end",), tag=None)
246
+
247
+ A tree walker that generates events from an existing tree as if it
248
+ was parsing XML data with ``iterparse()``.
249
+
250
+ Just as for ``iterparse()``, the ``tag`` argument can be a single tag or a
251
+ sequence of tags.
252
+
253
+ After receiving a 'start' or 'start-ns' event, the children and
254
+ descendants of the current element can be excluded from iteration
255
+ by calling the ``skip_subtree()`` method.
256
+ """
257
+ cdef _MultiTagMatcher _matcher
258
+ cdef list _node_stack
259
+ cdef list _events
260
+ cdef object _pop_event
261
+ cdef object _include_siblings
262
+ cdef int _index
263
+ cdef int _event_filter
264
+ cdef _IterwalkSkipStates _skip_state
265
+
266
+ def __init__(self, element_or_tree, events=("end",), tag=None):
267
+ cdef _Element root
268
+ cdef int ns_count
269
+ root = _rootNodeOrRaise(element_or_tree)
270
+ self._event_filter = _buildParseEventFilter(events)
271
+ if tag is None or tag == '*':
272
+ self._matcher = None
273
+ else:
274
+ self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag)
275
+ self._node_stack = []
276
+ self._events = []
277
+ self._pop_event = self._events.pop
278
+ self._skip_state = IWSKIP_CANNOT_SKIP # ignore all skip requests by default
279
+
280
+ if self._event_filter:
281
+ self._index = 0
282
+ if self._matcher is not None and self._event_filter & PARSE_EVENT_FILTER_START:
283
+ self._matcher.cacheTags(root._doc)
284
+
285
+ # When processing an ElementTree, add events for the preceding comments/PIs.
286
+ if self._event_filter & (PARSE_EVENT_FILTER_COMMENT | PARSE_EVENT_FILTER_PI):
287
+ if isinstance(element_or_tree, _ElementTree):
288
+ self._include_siblings = root
289
+ for elem in list(root.itersiblings(preceding=True))[::-1]:
290
+ if self._event_filter & PARSE_EVENT_FILTER_COMMENT and elem.tag is Comment:
291
+ self._events.append(('comment', elem))
292
+ elif self._event_filter & PARSE_EVENT_FILTER_PI and elem.tag is PI:
293
+ self._events.append(('pi', elem))
294
+
295
+ ns_count = self._start_node(root)
296
+ self._node_stack.append( (root, ns_count) )
297
+ else:
298
+ self._index = -1
299
+
300
+ def __iter__(self):
301
+ return self
302
+
303
+ def __next__(self):
304
+ cdef xmlNode* c_child
305
+ cdef _Element node
306
+ cdef _Element next_node
307
+ cdef int ns_count = 0
308
+ if self._events:
309
+ return self._next_event()
310
+ if self._matcher is not None and self._index >= 0:
311
+ node = self._node_stack[self._index][0]
312
+ self._matcher.cacheTags(node._doc)
313
+
314
+ # find next node
315
+ while self._index >= 0:
316
+ node = self._node_stack[self._index][0]
317
+
318
+ if self._skip_state == IWSKIP_SKIP_NEXT:
319
+ c_child = NULL
320
+ else:
321
+ c_child = self._process_non_elements(
322
+ node._doc, _findChildForwards(node._c_node, 0))
323
+ self._skip_state = IWSKIP_CANNOT_SKIP
324
+
325
+ while c_child is NULL:
326
+ # back off through parents
327
+ self._index -= 1
328
+ node = self._end_node()
329
+ if self._index < 0:
330
+ break
331
+ c_child = self._process_non_elements(
332
+ node._doc, _nextElement(node._c_node))
333
+
334
+ if c_child is not NULL:
335
+ next_node = _elementFactory(node._doc, c_child)
336
+ if self._event_filter & (PARSE_EVENT_FILTER_START |
337
+ PARSE_EVENT_FILTER_START_NS):
338
+ ns_count = self._start_node(next_node)
339
+ elif self._event_filter & PARSE_EVENT_FILTER_END_NS:
340
+ ns_count = _countNsDefs(next_node._c_node)
341
+ self._node_stack.append( (next_node, ns_count) )
342
+ self._index += 1
343
+ if self._events:
344
+ return self._next_event()
345
+
346
+ if self._include_siblings is not None:
347
+ node, self._include_siblings = self._include_siblings, None
348
+ self._process_non_elements(node._doc, _nextElement(node._c_node))
349
+ if self._events:
350
+ return self._next_event()
351
+
352
+ raise StopIteration
353
+
354
+ @cython.final
355
+ cdef xmlNode* _process_non_elements(self, _Document doc, xmlNode* c_node):
356
+ while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE:
357
+ if c_node.type == tree.XML_COMMENT_NODE:
358
+ if self._event_filter & PARSE_EVENT_FILTER_COMMENT:
359
+ self._events.append(
360
+ ("comment", _elementFactory(doc, c_node)))
361
+ c_node = _nextElement(c_node)
362
+ elif c_node.type == tree.XML_PI_NODE:
363
+ if self._event_filter & PARSE_EVENT_FILTER_PI:
364
+ self._events.append(
365
+ ("pi", _elementFactory(doc, c_node)))
366
+ c_node = _nextElement(c_node)
367
+ else:
368
+ break
369
+ return c_node
370
+
371
+ @cython.final
372
+ cdef _next_event(self):
373
+ if self._skip_state == IWSKIP_NEXT_IS_START:
374
+ if self._events[0][0] in ('start', 'start-ns'):
375
+ self._skip_state = IWSKIP_CAN_SKIP
376
+ return self._pop_event(0)
377
+
378
+ def skip_subtree(self):
379
+ """Prevent descending into the current subtree.
380
+ Instead, the next returned event will be the 'end' event of the current element
381
+ (if included), ignoring any children or descendants.
382
+
383
+ This has no effect right after an 'end' or 'end-ns' event.
384
+ """
385
+ if self._skip_state == IWSKIP_CAN_SKIP:
386
+ self._skip_state = IWSKIP_SKIP_NEXT
387
+
388
+ @cython.final
389
+ cdef int _start_node(self, _Element node) except -1:
390
+ cdef int ns_count
391
+ if self._event_filter & PARSE_EVENT_FILTER_START_NS:
392
+ ns_count = _appendStartNsEvents(node._c_node, self._events)
393
+ if self._events:
394
+ self._skip_state = IWSKIP_NEXT_IS_START
395
+ elif self._event_filter & PARSE_EVENT_FILTER_END_NS:
396
+ ns_count = _countNsDefs(node._c_node)
397
+ else:
398
+ ns_count = 0
399
+ if self._event_filter & PARSE_EVENT_FILTER_START:
400
+ if self._matcher is None or self._matcher.matches(node._c_node):
401
+ self._events.append( ("start", node) )
402
+ self._skip_state = IWSKIP_NEXT_IS_START
403
+ return ns_count
404
+
405
+ @cython.final
406
+ cdef _Element _end_node(self):
407
+ cdef _Element node
408
+ cdef int i, ns_count
409
+ node, ns_count = self._node_stack.pop()
410
+ if self._event_filter & PARSE_EVENT_FILTER_END:
411
+ if self._matcher is None or self._matcher.matches(node._c_node):
412
+ self._events.append( ("end", node) )
413
+ if self._event_filter & PARSE_EVENT_FILTER_END_NS and ns_count:
414
+ event = ("end-ns", None)
415
+ for i in range(ns_count):
416
+ self._events.append(event)
417
+ return node
418
+
419
+
420
+ cdef int _countNsDefs(xmlNode* c_node) noexcept:
421
+ cdef xmlNs* c_ns
422
+ cdef int count
423
+ count = 0
424
+ c_ns = c_node.nsDef
425
+ while c_ns is not NULL:
426
+ count += (c_ns.href is not NULL)
427
+ c_ns = c_ns.next
428
+ return count
429
+
430
+
431
+ cdef int _appendStartNsEvents(xmlNode* c_node, list event_list) except -1:
432
+ cdef xmlNs* c_ns
433
+ cdef int count
434
+ count = 0
435
+ c_ns = c_node.nsDef
436
+ while c_ns is not NULL:
437
+ if c_ns.href:
438
+ ns_tuple = (funicodeOrEmpty(c_ns.prefix),
439
+ funicode(c_ns.href))
440
+ event_list.append( ("start-ns", ns_tuple) )
441
+ count += 1
442
+ c_ns = c_ns.next
443
+ return count
.venv/lib/python3.12/site-packages/lxml/lxml.etree.h ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Generated by Cython 3.2.9 */
2
+
3
+ #ifndef __PYX_HAVE__lxml__etree
4
+ #define __PYX_HAVE__lxml__etree
5
+
6
+ #include "Python.h"
7
+ struct LxmlDocument;
8
+ struct LxmlElement;
9
+ struct LxmlElementTree;
10
+ struct LxmlElementTagMatcher;
11
+ struct LxmlElementIterator;
12
+ struct LxmlElementBase;
13
+ struct LxmlElementClassLookup;
14
+ struct LxmlFallbackElementClassLookup;
15
+
16
+ /* "lxml/etree.pyx":456
17
+ *
18
+ * # type of a function that steps from node to node
19
+ * ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*) # <<<<<<<<<<<<<<
20
+ *
21
+ *
22
+ */
23
+ typedef xmlNode *(*_node_to_node_function)(xmlNode *);
24
+
25
+ /* "lxml/etree.pyx":470
26
+ * # Public Python API
27
+ *
28
+ * @cython.final # <<<<<<<<<<<<<<
29
+ * @cython.freelist(8)
30
+ * cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]:
31
+ */
32
+ struct LxmlDocument {
33
+ PyObject_HEAD
34
+ struct __pyx_vtabstruct_4lxml_5etree__Document *__pyx_vtab;
35
+ int _ns_counter;
36
+ PyObject *_prefix_tail;
37
+ xmlDoc *_c_doc;
38
+ struct __pyx_obj_4lxml_5etree__BaseParser *_parser;
39
+ };
40
+
41
+ /* "lxml/etree.pyx":823
42
+ *
43
+ *
44
+ * @cython.no_gc_clear # <<<<<<<<<<<<<<
45
+ * cdef public class _Element [ type LxmlElementType, object LxmlElement ]:
46
+ * """Element class.
47
+ */
48
+ struct LxmlElement {
49
+ PyObject_HEAD
50
+ struct LxmlDocument *_doc;
51
+ xmlNode *_c_node;
52
+ PyObject *_tag;
53
+ };
54
+
55
+ /* "lxml/etree.pyx":1997
56
+ *
57
+ *
58
+ * cdef public class _ElementTree [ type LxmlElementTreeType, # <<<<<<<<<<<<<<
59
+ * object LxmlElementTree ]:
60
+ * cdef _Document _doc
61
+ */
62
+ struct LxmlElementTree {
63
+ PyObject_HEAD
64
+ struct __pyx_vtabstruct_4lxml_5etree__ElementTree *__pyx_vtab;
65
+ struct LxmlDocument *_doc;
66
+ struct LxmlElement *_context_node;
67
+ };
68
+
69
+ /* "lxml/etree.pyx":2771
70
+ *
71
+ *
72
+ * cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher, # <<<<<<<<<<<<<<
73
+ * type LxmlElementTagMatcherType ]:
74
+ * """
75
+ */
76
+ struct LxmlElementTagMatcher {
77
+ PyObject_HEAD
78
+ struct __pyx_vtabstruct_4lxml_5etree__ElementTagMatcher *__pyx_vtab;
79
+ PyObject *_pystrings;
80
+ int _node_type;
81
+ char *_href;
82
+ char *_name;
83
+ };
84
+
85
+ /* "lxml/etree.pyx":2802
86
+ * self._name = NULL
87
+ *
88
+ * cdef public class _ElementIterator(_ElementTagMatcher) [ # <<<<<<<<<<<<<<
89
+ * object LxmlElementIterator, type LxmlElementIteratorType ]:
90
+ * """
91
+ */
92
+ struct LxmlElementIterator {
93
+ struct LxmlElementTagMatcher __pyx_base;
94
+ struct LxmlElement *_node;
95
+ _node_to_node_function _next_element;
96
+ };
97
+
98
+ /* "src/lxml/classlookup.pxi":6
99
+ * # Custom Element classes
100
+ *
101
+ * cdef public class ElementBase(_Element) [ type LxmlElementBaseType, # <<<<<<<<<<<<<<
102
+ * object LxmlElementBase ]:
103
+ * """ElementBase(*children, attrib=None, nsmap=None, **_extra)
104
+ */
105
+ struct LxmlElementBase {
106
+ struct LxmlElement __pyx_base;
107
+ };
108
+
109
+ /* "src/lxml/classlookup.pxi":210
110
+ * # Element class lookup
111
+ *
112
+ * ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*) # <<<<<<<<<<<<<<
113
+ *
114
+ * # class to store element class lookup functions
115
+ */
116
+ typedef PyObject *(*_element_class_lookup_function)(PyObject *, struct LxmlDocument *, xmlNode *);
117
+
118
+ /* "src/lxml/classlookup.pxi":213
119
+ *
120
+ * # class to store element class lookup functions
121
+ * cdef public class ElementClassLookup [ type LxmlElementClassLookupType, # <<<<<<<<<<<<<<
122
+ * object LxmlElementClassLookup ]:
123
+ * """ElementClassLookup(self)
124
+ */
125
+ struct LxmlElementClassLookup {
126
+ PyObject_HEAD
127
+ _element_class_lookup_function _lookup_function;
128
+ };
129
+
130
+ /* "src/lxml/classlookup.pxi":221
131
+ *
132
+ *
133
+ * cdef public class FallbackElementClassLookup(ElementClassLookup) \ # <<<<<<<<<<<<<<
134
+ * [ type LxmlFallbackElementClassLookupType,
135
+ * object LxmlFallbackElementClassLookup ]:
136
+ */
137
+ struct LxmlFallbackElementClassLookup {
138
+ struct LxmlElementClassLookup __pyx_base;
139
+ struct __pyx_vtabstruct_4lxml_5etree_FallbackElementClassLookup *__pyx_vtab;
140
+ struct LxmlElementClassLookup *fallback;
141
+ _element_class_lookup_function _fallback_function;
142
+ };
143
+
144
+ #ifndef __PYX_HAVE_API__lxml__etree
145
+
146
+ #ifdef CYTHON_EXTERN_C
147
+ #undef __PYX_EXTERN_C
148
+ #define __PYX_EXTERN_C CYTHON_EXTERN_C
149
+ #elif defined(__PYX_EXTERN_C)
150
+ #ifdef _MSC_VER
151
+ #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.")
152
+ #else
153
+ #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.
154
+ #endif
155
+ #else
156
+ #ifdef __cplusplus
157
+ #define __PYX_EXTERN_C extern "C"
158
+ #else
159
+ #define __PYX_EXTERN_C extern
160
+ #endif
161
+ #endif
162
+
163
+ #ifndef DL_IMPORT
164
+ #define DL_IMPORT(_T) _T
165
+ #endif
166
+
167
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlDocumentType;
168
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementType;
169
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTreeType;
170
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTagMatcherType;
171
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementIteratorType;
172
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementBaseType;
173
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementClassLookupType;
174
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlFallbackElementClassLookupType;
175
+
176
+ __PYX_EXTERN_C struct LxmlElement *deepcopyNodeToDocument(struct LxmlDocument *, xmlNode *);
177
+ __PYX_EXTERN_C struct LxmlElementTree *elementTreeFactory(struct LxmlElement *);
178
+ __PYX_EXTERN_C struct LxmlElementTree *newElementTree(struct LxmlElement *, PyObject *);
179
+ __PYX_EXTERN_C struct LxmlElementTree *adoptExternalDocument(xmlDoc *, PyObject *, int);
180
+ __PYX_EXTERN_C struct LxmlElement *elementFactory(struct LxmlDocument *, xmlNode *);
181
+ __PYX_EXTERN_C struct LxmlElement *makeElement(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
182
+ __PYX_EXTERN_C struct LxmlElement *makeSubElement(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
183
+ __PYX_EXTERN_C void setElementClassLookupFunction(_element_class_lookup_function, PyObject *);
184
+ __PYX_EXTERN_C PyObject *lookupDefaultElementClass(PyObject *, PyObject *, xmlNode *);
185
+ __PYX_EXTERN_C PyObject *lookupNamespaceElementClass(PyObject *, PyObject *, xmlNode *);
186
+ __PYX_EXTERN_C PyObject *callLookupFallback(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *);
187
+ __PYX_EXTERN_C int tagMatches(xmlNode *, const xmlChar *, const xmlChar *);
188
+ __PYX_EXTERN_C struct LxmlDocument *documentOrRaise(PyObject *);
189
+ __PYX_EXTERN_C struct LxmlElement *rootNodeOrRaise(PyObject *);
190
+ __PYX_EXTERN_C int hasText(xmlNode *);
191
+ __PYX_EXTERN_C int hasTail(xmlNode *);
192
+ __PYX_EXTERN_C PyObject *textOf(xmlNode *);
193
+ __PYX_EXTERN_C PyObject *tailOf(xmlNode *);
194
+ __PYX_EXTERN_C int setNodeText(xmlNode *, PyObject *);
195
+ __PYX_EXTERN_C int setTailText(xmlNode *, PyObject *);
196
+ __PYX_EXTERN_C PyObject *attributeValue(xmlNode *, xmlAttr *);
197
+ __PYX_EXTERN_C PyObject *attributeValueFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
198
+ __PYX_EXTERN_C PyObject *getAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
199
+ __PYX_EXTERN_C PyObject *iterattributes(struct LxmlElement *, int);
200
+ __PYX_EXTERN_C PyObject *collectAttributes(xmlNode *, int);
201
+ __PYX_EXTERN_C int setAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
202
+ __PYX_EXTERN_C int delAttribute(struct LxmlElement *, PyObject *);
203
+ __PYX_EXTERN_C int delAttributeFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
204
+ __PYX_EXTERN_C int hasChild(xmlNode *);
205
+ __PYX_EXTERN_C xmlNode *findChild(xmlNode *, Py_ssize_t);
206
+ __PYX_EXTERN_C xmlNode *findChildForwards(xmlNode *, Py_ssize_t);
207
+ __PYX_EXTERN_C xmlNode *findChildBackwards(xmlNode *, Py_ssize_t);
208
+ __PYX_EXTERN_C xmlNode *nextElement(xmlNode *);
209
+ __PYX_EXTERN_C xmlNode *previousElement(xmlNode *);
210
+ __PYX_EXTERN_C void appendChild(struct LxmlElement *, struct LxmlElement *);
211
+ __PYX_EXTERN_C int appendChildToElement(struct LxmlElement *, struct LxmlElement *);
212
+ __PYX_EXTERN_C PyObject *pyunicode(const xmlChar *);
213
+ __PYX_EXTERN_C PyObject *utf8(PyObject *);
214
+ __PYX_EXTERN_C PyObject *getNsTag(PyObject *);
215
+ __PYX_EXTERN_C PyObject *getNsTagWithEmptyNs(PyObject *);
216
+ __PYX_EXTERN_C PyObject *namespacedName(xmlNode *);
217
+ __PYX_EXTERN_C PyObject *namespacedNameFromNsName(const xmlChar *, const xmlChar *);
218
+ __PYX_EXTERN_C void iteratorStoreNext(struct LxmlElementIterator *, struct LxmlElement *);
219
+ __PYX_EXTERN_C void initTagMatch(struct LxmlElementTagMatcher *, PyObject *);
220
+ __PYX_EXTERN_C xmlNs *findOrBuildNodeNsPrefix(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *);
221
+
222
+ #endif /* !__PYX_HAVE_API__lxml__etree */
223
+
224
+ /* WARNING: the interface of the module init function changed in CPython 3.5. */
225
+ /* It now returns a PyModuleDef instance instead of a PyModule instance. */
226
+
227
+ /* WARNING: Use PyImport_AppendInittab("etree", PyInit_etree) instead of calling PyInit_etree directly from Python 3.5 */
228
+ PyMODINIT_FUNC PyInit_etree(void);
229
+
230
+ #if PY_VERSION_HEX >= 0x03050000 && (defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) || (defined(__cplusplus) && __cplusplus >= 201402L))
231
+ #if defined(__cplusplus) && __cplusplus >= 201402L
232
+ [[deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")]] inline
233
+ #elif defined(__GNUC__) || defined(__clang__)
234
+ __attribute__ ((__deprecated__("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly."), __unused__)) __inline__
235
+ #elif defined(_MSC_VER)
236
+ __declspec(deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")) __inline
237
+ #endif
238
+ static PyObject* __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyObject* res) {
239
+ return res;
240
+ }
241
+ #define PyInit_etree() __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyInit_etree())
242
+ #endif
243
+
244
+ #endif /* !__PYX_HAVE__lxml__etree */
.venv/lib/python3.12/site-packages/lxml/lxml.etree_api.h ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Generated by Cython 3.2.9 */
2
+
3
+ #ifndef __PYX_HAVE_API__lxml__etree
4
+ #define __PYX_HAVE_API__lxml__etree
5
+ #ifdef __MINGW64__
6
+ #define MS_WIN64
7
+ #endif
8
+ #include "Python.h"
9
+ #include "lxml.etree.h"
10
+
11
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0;
12
+ #define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument
13
+ static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0;
14
+ #define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory
15
+ static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0;
16
+ #define newElementTree __pyx_api_f_4lxml_5etree_newElementTree
17
+ static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0;
18
+ #define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument
19
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0;
20
+ #define elementFactory __pyx_api_f_4lxml_5etree_elementFactory
21
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
22
+ #define makeElement __pyx_api_f_4lxml_5etree_makeElement
23
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
24
+ #define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement
25
+ static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0;
26
+ #define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction
27
+ static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
28
+ #define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass
29
+ static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
30
+ #define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass
31
+ static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0;
32
+ #define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback
33
+ static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
34
+ #define tagMatches __pyx_api_f_4lxml_5etree_tagMatches
35
+ static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0;
36
+ #define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise
37
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0;
38
+ #define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise
39
+ static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0;
40
+ #define hasText __pyx_api_f_4lxml_5etree_hasText
41
+ static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0;
42
+ #define hasTail __pyx_api_f_4lxml_5etree_hasTail
43
+ static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0;
44
+ #define textOf __pyx_api_f_4lxml_5etree_textOf
45
+ static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0;
46
+ #define tailOf __pyx_api_f_4lxml_5etree_tailOf
47
+ static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0;
48
+ #define setNodeText __pyx_api_f_4lxml_5etree_setNodeText
49
+ static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0;
50
+ #define setTailText __pyx_api_f_4lxml_5etree_setTailText
51
+ static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0;
52
+ #define attributeValue __pyx_api_f_4lxml_5etree_attributeValue
53
+ static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
54
+ #define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName
55
+ static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
56
+ #define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue
57
+ static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0;
58
+ #define iterattributes __pyx_api_f_4lxml_5etree_iterattributes
59
+ static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0;
60
+ #define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes
61
+ static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
62
+ #define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue
63
+ static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0;
64
+ #define delAttribute __pyx_api_f_4lxml_5etree_delAttribute
65
+ static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
66
+ #define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName
67
+ static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0;
68
+ #define hasChild __pyx_api_f_4lxml_5etree_hasChild
69
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0;
70
+ #define findChild __pyx_api_f_4lxml_5etree_findChild
71
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0;
72
+ #define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards
73
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0;
74
+ #define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards
75
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0;
76
+ #define nextElement __pyx_api_f_4lxml_5etree_nextElement
77
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0;
78
+ #define previousElement __pyx_api_f_4lxml_5etree_previousElement
79
+ static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0;
80
+ #define appendChild __pyx_api_f_4lxml_5etree_appendChild
81
+ static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0;
82
+ #define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement
83
+ static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0;
84
+ #define pyunicode __pyx_api_f_4lxml_5etree_pyunicode
85
+ static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0;
86
+ #define utf8 __pyx_api_f_4lxml_5etree_utf8
87
+ static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0;
88
+ #define getNsTag __pyx_api_f_4lxml_5etree_getNsTag
89
+ static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0;
90
+ #define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs
91
+ static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0;
92
+ #define namespacedName __pyx_api_f_4lxml_5etree_namespacedName
93
+ static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0;
94
+ #define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName
95
+ static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0;
96
+ #define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext
97
+ static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0;
98
+ #define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch
99
+ static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0;
100
+ #define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix
101
+ static int __Pyx_ImportFunction_3_2_9(PyObject *module, const char *funcname, void (**f)(void), const char *sig);
102
+
103
+ #ifndef __PYX_HAVE_RT_ImportFromPxd_3_2_9
104
+ #define __PYX_HAVE_RT_ImportFromPxd_3_2_9
105
+ static int __Pyx_ImportFromPxd_3_2_9(PyObject *module, const char *name, void **p, const char *sig, const char *what) {
106
+ PyObject *d = 0;
107
+ PyObject *cobj = 0;
108
+ d = PyObject_GetAttrString(module, "__pyx_capi__");
109
+ if (!d)
110
+ goto bad;
111
+ #if (defined(Py_LIMITED_API) && Py_LIMITED_API >= 0x030d0000) || (!defined(Py_LIMITED_API) && PY_VERSION_HEX >= 0x030d0000)
112
+ PyDict_GetItemStringRef(d, name, &cobj);
113
+ #else
114
+ cobj = PyDict_GetItemString(d, name);
115
+ Py_XINCREF(cobj);
116
+ #endif
117
+ if (!cobj) {
118
+ PyErr_Format(PyExc_ImportError,
119
+ "%.200s does not export expected C %.8s %.200s",
120
+ PyModule_GetName(module), what, name);
121
+ goto bad;
122
+ }
123
+ if (!PyCapsule_IsValid(cobj, sig)) {
124
+ PyErr_Format(PyExc_TypeError,
125
+ "C %.8s %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
126
+ what, PyModule_GetName(module), name, sig, PyCapsule_GetName(cobj));
127
+ goto bad;
128
+ }
129
+ *p = PyCapsule_GetPointer(cobj, sig);
130
+ if (!(*p))
131
+ goto bad;
132
+ Py_DECREF(d);
133
+ Py_DECREF(cobj);
134
+ return 0;
135
+ bad:
136
+ Py_XDECREF(d);
137
+ Py_XDECREF(cobj);
138
+ return -1;
139
+ }
140
+ #endif
141
+
142
+ #ifndef __PYX_HAVE_RT_ImportFunction_3_2_9
143
+ #define __PYX_HAVE_RT_ImportFunction_3_2_9
144
+ static int __Pyx_ImportFunction_3_2_9(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
145
+ union {
146
+ void (*fp)(void);
147
+ void *p;
148
+ } tmp;
149
+ int result = __Pyx_ImportFromPxd_3_2_9(module, funcname, &tmp.p, sig, "function");
150
+ if (result == 0) {
151
+ *f = tmp.fp;
152
+ }
153
+ return result;
154
+ }
155
+ #endif
156
+
157
+
158
+ static int import_lxml__etree(void) {
159
+ PyObject *module = 0;
160
+ module = PyImport_ImportModule("lxml.etree");
161
+ if (!module) goto bad;
162
+ if (__Pyx_ImportFunction_3_2_9(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
163
+ if (__Pyx_ImportFunction_3_2_9(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad;
164
+ if (__Pyx_ImportFunction_3_2_9(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad;
165
+ if (__Pyx_ImportFunction_3_2_9(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad;
166
+ if (__Pyx_ImportFunction_3_2_9(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
167
+ if (__Pyx_ImportFunction_3_2_9(module, "makeElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeElement, "struct LxmlElement *(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
168
+ if (__Pyx_ImportFunction_3_2_9(module, "makeSubElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeSubElement, "struct LxmlElement *(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
169
+ if (__Pyx_ImportFunction_3_2_9(module, "setElementClassLookupFunction", (void (**)(void))&__pyx_api_f_4lxml_5etree_setElementClassLookupFunction, "void (_element_class_lookup_function, PyObject *)") < 0) goto bad;
170
+ if (__Pyx_ImportFunction_3_2_9(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
171
+ if (__Pyx_ImportFunction_3_2_9(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
172
+ if (__Pyx_ImportFunction_3_2_9(module, "callLookupFallback", (void (**)(void))&__pyx_api_f_4lxml_5etree_callLookupFallback, "PyObject *(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *)") < 0) goto bad;
173
+ if (__Pyx_ImportFunction_3_2_9(module, "tagMatches", (void (**)(void))&__pyx_api_f_4lxml_5etree_tagMatches, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
174
+ if (__Pyx_ImportFunction_3_2_9(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad;
175
+ if (__Pyx_ImportFunction_3_2_9(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad;
176
+ if (__Pyx_ImportFunction_3_2_9(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad;
177
+ if (__Pyx_ImportFunction_3_2_9(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad;
178
+ if (__Pyx_ImportFunction_3_2_9(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad;
179
+ if (__Pyx_ImportFunction_3_2_9(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad;
180
+ if (__Pyx_ImportFunction_3_2_9(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad;
181
+ if (__Pyx_ImportFunction_3_2_9(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad;
182
+ if (__Pyx_ImportFunction_3_2_9(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad;
183
+ if (__Pyx_ImportFunction_3_2_9(module, "attributeValueFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValueFromNsName, "PyObject *(xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
184
+ if (__Pyx_ImportFunction_3_2_9(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
185
+ if (__Pyx_ImportFunction_3_2_9(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad;
186
+ if (__Pyx_ImportFunction_3_2_9(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad;
187
+ if (__Pyx_ImportFunction_3_2_9(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
188
+ if (__Pyx_ImportFunction_3_2_9(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad;
189
+ if (__Pyx_ImportFunction_3_2_9(module, "delAttributeFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttributeFromNsName, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
190
+ if (__Pyx_ImportFunction_3_2_9(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad;
191
+ if (__Pyx_ImportFunction_3_2_9(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
192
+ if (__Pyx_ImportFunction_3_2_9(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
193
+ if (__Pyx_ImportFunction_3_2_9(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
194
+ if (__Pyx_ImportFunction_3_2_9(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad;
195
+ if (__Pyx_ImportFunction_3_2_9(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad;
196
+ if (__Pyx_ImportFunction_3_2_9(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
197
+ if (__Pyx_ImportFunction_3_2_9(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
198
+ if (__Pyx_ImportFunction_3_2_9(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad;
199
+ if (__Pyx_ImportFunction_3_2_9(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad;
200
+ if (__Pyx_ImportFunction_3_2_9(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad;
201
+ if (__Pyx_ImportFunction_3_2_9(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad;
202
+ if (__Pyx_ImportFunction_3_2_9(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad;
203
+ if (__Pyx_ImportFunction_3_2_9(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad;
204
+ if (__Pyx_ImportFunction_3_2_9(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad;
205
+ if (__Pyx_ImportFunction_3_2_9(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad;
206
+ if (__Pyx_ImportFunction_3_2_9(module, "findOrBuildNodeNsPrefix", (void (**)(void))&__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix, "xmlNs *(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
207
+ Py_DECREF(module); module = 0;
208
+ return 0;
209
+ bad:
210
+ Py_XDECREF(module);
211
+ return -1;
212
+ }
213
+
214
+ #endif /* !__PYX_HAVE_API__lxml__etree */
.venv/lib/python3.12/site-packages/lxml/nsclasses.pxi ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # module-level API for namespace implementations
2
+
3
+ cdef class LxmlRegistryError(LxmlError):
4
+ """Base class of lxml registry errors.
5
+ """
6
+
7
+ cdef class NamespaceRegistryError(LxmlRegistryError):
8
+ """Error registering a namespace extension.
9
+ """
10
+
11
+
12
+ @cython.internal
13
+ cdef class _NamespaceRegistry:
14
+ "Dictionary-like namespace registry"
15
+ cdef object _ns_uri
16
+ cdef bytes _ns_uri_utf
17
+ cdef dict _entries
18
+ cdef char* _c_ns_uri_utf
19
+ def __cinit__(self, ns_uri):
20
+ self._ns_uri = ns_uri
21
+ if ns_uri is None:
22
+ self._ns_uri_utf = None
23
+ self._c_ns_uri_utf = NULL
24
+ else:
25
+ self._ns_uri_utf = _utf8(ns_uri)
26
+ self._c_ns_uri_utf = _cstr(self._ns_uri_utf)
27
+ self._entries = {}
28
+
29
+ def update(self, class_dict_iterable):
30
+ """update(self, class_dict_iterable)
31
+
32
+ Forgivingly update the registry.
33
+
34
+ ``class_dict_iterable`` may be a dict or some other iterable
35
+ that yields (name, value) pairs.
36
+
37
+ If a value does not match the required type for this registry,
38
+ or if the name starts with '_', it will be silently discarded.
39
+ This allows registrations at the module or class level using
40
+ vars(), globals() etc."""
41
+ if hasattr(class_dict_iterable, 'items'):
42
+ class_dict_iterable = class_dict_iterable.items()
43
+ for name, item in class_dict_iterable:
44
+ if (name is None or name[:1] != '_') and callable(item):
45
+ self[name] = item
46
+
47
+ def __getitem__(self, name):
48
+ if name is not None:
49
+ name = _utf8(name)
50
+ return self._get(name)
51
+
52
+ def __delitem__(self, name):
53
+ if name is not None:
54
+ name = _utf8(name)
55
+ del self._entries[name]
56
+
57
+ cdef object _get(self, object name):
58
+ cdef python.PyObject* dict_result
59
+ dict_result = python.PyDict_GetItem(self._entries, name)
60
+ if dict_result is NULL:
61
+ raise KeyError, "Name not registered."
62
+ return <object>dict_result
63
+
64
+ cdef object _getForString(self, char* name):
65
+ cdef python.PyObject* dict_result
66
+ dict_result = python.PyDict_GetItem(self._entries, name)
67
+ if dict_result is NULL:
68
+ raise KeyError, "Name not registered."
69
+ return <object>dict_result
70
+
71
+ def __iter__(self):
72
+ return iter(self._entries)
73
+
74
+ def items(self):
75
+ return list(self._entries.items())
76
+
77
+ def iteritems(self):
78
+ return iter(self._entries.items())
79
+
80
+ def clear(self):
81
+ self._entries.clear()
82
+
83
+ def __call__(self, obj):
84
+ # Usage as decorator:
85
+ # ns = lookup.get_namespace("...")
86
+ # @ns('abc')
87
+ # class element(ElementBase): pass
88
+ #
89
+ # @ns
90
+ # class elementname(ElementBase): pass
91
+
92
+ if obj is None or python._isString(obj):
93
+ # @ns(None) or @ns('tag')
94
+ return partial(self.__deco, obj)
95
+ # plain @ns decorator
96
+ self[obj.__name__] = obj
97
+ return obj
98
+
99
+ def __deco(self, name, obj):
100
+ self[name] = obj
101
+ return obj
102
+
103
+
104
+ @cython.final
105
+ @cython.internal
106
+ cdef class _ClassNamespaceRegistry(_NamespaceRegistry):
107
+ "Dictionary-like registry for namespace implementation classes"
108
+ def __setitem__(self, name, item):
109
+ if not isinstance(item, type) or not issubclass(item, ElementBase):
110
+ raise NamespaceRegistryError, \
111
+ "Registered element classes must be subtypes of ElementBase"
112
+ if name is not None:
113
+ name = _utf8(name)
114
+ self._entries[name] = item
115
+
116
+ def __repr__(self):
117
+ return "Namespace(%r)" % self._ns_uri
118
+
119
+
120
+ cdef class ElementNamespaceClassLookup(FallbackElementClassLookup):
121
+ """ElementNamespaceClassLookup(self, fallback=None)
122
+
123
+ Element class lookup scheme that searches the Element class in the
124
+ Namespace registry.
125
+
126
+ Usage:
127
+
128
+ >>> lookup = ElementNamespaceClassLookup()
129
+ >>> ns_elements = lookup.get_namespace("http://schema.org/Movie")
130
+
131
+ >>> @ns_elements
132
+ ... class movie(ElementBase):
133
+ ... "Element implementation for 'movie' tag (using class name) in schema namespace."
134
+
135
+ >>> @ns_elements("movie")
136
+ ... class MovieElement(ElementBase):
137
+ ... "Element implementation for 'movie' tag (explicit tag name) in schema namespace."
138
+ """
139
+ cdef dict _namespace_registries
140
+ def __cinit__(self):
141
+ self._namespace_registries = {}
142
+
143
+ def __init__(self, ElementClassLookup fallback=None):
144
+ FallbackElementClassLookup.__init__(self, fallback)
145
+ self._lookup_function = _find_nselement_class
146
+
147
+ def get_namespace(self, ns_uri):
148
+ """get_namespace(self, ns_uri)
149
+
150
+ Retrieve the namespace object associated with the given URI.
151
+ Pass None for the empty namespace.
152
+
153
+ Creates a new namespace object if it does not yet exist."""
154
+ if ns_uri:
155
+ ns_utf = _utf8(ns_uri)
156
+ else:
157
+ ns_utf = None
158
+ try:
159
+ return self._namespace_registries[ns_utf]
160
+ except KeyError:
161
+ registry = self._namespace_registries[ns_utf] = \
162
+ _ClassNamespaceRegistry(ns_uri)
163
+ return registry
164
+
165
+ cdef object _find_nselement_class(state, _Document doc, xmlNode* c_node):
166
+ cdef python.PyObject* dict_result
167
+ cdef ElementNamespaceClassLookup lookup
168
+ cdef _NamespaceRegistry registry
169
+ if state is None:
170
+ return _lookupDefaultElementClass(None, doc, c_node)
171
+
172
+ lookup = <ElementNamespaceClassLookup>state
173
+ if c_node.type != tree.XML_ELEMENT_NODE:
174
+ return _callLookupFallback(lookup, doc, c_node)
175
+
176
+ c_namespace_utf = _getNs(c_node)
177
+ if c_namespace_utf is not NULL:
178
+ dict_result = python.PyDict_GetItem(
179
+ lookup._namespace_registries, <unsigned char*>c_namespace_utf)
180
+ else:
181
+ dict_result = python.PyDict_GetItem(
182
+ lookup._namespace_registries, None)
183
+ if dict_result is not NULL:
184
+ registry = <_NamespaceRegistry>dict_result
185
+ classes = registry._entries
186
+
187
+ if c_node.name is not NULL:
188
+ dict_result = python.PyDict_GetItem(
189
+ classes, <unsigned char*>c_node.name)
190
+ else:
191
+ dict_result = NULL
192
+
193
+ if dict_result is NULL:
194
+ dict_result = python.PyDict_GetItem(classes, None)
195
+
196
+ if dict_result is not NULL:
197
+ return <object>dict_result
198
+ return _callLookupFallback(lookup, doc, c_node)
199
+
200
+
201
+ ################################################################################
202
+ # XPath extension functions
203
+
204
+ cdef dict __FUNCTION_NAMESPACE_REGISTRIES
205
+ __FUNCTION_NAMESPACE_REGISTRIES = {}
206
+
207
+ def FunctionNamespace(ns_uri):
208
+ """FunctionNamespace(ns_uri)
209
+
210
+ Retrieve the function namespace object associated with the given
211
+ URI.
212
+
213
+ Creates a new one if it does not yet exist. A function namespace
214
+ can only be used to register extension functions.
215
+
216
+ Usage:
217
+
218
+ >>> ns_functions = FunctionNamespace("http://schema.org/Movie")
219
+
220
+ >>> @ns_functions # uses function name
221
+ ... def add2(x):
222
+ ... return x + 2
223
+
224
+ >>> @ns_functions("add3") # uses explicit name
225
+ ... def add_three(x):
226
+ ... return x + 3
227
+ """
228
+ ns_utf = _utf8(ns_uri) if ns_uri else None
229
+ try:
230
+ return __FUNCTION_NAMESPACE_REGISTRIES[ns_utf]
231
+ except KeyError:
232
+ registry = __FUNCTION_NAMESPACE_REGISTRIES[ns_utf] = \
233
+ _XPathFunctionNamespaceRegistry(ns_uri)
234
+ return registry
235
+
236
+ @cython.internal
237
+ cdef class _FunctionNamespaceRegistry(_NamespaceRegistry):
238
+ def __setitem__(self, name, item):
239
+ if not callable(item):
240
+ raise NamespaceRegistryError, \
241
+ "Registered functions must be callable."
242
+ if not name:
243
+ raise ValueError, \
244
+ "extensions must have non empty names"
245
+ self._entries[_utf8(name)] = item
246
+
247
+ def __repr__(self):
248
+ return "FunctionNamespace(%r)" % self._ns_uri
249
+
250
+ @cython.final
251
+ @cython.internal
252
+ cdef class _XPathFunctionNamespaceRegistry(_FunctionNamespaceRegistry):
253
+ cdef object _prefix
254
+ cdef bytes _prefix_utf
255
+
256
+ property prefix:
257
+ "Namespace prefix for extension functions."
258
+ def __del__(self):
259
+ self._prefix = None # no prefix configured
260
+ self._prefix_utf = None
261
+ def __get__(self):
262
+ if self._prefix is None:
263
+ return ''
264
+ else:
265
+ return self._prefix
266
+ def __set__(self, prefix):
267
+ if prefix == '':
268
+ prefix = None # empty prefix
269
+ self._prefix_utf = _utf8(prefix) if prefix is not None else None
270
+ self._prefix = prefix
271
+
272
+ cdef list _find_all_extension_prefixes():
273
+ "Internal lookup function to find all function prefixes for XSLT/XPath."
274
+ cdef _XPathFunctionNamespaceRegistry registry
275
+ cdef list ns_prefixes = []
276
+ for registry in __FUNCTION_NAMESPACE_REGISTRIES.itervalues():
277
+ if registry._prefix_utf is not None:
278
+ if registry._ns_uri_utf is not None:
279
+ ns_prefixes.append(
280
+ (registry._prefix_utf, registry._ns_uri_utf))
281
+ return ns_prefixes
.venv/lib/python3.12/site-packages/lxml/objectify.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e0bbc24c44024d06c001a5e399143ebac39c5218da976c5a2d8a0b4ea14cb569
3
+ size 2920920
.venv/lib/python3.12/site-packages/lxml/objectify.pyx ADDED
@@ -0,0 +1,2148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: binding=True
2
+ # cython: auto_pickle=False
3
+ # cython: language_level=3
4
+
5
+ """
6
+ The ``lxml.objectify`` module implements a Python object API for XML.
7
+ It is based on `lxml.etree`.
8
+ """
9
+
10
+ cimport cython
11
+
12
+ from lxml.includes.etreepublic cimport _Document, _Element, ElementBase, ElementClassLookup
13
+ from lxml.includes.etreepublic cimport elementFactory, import_lxml__etree, textOf, pyunicode
14
+ from lxml.includes.tree cimport const_xmlChar, _xcstr
15
+ from lxml cimport python
16
+ from lxml.includes cimport tree
17
+
18
+ cimport lxml.includes.etreepublic as cetree
19
+ cimport libc.string as cstring_h # not to be confused with stdlib 'string'
20
+ from libc.string cimport const_char
21
+ from libc cimport limits
22
+
23
+ __all__ = ['BoolElement', 'DataElement', 'E', 'Element', 'ElementMaker',
24
+ 'FloatElement', 'IntElement', 'NoneElement',
25
+ 'NumberElement', 'ObjectPath', 'ObjectifiedDataElement',
26
+ 'ObjectifiedElement', 'ObjectifyElementClassLookup',
27
+ 'PYTYPE_ATTRIBUTE', 'PyType', 'StringElement', 'SubElement',
28
+ 'XML', 'annotate', 'deannotate', 'dump', 'enable_recursive_str',
29
+ 'fromstring', 'getRegisteredTypes', 'makeparser', 'parse',
30
+ 'pyannotate', 'pytypename', 'set_default_parser',
31
+ 'set_pytype_attribute_tag', 'xsiannotate']
32
+
33
+ cdef object etree
34
+ from lxml import etree
35
+ # initialize C-API of lxml.etree
36
+ import_lxml__etree()
37
+
38
+ __version__ = etree.__version__
39
+
40
+ cdef object _float_is_inf, _float_is_nan
41
+ from math import isinf as _float_is_inf, isnan as _float_is_nan
42
+
43
+ cdef object re
44
+ import re
45
+
46
+ cdef tuple IGNORABLE_ERRORS = (ValueError, TypeError)
47
+ cdef object is_special_method = re.compile('__.*__$').match
48
+
49
+
50
+ cdef object _typename(object t):
51
+ cdef const_char* c_name
52
+ c_name = python._fqtypename(t)
53
+ s = cstring_h.strrchr(c_name, c'.')
54
+ if s is not NULL:
55
+ c_name = s + 1
56
+ return pyunicode(<const_xmlChar*>c_name)
57
+
58
+
59
+ # namespace/name for "pytype" hint attribute
60
+ cdef object PYTYPE_NAMESPACE
61
+ cdef bytes PYTYPE_NAMESPACE_UTF8
62
+ cdef const_xmlChar* _PYTYPE_NAMESPACE
63
+
64
+ cdef object PYTYPE_ATTRIBUTE_NAME
65
+ cdef bytes PYTYPE_ATTRIBUTE_NAME_UTF8
66
+ cdef const_xmlChar* _PYTYPE_ATTRIBUTE_NAME
67
+
68
+ PYTYPE_ATTRIBUTE = None
69
+
70
+ cdef unicode TREE_PYTYPE_NAME = "TREE"
71
+
72
+ cdef tuple _unicodeAndUtf8(s):
73
+ return s, python.PyUnicode_AsUTF8String(s)
74
+
75
+ def set_pytype_attribute_tag(attribute_tag=None):
76
+ """set_pytype_attribute_tag(attribute_tag=None)
77
+ Change name and namespace of the XML attribute that holds Python type
78
+ information.
79
+
80
+ Do not use this unless you know what you are doing.
81
+
82
+ Reset by calling without argument.
83
+
84
+ Default: "{http://codespeak.net/lxml/objectify/pytype}pytype"
85
+ """
86
+ global PYTYPE_ATTRIBUTE, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME
87
+ global PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8
88
+ global PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8
89
+ if attribute_tag is None:
90
+ PYTYPE_NAMESPACE, PYTYPE_NAMESPACE_UTF8 = \
91
+ _unicodeAndUtf8("http://codespeak.net/lxml/objectify/pytype")
92
+ PYTYPE_ATTRIBUTE_NAME, PYTYPE_ATTRIBUTE_NAME_UTF8 = \
93
+ _unicodeAndUtf8("pytype")
94
+ else:
95
+ PYTYPE_NAMESPACE_UTF8, PYTYPE_ATTRIBUTE_NAME_UTF8 = \
96
+ cetree.getNsTag(attribute_tag)
97
+ PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8.decode('utf8')
98
+ PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8.decode('utf8')
99
+
100
+ _PYTYPE_NAMESPACE = PYTYPE_NAMESPACE_UTF8
101
+ _PYTYPE_ATTRIBUTE_NAME = PYTYPE_ATTRIBUTE_NAME_UTF8
102
+ PYTYPE_ATTRIBUTE = cetree.namespacedNameFromNsName(
103
+ _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
104
+
105
+ set_pytype_attribute_tag()
106
+
107
+
108
+ # namespaces for XML Schema
109
+ cdef object XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8
110
+ XML_SCHEMA_NS, XML_SCHEMA_NS_UTF8 = \
111
+ _unicodeAndUtf8("http://www.w3.org/2001/XMLSchema")
112
+ cdef const_xmlChar* _XML_SCHEMA_NS = _xcstr(XML_SCHEMA_NS_UTF8)
113
+
114
+ cdef object XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8
115
+ XML_SCHEMA_INSTANCE_NS, XML_SCHEMA_INSTANCE_NS_UTF8 = \
116
+ _unicodeAndUtf8("http://www.w3.org/2001/XMLSchema-instance")
117
+ cdef const_xmlChar* _XML_SCHEMA_INSTANCE_NS = _xcstr(XML_SCHEMA_INSTANCE_NS_UTF8)
118
+
119
+ cdef object XML_SCHEMA_INSTANCE_NIL_ATTR = "{%s}nil" % XML_SCHEMA_INSTANCE_NS
120
+ cdef object XML_SCHEMA_INSTANCE_TYPE_ATTR = "{%s}type" % XML_SCHEMA_INSTANCE_NS
121
+
122
+
123
+ ################################################################################
124
+ # Element class for the main API
125
+
126
+ cdef class ObjectifiedElement(ElementBase):
127
+ """Main XML Element class.
128
+
129
+ Element children are accessed as object attributes. Multiple children
130
+ with the same name are available through a list index. Example::
131
+
132
+ >>> root = XML("<root><c1><c2>0</c2><c2>1</c2></c1></root>")
133
+ >>> second_c2 = root.c1.c2[1]
134
+ >>> print(second_c2.text)
135
+ 1
136
+
137
+ Note that you cannot (and must not) instantiate this class or its
138
+ subclasses.
139
+ """
140
+ def __iter__(self):
141
+ """Iterate over self and all siblings with the same tag.
142
+ """
143
+ parent = self.getparent()
144
+ if parent is None:
145
+ return iter([self])
146
+ return etree.ElementChildIterator(parent, tag=self.tag)
147
+
148
+ def __str__(self):
149
+ if __RECURSIVE_STR:
150
+ return _dump(self, 0)
151
+ else:
152
+ return textOf(self._c_node) or ''
153
+
154
+ # pickle support for objectified Element
155
+ def __reduce__(self):
156
+ return fromstring, (etree.tostring(self),)
157
+
158
+ @property
159
+ def text(self):
160
+ return textOf(self._c_node)
161
+
162
+ @property
163
+ def __dict__(self):
164
+ """A fake implementation for __dict__ to support dir() etc.
165
+
166
+ Note that this only considers the first child with a given name.
167
+ """
168
+ cdef _Element child
169
+ cdef dict children
170
+ c_ns = tree._getNs(self._c_node)
171
+ tag = "{%s}*" % pyunicode(c_ns) if c_ns is not NULL else None
172
+ children = {}
173
+ for child in etree.ElementChildIterator(self, tag=tag):
174
+ if c_ns is NULL and tree._getNs(child._c_node) is not NULL:
175
+ continue
176
+ name = pyunicode(child._c_node.name)
177
+ if name not in children:
178
+ children[name] = child
179
+ return children
180
+
181
+ def __len__(self):
182
+ """Count self and siblings with the same tag.
183
+ """
184
+ return _countSiblings(self._c_node)
185
+
186
+ def countchildren(self):
187
+ """countchildren(self)
188
+
189
+ Return the number of children of this element, regardless of their
190
+ name.
191
+ """
192
+ # copied from etree
193
+ cdef Py_ssize_t c
194
+ cdef tree.xmlNode* c_node
195
+ c = 0
196
+ c_node = self._c_node.children
197
+ while c_node is not NULL:
198
+ if tree._isElement(c_node):
199
+ c += 1
200
+ c_node = c_node.next
201
+ return c
202
+
203
+ def getchildren(self):
204
+ """getchildren(self)
205
+
206
+ Returns a sequence of all direct children. The elements are
207
+ returned in document order.
208
+ """
209
+ cdef tree.xmlNode* c_node
210
+ result = []
211
+ c_node = self._c_node.children
212
+ while c_node is not NULL:
213
+ if tree._isElement(c_node):
214
+ result.append(cetree.elementFactory(self._doc, c_node))
215
+ c_node = c_node.next
216
+ return result
217
+
218
+ def __getattr__(self, tag):
219
+ """Return the (first) child with the given tag name. If no namespace
220
+ is provided, the child will be looked up in the same one as self.
221
+ """
222
+ return _lookupChildOrRaise(self, tag)
223
+
224
+ def __setattr__(self, tag, value):
225
+ """Set the value of the (first) child with the given tag name. If no
226
+ namespace is provided, the child will be looked up in the same one as
227
+ self.
228
+ """
229
+ cdef _Element element
230
+ # properties are looked up /after/ __setattr__, so we must emulate them
231
+ if tag == 'text' or tag == 'pyval':
232
+ # read-only !
233
+ raise TypeError, f"attribute '{tag}' of '{_typename(self)}' objects is not writable"
234
+ elif tag == 'tail':
235
+ cetree.setTailText(self._c_node, value)
236
+ return
237
+ elif tag == 'tag':
238
+ ElementBase.tag.__set__(self, value)
239
+ return
240
+ elif tag == 'base':
241
+ ElementBase.base.__set__(self, value)
242
+ return
243
+ tag = _buildChildTag(self, tag)
244
+ element = _lookupChild(self, tag)
245
+ if element is None:
246
+ _appendValue(self, tag, value)
247
+ else:
248
+ _replaceElement(element, value)
249
+
250
+ def __delattr__(self, tag):
251
+ child = _lookupChildOrRaise(self, tag)
252
+ self.remove(child)
253
+
254
+ def addattr(self, tag, value):
255
+ """addattr(self, tag, value)
256
+
257
+ Add a child value to the element.
258
+
259
+ As opposed to append(), it sets a data value, not an element.
260
+ """
261
+ _appendValue(self, _buildChildTag(self, tag), value)
262
+
263
+ def __getitem__(self, key):
264
+ """Return a sibling, counting from the first child of the parent. The
265
+ method behaves like both a dict and a sequence.
266
+
267
+ * If argument is an integer, returns the sibling at that position.
268
+
269
+ * If argument is a string, does the same as getattr(). This can be
270
+ used to provide namespaces for element lookup, or to look up
271
+ children with special names (``text`` etc.).
272
+
273
+ * If argument is a slice object, returns the matching slice.
274
+ """
275
+ cdef tree.xmlNode* c_self_node
276
+ cdef tree.xmlNode* c_parent
277
+ cdef tree.xmlNode* c_node
278
+ cdef Py_ssize_t c_index
279
+ if python._isString(key):
280
+ return _lookupChildOrRaise(self, key)
281
+ elif isinstance(key, slice):
282
+ return list(self)[key]
283
+ # normal item access
284
+ c_index = key # raises TypeError if necessary
285
+ c_self_node = self._c_node
286
+ c_parent = c_self_node.parent
287
+ if c_parent is NULL:
288
+ if c_index == 0 or c_index == -1:
289
+ return self
290
+ raise IndexError, unicode(key)
291
+ if c_index < 0:
292
+ c_node = c_parent.last
293
+ else:
294
+ c_node = c_parent.children
295
+ c_node = _findFollowingSibling(
296
+ c_node, tree._getNs(c_self_node), c_self_node.name, c_index)
297
+ if c_node is NULL:
298
+ raise IndexError, unicode(key)
299
+ return elementFactory(self._doc, c_node)
300
+
301
+ def __setitem__(self, key, value):
302
+ """Set the value of a sibling, counting from the first child of the
303
+ parent. Implements key assignment, item assignment and slice
304
+ assignment.
305
+
306
+ * If argument is an integer, sets the sibling at that position.
307
+
308
+ * If argument is a string, does the same as setattr(). This is used
309
+ to provide namespaces for element lookup.
310
+
311
+ * If argument is a sequence (list, tuple, etc.), assign the contained
312
+ items to the siblings.
313
+ """
314
+ cdef _Element element
315
+ cdef tree.xmlNode* c_node
316
+ if python._isString(key):
317
+ key = _buildChildTag(self, key)
318
+ element = _lookupChild(self, key)
319
+ if element is None:
320
+ _appendValue(self, key, value)
321
+ else:
322
+ _replaceElement(element, value)
323
+ return
324
+
325
+ if self._c_node.parent is NULL:
326
+ # the 'root[i] = ...' case
327
+ raise TypeError, "assignment to root element is invalid"
328
+
329
+ if isinstance(key, slice):
330
+ # slice assignment
331
+ _setSlice(key, self, value)
332
+ else:
333
+ # normal index assignment
334
+ if key < 0:
335
+ c_node = self._c_node.parent.last
336
+ else:
337
+ c_node = self._c_node.parent.children
338
+ c_node = _findFollowingSibling(
339
+ c_node, tree._getNs(self._c_node), self._c_node.name, key)
340
+ if c_node is NULL:
341
+ raise IndexError, unicode(key)
342
+ element = elementFactory(self._doc, c_node)
343
+ _replaceElement(element, value)
344
+
345
+ def __delitem__(self, key):
346
+ parent = self.getparent()
347
+ if parent is None:
348
+ raise TypeError, "deleting items not supported by root element"
349
+ if isinstance(key, slice):
350
+ # slice deletion
351
+ del_items = list(self)[key]
352
+ remove = parent.remove
353
+ for el in del_items:
354
+ remove(el)
355
+ else:
356
+ # normal index deletion
357
+ sibling = self.__getitem__(key)
358
+ parent.remove(sibling)
359
+
360
+ def descendantpaths(self, prefix=None):
361
+ """descendantpaths(self, prefix=None)
362
+
363
+ Returns a list of object path expressions for all descendants.
364
+ """
365
+ if prefix is not None and not python._isString(prefix):
366
+ prefix = '.'.join(prefix)
367
+ return _build_descendant_paths(self._c_node, prefix)
368
+
369
+
370
+ cdef inline bint _tagMatches(tree.xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
371
+ if c_node.name != c_name:
372
+ return 0
373
+ if c_href == NULL:
374
+ return 1
375
+ c_node_href = tree._getNs(c_node)
376
+ if c_node_href == NULL:
377
+ return c_href[0] == c'\0'
378
+ return tree.xmlStrcmp(c_node_href, c_href) == 0
379
+
380
+
381
+ cdef Py_ssize_t _countSiblings(tree.xmlNode* c_start_node) noexcept:
382
+ cdef tree.xmlNode* c_node
383
+ cdef Py_ssize_t count
384
+ c_tag = c_start_node.name
385
+ c_href = tree._getNs(c_start_node)
386
+ count = 1
387
+ c_node = c_start_node.next
388
+ while c_node is not NULL:
389
+ if c_node.type == tree.XML_ELEMENT_NODE and \
390
+ _tagMatches(c_node, c_href, c_tag):
391
+ count += 1
392
+ c_node = c_node.next
393
+ c_node = c_start_node.prev
394
+ while c_node is not NULL:
395
+ if c_node.type == tree.XML_ELEMENT_NODE and \
396
+ _tagMatches(c_node, c_href, c_tag):
397
+ count += 1
398
+ c_node = c_node.prev
399
+ return count
400
+
401
+ cdef tree.xmlNode* _findFollowingSibling(tree.xmlNode* c_node,
402
+ const_xmlChar* href, const_xmlChar* name,
403
+ Py_ssize_t index) noexcept:
404
+ if index >= 0:
405
+ next = cetree.nextElement
406
+ else:
407
+ index = -1 - index
408
+ next = cetree.previousElement
409
+ while c_node is not NULL:
410
+ if c_node.type == tree.XML_ELEMENT_NODE and \
411
+ _tagMatches(c_node, href, name):
412
+ index = index - 1
413
+ if index < 0:
414
+ return c_node
415
+ c_node = next(c_node)
416
+ return NULL
417
+
418
+ cdef object _lookupChild(_Element parent, tag):
419
+ cdef tree.xmlNode* c_result
420
+ cdef tree.xmlNode* c_node
421
+ c_node = parent._c_node
422
+ ns, tag = cetree.getNsTagWithEmptyNs(tag)
423
+ c_tag_len = len(<bytes> tag)
424
+ if c_tag_len > limits.INT_MAX:
425
+ return None
426
+ c_tag = tree.xmlDictExists(
427
+ c_node.doc.dict, _xcstr(tag), <int> c_tag_len)
428
+ if c_tag is NULL:
429
+ return None # not in the hash map => not in the tree
430
+ if ns is None:
431
+ # either inherit ns from parent or use empty (i.e. no) namespace
432
+ c_href = tree._getNs(c_node) or <const_xmlChar*>''
433
+ else:
434
+ c_href = _xcstr(ns)
435
+ c_result = _findFollowingSibling(c_node.children, c_href, c_tag, 0)
436
+ if c_result is NULL:
437
+ return None
438
+ return elementFactory(parent._doc, c_result)
439
+
440
+ cdef object _lookupChildOrRaise(_Element parent, tag):
441
+ element = _lookupChild(parent, tag)
442
+ if element is None:
443
+ raise AttributeError, "no such child: " + _buildChildTag(parent, tag)
444
+ return element
445
+
446
+ cdef object _buildChildTag(_Element parent, tag):
447
+ ns, tag = cetree.getNsTag(tag)
448
+ c_tag = _xcstr(tag)
449
+ c_href = tree._getNs(parent._c_node) if ns is None else _xcstr(ns)
450
+ return cetree.namespacedNameFromNsName(c_href, c_tag)
451
+
452
+ cdef _replaceElement(_Element element, value):
453
+ cdef _Element new_element
454
+ if isinstance(value, _Element):
455
+ # deep copy the new element
456
+ new_element = cetree.deepcopyNodeToDocument(
457
+ element._doc, (<_Element>value)._c_node)
458
+ new_element.tag = element.tag
459
+ elif isinstance(value, (list, tuple)):
460
+ element[:] = value
461
+ return
462
+ else:
463
+ new_element = element.makeelement(element.tag)
464
+ _setElementValue(new_element, value)
465
+ element.getparent().replace(element, new_element)
466
+
467
+ cdef _appendValue(_Element parent, tag, value):
468
+ cdef _Element new_element
469
+ if isinstance(value, _Element):
470
+ # deep copy the new element
471
+ new_element = cetree.deepcopyNodeToDocument(
472
+ parent._doc, (<_Element>value)._c_node)
473
+ new_element.tag = tag
474
+ cetree.appendChildToElement(parent, new_element)
475
+ elif isinstance(value, (list, tuple)):
476
+ for item in value:
477
+ _appendValue(parent, tag, item)
478
+ else:
479
+ new_element = cetree.makeElement(
480
+ tag, parent._doc, None, None, None, None, None)
481
+ _setElementValue(new_element, value)
482
+ cetree.appendChildToElement(parent, new_element)
483
+
484
+ cdef _setElementValue(_Element element, value):
485
+ if value is None:
486
+ cetree.setAttributeValue(
487
+ element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true")
488
+ elif isinstance(value, _Element):
489
+ _replaceElement(element, value)
490
+ return
491
+ else:
492
+ cetree.delAttributeFromNsName(
493
+ element._c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil")
494
+ if python._isString(value):
495
+ pytype_name = "str"
496
+ py_type = <PyType>_PYTYPE_DICT.get(pytype_name)
497
+ else:
498
+ pytype_name = _typename(value)
499
+ py_type = <PyType>_PYTYPE_DICT.get(pytype_name)
500
+ if py_type is not None:
501
+ value = py_type.stringify(value)
502
+ else:
503
+ value = unicode(value)
504
+ if py_type is not None:
505
+ cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name)
506
+ else:
507
+ cetree.delAttributeFromNsName(
508
+ element._c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
509
+ cetree.setNodeText(element._c_node, value)
510
+
511
+ cdef _setSlice(sliceobject, _Element target, items):
512
+ cdef _Element parent
513
+ cdef tree.xmlNode* c_node
514
+ cdef Py_ssize_t c_step, c_start, pos
515
+ # collect existing slice
516
+ if (<slice>sliceobject).step is None:
517
+ c_step = 1
518
+ else:
519
+ c_step = (<slice>sliceobject).step
520
+ if c_step == 0:
521
+ raise ValueError, "Invalid slice"
522
+ cdef list del_items = target[sliceobject]
523
+
524
+ # collect new values
525
+ new_items = []
526
+ tag = target.tag
527
+ for item in items:
528
+ if isinstance(item, _Element):
529
+ # deep copy the new element
530
+ new_element = cetree.deepcopyNodeToDocument(
531
+ target._doc, (<_Element>item)._c_node)
532
+ new_element.tag = tag
533
+ else:
534
+ new_element = cetree.makeElement(
535
+ tag, target._doc, None, None, None, None, None)
536
+ _setElementValue(new_element, item)
537
+ new_items.append(new_element)
538
+
539
+ # sanity check - raise what a list would raise
540
+ if c_step != 1 and len(del_items) != len(new_items):
541
+ raise ValueError, \
542
+ f"attempt to assign sequence of size {len(new_items)} to extended slice of size {len(del_items)}"
543
+
544
+ # replace existing items
545
+ pos = 0
546
+ parent = target.getparent()
547
+ replace = parent.replace
548
+ while pos < len(new_items) and pos < len(del_items):
549
+ replace(del_items[pos], new_items[pos])
550
+ pos += 1
551
+ # remove leftover items
552
+ if pos < len(del_items):
553
+ remove = parent.remove
554
+ while pos < len(del_items):
555
+ remove(del_items[pos])
556
+ pos += 1
557
+ # append remaining new items
558
+ if pos < len(new_items):
559
+ # the sanity check above guarantees (step == 1)
560
+ if pos > 0:
561
+ item = new_items[pos-1]
562
+ else:
563
+ if (<slice>sliceobject).start > 0:
564
+ c_node = parent._c_node.children
565
+ else:
566
+ c_node = parent._c_node.last
567
+ c_node = _findFollowingSibling(
568
+ c_node, tree._getNs(target._c_node), target._c_node.name,
569
+ (<slice>sliceobject).start - 1)
570
+ if c_node is NULL:
571
+ while pos < len(new_items):
572
+ cetree.appendChildToElement(parent, new_items[pos])
573
+ pos += 1
574
+ return
575
+ item = cetree.elementFactory(parent._doc, c_node)
576
+ while pos < len(new_items):
577
+ add = item.addnext
578
+ item = new_items[pos]
579
+ add(item)
580
+ pos += 1
581
+
582
+ ################################################################################
583
+ # Data type support in subclasses
584
+
585
+ cdef class ObjectifiedDataElement(ObjectifiedElement):
586
+ """This is the base class for all data type Elements. Subclasses should
587
+ override the 'pyval' property and possibly the __str__ method.
588
+ """
589
+ @property
590
+ def pyval(self):
591
+ return textOf(self._c_node)
592
+
593
+ def __str__(self):
594
+ return textOf(self._c_node) or ''
595
+
596
+ def __repr__(self):
597
+ return textOf(self._c_node) or ''
598
+
599
+ def _setText(self, s):
600
+ """For use in subclasses only. Don't use unless you know what you are
601
+ doing.
602
+ """
603
+ cetree.setNodeText(self._c_node, s)
604
+
605
+
606
+ cdef class NumberElement(ObjectifiedDataElement):
607
+ cdef object _parse_value
608
+
609
+ def _setValueParser(self, function):
610
+ """Set the function that parses the Python value from a string.
611
+
612
+ Do not use this unless you know what you are doing.
613
+ """
614
+ self._parse_value = function
615
+
616
+ @property
617
+ def pyval(self):
618
+ return _parseNumber(self)
619
+
620
+ def __int__(self):
621
+ return int(_parseNumber(self))
622
+
623
+ def __float__(self):
624
+ return float(_parseNumber(self))
625
+
626
+ def __complex__(self):
627
+ return complex(_parseNumber(self))
628
+
629
+ def __str__(self):
630
+ return unicode(_parseNumber(self))
631
+
632
+ def __repr__(self):
633
+ return repr(_parseNumber(self))
634
+
635
+ def __oct__(self):
636
+ return oct(_parseNumber(self))
637
+
638
+ def __hex__(self):
639
+ return hex(_parseNumber(self))
640
+
641
+ def __richcmp__(self, other, int op):
642
+ return _richcmpPyvals(self, other, op)
643
+
644
+ def __hash__(self):
645
+ return hash(_parseNumber(self))
646
+
647
+ def __add__(self, other):
648
+ return _numericValueOf(self) + _numericValueOf(other)
649
+
650
+ def __radd__(self, other):
651
+ return _numericValueOf(other) + _numericValueOf(self)
652
+
653
+ def __sub__(self, other):
654
+ return _numericValueOf(self) - _numericValueOf(other)
655
+
656
+ def __rsub__(self, other):
657
+ return _numericValueOf(other) - _numericValueOf(self)
658
+
659
+ def __mul__(self, other):
660
+ return _numericValueOf(self) * _numericValueOf(other)
661
+
662
+ def __rmul__(self, other):
663
+ return _numericValueOf(other) * _numericValueOf(self)
664
+
665
+ def __div__(self, other):
666
+ return _numericValueOf(self) / _numericValueOf(other)
667
+
668
+ def __rdiv__(self, other):
669
+ return _numericValueOf(other) / _numericValueOf(self)
670
+
671
+ def __truediv__(self, other):
672
+ return _numericValueOf(self) / _numericValueOf(other)
673
+
674
+ def __rtruediv__(self, other):
675
+ return _numericValueOf(other) / _numericValueOf(self)
676
+
677
+ def __floordiv__(self, other):
678
+ return _numericValueOf(self) // _numericValueOf(other)
679
+
680
+ def __rfloordiv__(self, other):
681
+ return _numericValueOf(other) // _numericValueOf(self)
682
+
683
+ def __mod__(self, other):
684
+ return _numericValueOf(self) % _numericValueOf(other)
685
+
686
+ def __rmod__(self, other):
687
+ return _numericValueOf(other) % _numericValueOf(self)
688
+
689
+ def __divmod__(self, other):
690
+ return divmod(_numericValueOf(self), _numericValueOf(other))
691
+
692
+ def __rdivmod__(self, other):
693
+ return divmod(_numericValueOf(other), _numericValueOf(self))
694
+
695
+ def __pow__(self, other, modulo):
696
+ if modulo is None:
697
+ return _numericValueOf(self) ** _numericValueOf(other)
698
+ else:
699
+ return pow(_numericValueOf(self), _numericValueOf(other), modulo)
700
+
701
+ def __rpow__(self, other, modulo):
702
+ if modulo is None:
703
+ return _numericValueOf(other) ** _numericValueOf(self)
704
+ else:
705
+ return pow(_numericValueOf(other), _numericValueOf(self), modulo)
706
+
707
+ def __neg__(self):
708
+ return - _numericValueOf(self)
709
+
710
+ def __pos__(self):
711
+ return + _numericValueOf(self)
712
+
713
+ def __abs__(self):
714
+ return abs( _numericValueOf(self) )
715
+
716
+ def __bool__(self):
717
+ return bool(_numericValueOf(self))
718
+
719
+ def __invert__(self):
720
+ return ~ _numericValueOf(self)
721
+
722
+ def __lshift__(self, other):
723
+ return _numericValueOf(self) << _numericValueOf(other)
724
+
725
+ def __rlshift__(self, other):
726
+ return _numericValueOf(other) << _numericValueOf(self)
727
+
728
+ def __rshift__(self, other):
729
+ return _numericValueOf(self) >> _numericValueOf(other)
730
+
731
+ def __rrshift__(self, other):
732
+ return _numericValueOf(other) >> _numericValueOf(self)
733
+
734
+ def __and__(self, other):
735
+ return _numericValueOf(self) & _numericValueOf(other)
736
+
737
+ def __rand__(self, other):
738
+ return _numericValueOf(other) & _numericValueOf(self)
739
+
740
+ def __or__(self, other):
741
+ return _numericValueOf(self) | _numericValueOf(other)
742
+
743
+ def __ror__(self, other):
744
+ return _numericValueOf(other) | _numericValueOf(self)
745
+
746
+ def __xor__(self, other):
747
+ return _numericValueOf(self) ^ _numericValueOf(other)
748
+
749
+ def __rxor__(self, other):
750
+ return _numericValueOf(other) ^ _numericValueOf(self)
751
+
752
+
753
+ cdef class IntElement(NumberElement):
754
+ def _init(self):
755
+ self._parse_value = int
756
+
757
+ def __index__(self):
758
+ return int(_parseNumber(self))
759
+
760
+
761
+ cdef class FloatElement(NumberElement):
762
+ def _init(self):
763
+ self._parse_value = float
764
+
765
+
766
+ cdef class StringElement(ObjectifiedDataElement):
767
+ """String data class.
768
+
769
+ Note that this class does *not* support the sequence protocol of strings:
770
+ len(), iter(), str_attr[0], str_attr[0:1], etc. are *not* supported.
771
+ Instead, use the .text attribute to get a 'real' string.
772
+ """
773
+ @property
774
+ def pyval(self):
775
+ return textOf(self._c_node) or ''
776
+
777
+ def __repr__(self):
778
+ return repr(textOf(self._c_node) or '')
779
+
780
+ def strlen(self):
781
+ text = textOf(self._c_node)
782
+ if text is None:
783
+ return 0
784
+ else:
785
+ return len(text)
786
+
787
+ def __bool__(self):
788
+ return bool(textOf(self._c_node))
789
+
790
+ def __richcmp__(self, other, int op):
791
+ return _richcmpPyvals(self, other, op)
792
+
793
+ def __hash__(self):
794
+ return hash(textOf(self._c_node) or '')
795
+
796
+ def __add__(self, other):
797
+ text = _strValueOf(self)
798
+ other = _strValueOf(other)
799
+ return text + other
800
+
801
+ def __radd__(self, other):
802
+ text = _strValueOf(self)
803
+ other = _strValueOf(other)
804
+ return other + text
805
+
806
+ def __mul__(self, other):
807
+ if isinstance(self, StringElement):
808
+ return (textOf((<StringElement>self)._c_node) or '') * _numericValueOf(other)
809
+ elif isinstance(other, StringElement):
810
+ return _numericValueOf(self) * (textOf((<StringElement>other)._c_node) or '')
811
+ else:
812
+ return NotImplemented
813
+
814
+ def __rmul__(self, other):
815
+ return _numericValueOf(other) * (textOf((<StringElement>self)._c_node) or '')
816
+
817
+ def __mod__(self, other):
818
+ return (_strValueOf(self) or '') % other
819
+
820
+ def __int__(self):
821
+ return int(textOf(self._c_node))
822
+
823
+ def __float__(self):
824
+ return float(textOf(self._c_node))
825
+
826
+ def __complex__(self):
827
+ return complex(textOf(self._c_node))
828
+
829
+
830
+ cdef class NoneElement(ObjectifiedDataElement):
831
+ def __str__(self):
832
+ return "None"
833
+
834
+ def __repr__(self):
835
+ return "None"
836
+
837
+ def __bool__(self):
838
+ return False
839
+
840
+ def __richcmp__(self, other, int op):
841
+ if other is None or self is None:
842
+ return python.PyObject_RichCompare(None, None, op)
843
+ if isinstance(self, NoneElement):
844
+ return python.PyObject_RichCompare(None, other, op)
845
+ else:
846
+ return python.PyObject_RichCompare(self, None, op)
847
+
848
+ def __hash__(self):
849
+ return hash(None)
850
+
851
+ @property
852
+ def pyval(self):
853
+ return None
854
+
855
+
856
+ cdef class BoolElement(IntElement):
857
+ """Boolean type base on string values: 'true' or 'false'.
858
+
859
+ Note that this inherits from IntElement to mimic the behaviour of
860
+ Python's bool type.
861
+ """
862
+ def _init(self):
863
+ self._parse_value = _parseBool # wraps as Python callable
864
+
865
+ def __bool__(self):
866
+ return _parseBool(textOf(self._c_node))
867
+
868
+ def __int__(self):
869
+ return 0 + _parseBool(textOf(self._c_node))
870
+
871
+ def __float__(self):
872
+ return 0.0 + _parseBool(textOf(self._c_node))
873
+
874
+ def __richcmp__(self, other, int op):
875
+ return _richcmpPyvals(self, other, op)
876
+
877
+ def __hash__(self):
878
+ return hash(_parseBool(textOf(self._c_node)))
879
+
880
+ def __str__(self):
881
+ return unicode(_parseBool(textOf(self._c_node)))
882
+
883
+ def __repr__(self):
884
+ return repr(_parseBool(textOf(self._c_node)))
885
+
886
+ @property
887
+ def pyval(self):
888
+ return _parseBool(textOf(self._c_node))
889
+
890
+
891
+ cdef _checkBool(s):
892
+ cdef int value = -1
893
+ if s is not None:
894
+ value = __parseBoolAsInt(s)
895
+ if value == -1:
896
+ raise ValueError
897
+
898
+
899
+ cdef bint _parseBool(s) except -1:
900
+ cdef int value
901
+ if s is None:
902
+ return False
903
+ value = __parseBoolAsInt(s)
904
+ if value == -1:
905
+ raise ValueError, f"Invalid boolean value: '{s}'"
906
+ return value
907
+
908
+
909
+ cdef inline int __parseBoolAsInt(text) except -2:
910
+ if text == 'false':
911
+ return 0
912
+ elif text == 'true':
913
+ return 1
914
+ elif text == '0':
915
+ return 0
916
+ elif text == '1':
917
+ return 1
918
+ return -1
919
+
920
+
921
+ cdef object _parseNumber(NumberElement element):
922
+ return element._parse_value(textOf(element._c_node))
923
+
924
+
925
+ cdef enum NumberParserState:
926
+ NPS_SPACE_PRE = 0
927
+ NPS_SIGN = 1
928
+ NPS_DIGITS = 2
929
+ NPS_POINT_LEAD = 3
930
+ NPS_POINT = 4
931
+ NPS_FRACTION = 5
932
+ NPS_EXP = 6
933
+ NPS_EXP_SIGN = 7
934
+ NPS_DIGITS_EXP = 8
935
+ NPS_SPACE_TAIL = 9
936
+ NPS_INF1 = 20
937
+ NPS_INF2 = 21
938
+ NPS_INF3 = 22
939
+ NPS_NAN1 = 23
940
+ NPS_NAN2 = 24
941
+ NPS_NAN3 = 25
942
+ NPS_ERROR = 99
943
+
944
+
945
+ ctypedef fused bytes_unicode:
946
+ bytes
947
+ unicode
948
+
949
+
950
+ cdef _checkNumber(bytes_unicode s, bint allow_float):
951
+ cdef Py_UCS4 c
952
+ cdef NumberParserState state = NPS_SPACE_PRE
953
+
954
+ for c in s:
955
+ if c in '0123456789':
956
+ if state in (NPS_DIGITS, NPS_FRACTION, NPS_DIGITS_EXP):
957
+ pass
958
+ elif state in (NPS_SPACE_PRE, NPS_SIGN):
959
+ state = NPS_DIGITS
960
+ elif state in (NPS_POINT_LEAD, NPS_POINT):
961
+ state = NPS_FRACTION
962
+ elif state in (NPS_EXP, NPS_EXP_SIGN):
963
+ state = NPS_DIGITS_EXP
964
+ else:
965
+ state = NPS_ERROR
966
+ else:
967
+ if c == '.':
968
+ if state in (NPS_SPACE_PRE, NPS_SIGN):
969
+ state = NPS_POINT_LEAD
970
+ elif state == NPS_DIGITS:
971
+ state = NPS_POINT
972
+ else:
973
+ state = NPS_ERROR
974
+ if not allow_float:
975
+ state = NPS_ERROR
976
+ elif c in '-+':
977
+ if state == NPS_SPACE_PRE:
978
+ state = NPS_SIGN
979
+ elif state == NPS_EXP:
980
+ state = NPS_EXP_SIGN
981
+ else:
982
+ state = NPS_ERROR
983
+ elif c == 'E':
984
+ if state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION):
985
+ state = NPS_EXP
986
+ else:
987
+ state = NPS_ERROR
988
+ if not allow_float:
989
+ state = NPS_ERROR
990
+ # Allow INF and NaN. XMLSchema requires case, we don't, like Python.
991
+ elif c in 'iI':
992
+ state = NPS_INF1 if allow_float and state in (NPS_SPACE_PRE, NPS_SIGN) else NPS_ERROR
993
+ elif c in 'fF':
994
+ state = NPS_INF3 if state == NPS_INF2 else NPS_ERROR
995
+ elif c in 'aA':
996
+ state = NPS_NAN2 if state == NPS_NAN1 else NPS_ERROR
997
+ elif c in 'nN':
998
+ # Python also allows [+-]NaN, so let's accept that.
999
+ if state in (NPS_SPACE_PRE, NPS_SIGN):
1000
+ state = NPS_NAN1 if allow_float else NPS_ERROR
1001
+ elif state == NPS_NAN2:
1002
+ state = NPS_NAN3
1003
+ elif state == NPS_INF1:
1004
+ state = NPS_INF2
1005
+ else:
1006
+ state = NPS_ERROR
1007
+ # Allow spaces around text values.
1008
+ else:
1009
+ if c.isspace() if (bytes_unicode is unicode) else c in b'\x09\x0a\x0b\x0c\x0d\x20':
1010
+ if state in (NPS_SPACE_PRE, NPS_SPACE_TAIL):
1011
+ pass
1012
+ elif state in (NPS_DIGITS, NPS_POINT, NPS_FRACTION, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3):
1013
+ state = NPS_SPACE_TAIL
1014
+ else:
1015
+ state = NPS_ERROR
1016
+ else:
1017
+ state = NPS_ERROR
1018
+
1019
+ if state == NPS_ERROR:
1020
+ break
1021
+
1022
+ if state not in (NPS_DIGITS, NPS_FRACTION, NPS_POINT, NPS_DIGITS_EXP, NPS_INF3, NPS_NAN3, NPS_SPACE_TAIL):
1023
+ raise ValueError
1024
+
1025
+
1026
+ cdef _checkInt(s):
1027
+ return _checkNumber(<unicode>s, allow_float=False)
1028
+
1029
+
1030
+ cdef _checkFloat(s):
1031
+ return _checkNumber(<unicode>s, allow_float=True)
1032
+
1033
+
1034
+ cdef object _strValueOf(obj):
1035
+ if python._isString(obj):
1036
+ return obj
1037
+ if isinstance(obj, _Element):
1038
+ return textOf((<_Element>obj)._c_node) or ''
1039
+ if obj is None:
1040
+ return ''
1041
+ return unicode(obj)
1042
+
1043
+
1044
+ cdef object _numericValueOf(obj):
1045
+ if isinstance(obj, NumberElement):
1046
+ return _parseNumber(<NumberElement>obj)
1047
+ try:
1048
+ # not always numeric, but Python will raise the right exception
1049
+ return obj.pyval
1050
+ except AttributeError:
1051
+ pass
1052
+ return obj
1053
+
1054
+
1055
+ cdef _richcmpPyvals(left, right, int op):
1056
+ left = getattr(left, 'pyval', left)
1057
+ right = getattr(right, 'pyval', right)
1058
+ return python.PyObject_RichCompare(left, right, op)
1059
+
1060
+
1061
+ ################################################################################
1062
+ # Python type registry
1063
+
1064
+ cdef class PyType:
1065
+ """PyType(self, name, type_check, type_class, stringify=None)
1066
+ User defined type.
1067
+
1068
+ Named type that contains a type check function, a type class that
1069
+ inherits from ObjectifiedDataElement and an optional "stringification"
1070
+ function. The type check must take a string as argument and raise
1071
+ ValueError or TypeError if it cannot handle the string value. It may be
1072
+ None in which case it is not considered for type guessing. For registered
1073
+ named types, the 'stringify' function (or unicode() if None) is used to
1074
+ convert a Python object with type name 'name' to the string representation
1075
+ stored in the XML tree.
1076
+
1077
+ Example::
1078
+
1079
+ PyType('int', int, MyIntClass).register()
1080
+
1081
+ Note that the order in which types are registered matters. The first
1082
+ matching type will be used.
1083
+ """
1084
+ cdef readonly object name
1085
+ cdef readonly object type_check
1086
+ cdef readonly object stringify
1087
+ cdef object _type
1088
+ cdef list _schema_types
1089
+ def __init__(self, name, type_check, type_class, stringify=None):
1090
+ if isinstance(name, bytes):
1091
+ name = (<bytes>name).decode('ascii')
1092
+ elif not isinstance(name, unicode):
1093
+ raise TypeError, "Type name must be a string"
1094
+ if type_check is not None and not callable(type_check):
1095
+ raise TypeError, "Type check function must be callable (or None)"
1096
+ if name != TREE_PYTYPE_NAME and \
1097
+ not issubclass(type_class, ObjectifiedDataElement):
1098
+ raise TypeError, \
1099
+ "Data classes must inherit from ObjectifiedDataElement"
1100
+ self.name = name
1101
+ self._type = type_class
1102
+ self.type_check = type_check
1103
+ if stringify is None:
1104
+ stringify = unicode
1105
+ self.stringify = stringify
1106
+ self._schema_types = []
1107
+
1108
+ def __repr__(self):
1109
+ return "PyType(%s, %s)" % (self.name, self._type.__name__)
1110
+
1111
+ def register(self, before=None, after=None):
1112
+ """register(self, before=None, after=None)
1113
+
1114
+ Register the type.
1115
+
1116
+ The additional keyword arguments 'before' and 'after' accept a
1117
+ sequence of type names that must appear before/after the new type in
1118
+ the type list. If any of them is not currently known, it is simply
1119
+ ignored. Raises ValueError if the dependencies cannot be fulfilled.
1120
+ """
1121
+ if self.name == TREE_PYTYPE_NAME:
1122
+ raise ValueError, "Cannot register tree type"
1123
+ if self.type_check is not None:
1124
+ for item in _TYPE_CHECKS:
1125
+ if item[0] is self.type_check:
1126
+ _TYPE_CHECKS.remove(item)
1127
+ break
1128
+ entry = (self.type_check, self)
1129
+ first_pos = 0
1130
+ last_pos = -1
1131
+ if before or after:
1132
+ if before is None:
1133
+ before = ()
1134
+ elif after is None:
1135
+ after = ()
1136
+ for i, (check, pytype) in enumerate(_TYPE_CHECKS):
1137
+ if last_pos == -1 and pytype.name in before:
1138
+ last_pos = i
1139
+ if pytype.name in after:
1140
+ first_pos = i+1
1141
+ if last_pos == -1:
1142
+ _TYPE_CHECKS.append(entry)
1143
+ elif first_pos > last_pos:
1144
+ raise ValueError, "inconsistent before/after dependencies"
1145
+ else:
1146
+ _TYPE_CHECKS.insert(last_pos, entry)
1147
+
1148
+ _PYTYPE_DICT[self.name] = self
1149
+ for xs_type in self._schema_types:
1150
+ _SCHEMA_TYPE_DICT[xs_type] = self
1151
+
1152
+ def unregister(self):
1153
+ "unregister(self)"
1154
+ if _PYTYPE_DICT.get(self.name) is self:
1155
+ del _PYTYPE_DICT[self.name]
1156
+ for xs_type, pytype in list(_SCHEMA_TYPE_DICT.items()):
1157
+ if pytype is self:
1158
+ del _SCHEMA_TYPE_DICT[xs_type]
1159
+ if self.type_check is None:
1160
+ return
1161
+ try:
1162
+ _TYPE_CHECKS.remove( (self.type_check, self) )
1163
+ except ValueError:
1164
+ pass
1165
+
1166
+ property xmlSchemaTypes:
1167
+ """The list of XML Schema datatypes this Python type maps to.
1168
+
1169
+ Note that this must be set before registering the type!
1170
+ """
1171
+ def __get__(self):
1172
+ return self._schema_types
1173
+ def __set__(self, types):
1174
+ self._schema_types = list(map(unicode, types))
1175
+
1176
+
1177
+ cdef dict _PYTYPE_DICT = {}
1178
+ cdef dict _SCHEMA_TYPE_DICT = {}
1179
+ cdef list _TYPE_CHECKS = []
1180
+
1181
+ cdef unicode _xml_bool(value):
1182
+ return "true" if value else "false"
1183
+
1184
+ cdef unicode _xml_float(value):
1185
+ if _float_is_inf(value):
1186
+ if value > 0:
1187
+ return "INF"
1188
+ return "-INF"
1189
+ if _float_is_nan(value):
1190
+ return "NaN"
1191
+ return unicode(repr(value))
1192
+
1193
+ cdef _pytypename(obj):
1194
+ return "str" if python._isString(obj) else _typename(obj)
1195
+
1196
+ def pytypename(obj):
1197
+ """pytypename(obj)
1198
+
1199
+ Find the name of the corresponding PyType for a Python object.
1200
+ """
1201
+ return _pytypename(obj)
1202
+
1203
+ cdef _registerPyTypes():
1204
+ pytype = PyType('int', _checkInt, IntElement) # wraps functions for Python
1205
+ pytype.xmlSchemaTypes = ("integer", "int", "short", "byte", "unsignedShort",
1206
+ "unsignedByte", "nonPositiveInteger",
1207
+ "negativeInteger", "long", "nonNegativeInteger",
1208
+ "unsignedLong", "unsignedInt", "positiveInteger",)
1209
+ pytype.register()
1210
+
1211
+ # 'long' type just for backwards compatibility
1212
+ pytype = PyType('long', None, IntElement)
1213
+ pytype.register()
1214
+
1215
+ pytype = PyType('float', _checkFloat, FloatElement, _xml_float) # wraps functions for Python
1216
+ pytype.xmlSchemaTypes = ("double", "float")
1217
+ pytype.register()
1218
+
1219
+ pytype = PyType('bool', _checkBool, BoolElement, _xml_bool) # wraps functions for Python
1220
+ pytype.xmlSchemaTypes = ("boolean",)
1221
+ pytype.register()
1222
+
1223
+ pytype = PyType('str', None, StringElement)
1224
+ pytype.xmlSchemaTypes = ("string", "normalizedString", "token", "language",
1225
+ "Name", "NCName", "ID", "IDREF", "ENTITY",
1226
+ "NMTOKEN", )
1227
+ pytype.register()
1228
+
1229
+ # since lxml 2.0
1230
+ pytype = PyType('NoneType', None, NoneElement)
1231
+ pytype.register()
1232
+
1233
+ # backwards compatibility
1234
+ pytype = PyType('none', None, NoneElement)
1235
+ pytype.register()
1236
+
1237
+ # non-registered PyType for inner tree elements
1238
+ cdef PyType TREE_PYTYPE = PyType(TREE_PYTYPE_NAME, None, ObjectifiedElement)
1239
+
1240
+ _registerPyTypes()
1241
+
1242
+ def getRegisteredTypes():
1243
+ """getRegisteredTypes()
1244
+
1245
+ Returns a list of the currently registered PyType objects.
1246
+
1247
+ To add a new type, retrieve this list and call unregister() for all
1248
+ entries. Then add the new type at a suitable position (possibly replacing
1249
+ an existing one) and call register() for all entries.
1250
+
1251
+ This is necessary if the new type interferes with the type check functions
1252
+ of existing ones (normally only int/float/bool) and must the tried before
1253
+ other types. To add a type that is not yet parsable by the current type
1254
+ check functions, you can simply register() it, which will append it to the
1255
+ end of the type list.
1256
+ """
1257
+ cdef list types = []
1258
+ cdef set known = set()
1259
+ for check, pytype in _TYPE_CHECKS:
1260
+ name = pytype.name
1261
+ if name not in known:
1262
+ known.add(name)
1263
+ types.append(pytype)
1264
+ for pytype in _PYTYPE_DICT.values():
1265
+ name = pytype.name
1266
+ if name not in known:
1267
+ known.add(name)
1268
+ types.append(pytype)
1269
+ return types
1270
+
1271
+ cdef PyType _guessPyType(value, PyType defaulttype):
1272
+ if value is None:
1273
+ return None
1274
+ for type_check, tested_pytype in _TYPE_CHECKS:
1275
+ try:
1276
+ type_check(value)
1277
+ return <PyType>tested_pytype
1278
+ except IGNORABLE_ERRORS:
1279
+ # could not be parsed as the specified type => ignore
1280
+ pass
1281
+ return defaulttype
1282
+
1283
+ cdef object _guessElementClass(tree.xmlNode* c_node):
1284
+ value = textOf(c_node)
1285
+ if value is None:
1286
+ return None
1287
+ if value == '':
1288
+ return StringElement
1289
+
1290
+ for type_check, pytype in _TYPE_CHECKS:
1291
+ try:
1292
+ type_check(value)
1293
+ return (<PyType>pytype)._type
1294
+ except IGNORABLE_ERRORS:
1295
+ pass
1296
+ return None
1297
+
1298
+ ################################################################################
1299
+ # adapted ElementMaker supports registered PyTypes
1300
+
1301
+ @cython.final
1302
+ @cython.internal
1303
+ cdef class _ObjectifyElementMakerCaller:
1304
+ cdef object _tag
1305
+ cdef object _nsmap
1306
+ cdef object _element_factory
1307
+ cdef bint _annotate
1308
+
1309
+ def __call__(self, *children, **attrib):
1310
+ "__call__(self, *children, **attrib)"
1311
+ cdef _ObjectifyElementMakerCaller elementMaker
1312
+ cdef _Element element
1313
+ cdef _Element childElement
1314
+ cdef bint has_children
1315
+ cdef bint has_string_value
1316
+ if self._element_factory is None:
1317
+ element = _makeElement(self._tag, None, attrib, self._nsmap)
1318
+ else:
1319
+ element = self._element_factory(self._tag, attrib, self._nsmap)
1320
+
1321
+ pytype_name = None
1322
+ has_children = False
1323
+ has_string_value = False
1324
+ for child in children:
1325
+ if child is None:
1326
+ if len(children) == 1:
1327
+ cetree.setAttributeValue(
1328
+ element, XML_SCHEMA_INSTANCE_NIL_ATTR, "true")
1329
+ elif python._isString(child):
1330
+ _add_text(element, child)
1331
+ has_string_value = True
1332
+ elif isinstance(child, _Element):
1333
+ cetree.appendChildToElement(element, <_Element>child)
1334
+ has_children = True
1335
+ elif isinstance(child, _ObjectifyElementMakerCaller):
1336
+ elementMaker = <_ObjectifyElementMakerCaller>child
1337
+ if elementMaker._element_factory is None:
1338
+ cetree.makeSubElement(element, elementMaker._tag,
1339
+ None, None, None, None)
1340
+ else:
1341
+ childElement = elementMaker._element_factory(
1342
+ elementMaker._tag)
1343
+ cetree.appendChildToElement(element, childElement)
1344
+ has_children = True
1345
+ elif isinstance(child, dict):
1346
+ for name, value in child.items():
1347
+ # keyword arguments in attrib take precedence
1348
+ if name in attrib:
1349
+ continue
1350
+ pytype = _PYTYPE_DICT.get(_typename(value))
1351
+ if pytype is not None:
1352
+ value = (<PyType>pytype).stringify(value)
1353
+ elif not python._isString(value):
1354
+ value = unicode(value)
1355
+ cetree.setAttributeValue(element, name, value)
1356
+ else:
1357
+ if pytype_name is not None:
1358
+ # concatenation always makes the result a string
1359
+ has_string_value = True
1360
+ pytype_name = _typename(child)
1361
+ pytype = _PYTYPE_DICT.get(_typename(child))
1362
+ if pytype is not None:
1363
+ _add_text(element, (<PyType>pytype).stringify(child))
1364
+ else:
1365
+ has_string_value = True
1366
+ child = unicode(child)
1367
+ _add_text(element, child)
1368
+
1369
+ if self._annotate and not has_children:
1370
+ if has_string_value:
1371
+ cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, "str")
1372
+ elif pytype_name is not None:
1373
+ cetree.setAttributeValue(element, PYTYPE_ATTRIBUTE, pytype_name)
1374
+
1375
+ return element
1376
+
1377
+ cdef _add_text(_Element elem, text):
1378
+ # add text to the tree in construction, either as element text or
1379
+ # tail text, depending on the current tree state
1380
+ cdef tree.xmlNode* c_child
1381
+ c_child = cetree.findChildBackwards(elem._c_node, 0)
1382
+ if c_child is not NULL:
1383
+ old = cetree.tailOf(c_child)
1384
+ if old is not None:
1385
+ text = old + text
1386
+ cetree.setTailText(c_child, text)
1387
+ else:
1388
+ old = cetree.textOf(elem._c_node)
1389
+ if old is not None:
1390
+ text = old + text
1391
+ cetree.setNodeText(elem._c_node, text)
1392
+
1393
+ cdef class ElementMaker:
1394
+ """ElementMaker(self, namespace=None, nsmap=None, annotate=True, makeelement=None)
1395
+
1396
+ An ElementMaker that can be used for constructing trees.
1397
+
1398
+ Example::
1399
+
1400
+ >>> M = ElementMaker(annotate=False)
1401
+ >>> attributes = {'class': 'par'}
1402
+ >>> html = M.html( M.body( M.p('hello', attributes, M.br, 'objectify', style="font-weight: bold") ) )
1403
+
1404
+ >>> from lxml.etree import tostring
1405
+ >>> print(tostring(html, method='html').decode('ascii'))
1406
+ <html><body><p style="font-weight: bold" class="par">hello<br>objectify</p></body></html>
1407
+
1408
+ To create tags that are not valid Python identifiers, call the factory
1409
+ directly and pass the tag name as first argument::
1410
+
1411
+ >>> root = M('tricky-tag', 'some text')
1412
+ >>> print(root.tag)
1413
+ tricky-tag
1414
+ >>> print(root.text)
1415
+ some text
1416
+
1417
+ Note that this module has a predefined ElementMaker instance called ``E``.
1418
+ """
1419
+ cdef object _makeelement
1420
+ cdef object _namespace
1421
+ cdef object _nsmap
1422
+ cdef bint _annotate
1423
+ cdef dict _cache
1424
+ def __init__(self, *, namespace=None, nsmap=None, annotate=True,
1425
+ makeelement=None):
1426
+ if nsmap is None:
1427
+ nsmap = _DEFAULT_NSMAP if annotate else {}
1428
+ self._nsmap = nsmap
1429
+ self._namespace = None if namespace is None else "{%s}" % namespace
1430
+ self._annotate = annotate
1431
+ if makeelement is not None:
1432
+ if not callable(makeelement):
1433
+ raise TypeError(
1434
+ f"argument of 'makeelement' parameter must be callable, got {type(makeelement)}")
1435
+ self._makeelement = makeelement
1436
+ else:
1437
+ self._makeelement = None
1438
+ self._cache = {}
1439
+
1440
+ @cython.final
1441
+ cdef _build_element_maker(self, tag, bint caching):
1442
+ cdef _ObjectifyElementMakerCaller element_maker
1443
+ element_maker = _ObjectifyElementMakerCaller.__new__(_ObjectifyElementMakerCaller)
1444
+ if self._namespace is not None and tag[0] != "{":
1445
+ element_maker._tag = self._namespace + tag
1446
+ else:
1447
+ element_maker._tag = tag
1448
+ element_maker._nsmap = self._nsmap
1449
+ element_maker._annotate = self._annotate
1450
+ element_maker._element_factory = self._makeelement
1451
+ if caching:
1452
+ if len(self._cache) > 200:
1453
+ self._cache.clear()
1454
+ self._cache[tag] = element_maker
1455
+ return element_maker
1456
+
1457
+ def __getattr__(self, tag):
1458
+ element_maker = self._cache.get(tag)
1459
+ if element_maker is None:
1460
+ return self._build_element_maker(tag, caching=True)
1461
+ return element_maker
1462
+
1463
+ def __call__(self, tag, *args, **kwargs):
1464
+ element_maker = self._cache.get(tag)
1465
+ if element_maker is None:
1466
+ element_maker = self._build_element_maker(
1467
+ tag, caching=not is_special_method(tag))
1468
+ return element_maker(*args, **kwargs)
1469
+
1470
+ ################################################################################
1471
+ # Recursive element dumping
1472
+
1473
+ cdef bint __RECURSIVE_STR = 0 # default: off
1474
+
1475
+ def enable_recursive_str(on=True):
1476
+ """enable_recursive_str(on=True)
1477
+
1478
+ Enable a recursively generated tree representation for str(element),
1479
+ based on objectify.dump(element).
1480
+ """
1481
+ global __RECURSIVE_STR
1482
+ __RECURSIVE_STR = on
1483
+
1484
+ def dump(_Element element not None):
1485
+ """dump(_Element element not None)
1486
+
1487
+ Return a recursively generated string representation of an element.
1488
+ """
1489
+ return _dump(element, 0)
1490
+
1491
+ cdef object _dump(_Element element, int indent):
1492
+ indentstr = " " * indent
1493
+ if isinstance(element, ObjectifiedDataElement):
1494
+ value = repr(element)
1495
+ else:
1496
+ value = textOf(element._c_node)
1497
+ if value is not None:
1498
+ if not value.strip():
1499
+ value = None
1500
+ else:
1501
+ value = repr(value)
1502
+ result = f"{indentstr}{element.tag} = {value} [{_typename(element)}]\n"
1503
+ xsi_ns = "{%s}" % XML_SCHEMA_INSTANCE_NS
1504
+ pytype_ns = "{%s}" % PYTYPE_NAMESPACE
1505
+ for name, value in sorted(cetree.iterattributes(element, 3)):
1506
+ if '{' in name:
1507
+ if name == PYTYPE_ATTRIBUTE:
1508
+ if value == TREE_PYTYPE_NAME:
1509
+ continue
1510
+ else:
1511
+ name = name.replace(pytype_ns, 'py:')
1512
+ name = name.replace(xsi_ns, 'xsi:')
1513
+ result += f"{indentstr} * {name} = {value!r}\n"
1514
+
1515
+ indent += 1
1516
+ for child in element.iterchildren():
1517
+ result += _dump(child, indent)
1518
+ if indent == 1:
1519
+ return result[:-1] # strip last '\n'
1520
+ else:
1521
+ return result
1522
+
1523
+
1524
+ ################################################################################
1525
+ # Pickle support for objectified ElementTree
1526
+
1527
+ def __unpickleElementTree(data):
1528
+ return etree.ElementTree(fromstring(data))
1529
+
1530
+ cdef _setupPickle(elementTreeReduceFunction):
1531
+ import copyreg
1532
+ copyreg.pickle(etree._ElementTree,
1533
+ elementTreeReduceFunction, __unpickleElementTree)
1534
+
1535
+ def pickleReduceElementTree(obj):
1536
+ return __unpickleElementTree, (etree.tostring(obj),)
1537
+
1538
+ _setupPickle(pickleReduceElementTree)
1539
+ del pickleReduceElementTree
1540
+
1541
+ ################################################################################
1542
+ # Element class lookup
1543
+
1544
+ cdef class ObjectifyElementClassLookup(ElementClassLookup):
1545
+ """ObjectifyElementClassLookup(self, tree_class=None, empty_data_class=None)
1546
+ Element class lookup method that uses the objectify classes.
1547
+ """
1548
+ cdef object empty_data_class
1549
+ cdef object tree_class
1550
+ def __init__(self, tree_class=None, empty_data_class=None):
1551
+ """Lookup mechanism for objectify.
1552
+
1553
+ The default Element classes can be replaced by passing subclasses of
1554
+ ObjectifiedElement and ObjectifiedDataElement as keyword arguments.
1555
+ 'tree_class' defines inner tree classes (defaults to
1556
+ ObjectifiedElement), 'empty_data_class' defines the default class for
1557
+ empty data elements (defaults to StringElement).
1558
+ """
1559
+ self._lookup_function = _lookupElementClass
1560
+ if tree_class is None:
1561
+ tree_class = ObjectifiedElement
1562
+ self.tree_class = tree_class
1563
+ if empty_data_class is None:
1564
+ empty_data_class = StringElement
1565
+ self.empty_data_class = empty_data_class
1566
+
1567
+ cdef object _lookupElementClass(state, _Document doc, tree.xmlNode* c_node):
1568
+ cdef ObjectifyElementClassLookup lookup
1569
+ lookup = <ObjectifyElementClassLookup>state
1570
+ # if element has children => no data class
1571
+ if cetree.hasChild(c_node):
1572
+ return lookup.tree_class
1573
+
1574
+ # if element is defined as xsi:nil, return NoneElement class
1575
+ if "true" == cetree.attributeValueFromNsName(
1576
+ c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil"):
1577
+ return NoneElement
1578
+
1579
+ # check for Python type hint
1580
+ value = cetree.attributeValueFromNsName(
1581
+ c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
1582
+ if value is not None:
1583
+ if value == TREE_PYTYPE_NAME:
1584
+ return lookup.tree_class
1585
+ py_type = <PyType>_PYTYPE_DICT.get(value)
1586
+ if py_type is not None:
1587
+ return py_type._type
1588
+ # unknown 'pyval' => try to figure it out ourself, just go on
1589
+
1590
+ # check for XML Schema type hint
1591
+ value = cetree.attributeValueFromNsName(
1592
+ c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
1593
+
1594
+ if value is not None:
1595
+ schema_type = <PyType>_SCHEMA_TYPE_DICT.get(value)
1596
+ if schema_type is None and ':' in value:
1597
+ prefix, value = value.split(':', 1)
1598
+ schema_type = <PyType>_SCHEMA_TYPE_DICT.get(value)
1599
+ if schema_type is not None:
1600
+ return schema_type._type
1601
+
1602
+ # otherwise determine class based on text content type
1603
+ el_class = _guessElementClass(c_node)
1604
+ if el_class is not None:
1605
+ return el_class
1606
+
1607
+ # if element is a root node => default to tree node
1608
+ if c_node.parent is NULL or not tree._isElement(c_node.parent):
1609
+ return lookup.tree_class
1610
+
1611
+ return lookup.empty_data_class
1612
+
1613
+
1614
+ ################################################################################
1615
+ # Type annotations
1616
+
1617
+ cdef PyType _check_type(tree.xmlNode* c_node, PyType pytype):
1618
+ if pytype is None:
1619
+ return None
1620
+ value = textOf(c_node)
1621
+ try:
1622
+ pytype.type_check(value)
1623
+ return pytype
1624
+ except IGNORABLE_ERRORS:
1625
+ # could not be parsed as the specified type => ignore
1626
+ pass
1627
+ return None
1628
+
1629
+ def pyannotate(element_or_tree, *, ignore_old=False, ignore_xsi=False,
1630
+ empty_pytype=None):
1631
+ """pyannotate(element_or_tree, ignore_old=False, ignore_xsi=False, empty_pytype=None)
1632
+
1633
+ Recursively annotates the elements of an XML tree with 'pytype'
1634
+ attributes.
1635
+
1636
+ If the 'ignore_old' keyword argument is True (the default), current 'pytype'
1637
+ attributes will be ignored and replaced. Otherwise, they will be checked
1638
+ and only replaced if they no longer fit the current text value.
1639
+
1640
+ Setting the keyword argument ``ignore_xsi`` to True makes the function
1641
+ additionally ignore existing ``xsi:type`` annotations. The default is to
1642
+ use them as a type hint.
1643
+
1644
+ The default annotation of empty elements can be set with the
1645
+ ``empty_pytype`` keyword argument. The default is not to annotate empty
1646
+ elements. Pass 'str', for example, to make string values the default.
1647
+ """
1648
+ cdef _Element element
1649
+ element = cetree.rootNodeOrRaise(element_or_tree)
1650
+ _annotate(element, 0, 1, ignore_xsi, ignore_old, None, empty_pytype)
1651
+
1652
+ def xsiannotate(element_or_tree, *, ignore_old=False, ignore_pytype=False,
1653
+ empty_type=None):
1654
+ """xsiannotate(element_or_tree, ignore_old=False, ignore_pytype=False, empty_type=None)
1655
+
1656
+ Recursively annotates the elements of an XML tree with 'xsi:type'
1657
+ attributes.
1658
+
1659
+ If the 'ignore_old' keyword argument is True (the default), current
1660
+ 'xsi:type' attributes will be ignored and replaced. Otherwise, they will be
1661
+ checked and only replaced if they no longer fit the current text value.
1662
+
1663
+ Note that the mapping from Python types to XSI types is usually ambiguous.
1664
+ Currently, only the first XSI type name in the corresponding PyType
1665
+ definition will be used for annotation. Thus, you should consider naming
1666
+ the widest type first if you define additional types.
1667
+
1668
+ Setting the keyword argument ``ignore_pytype`` to True makes the function
1669
+ additionally ignore existing ``pytype`` annotations. The default is to
1670
+ use them as a type hint.
1671
+
1672
+ The default annotation of empty elements can be set with the
1673
+ ``empty_type`` keyword argument. The default is not to annotate empty
1674
+ elements. Pass 'string', for example, to make string values the default.
1675
+ """
1676
+ cdef _Element element
1677
+ element = cetree.rootNodeOrRaise(element_or_tree)
1678
+ _annotate(element, 1, 0, ignore_old, ignore_pytype, empty_type, None)
1679
+
1680
+ def annotate(element_or_tree, *, ignore_old=True, ignore_xsi=False,
1681
+ empty_pytype=None, empty_type=None, annotate_xsi=0,
1682
+ annotate_pytype=1):
1683
+ """annotate(element_or_tree, ignore_old=True, ignore_xsi=False, empty_pytype=None, empty_type=None, annotate_xsi=0, annotate_pytype=1)
1684
+
1685
+ Recursively annotates the elements of an XML tree with 'xsi:type'
1686
+ and/or 'py:pytype' attributes.
1687
+
1688
+ If the 'ignore_old' keyword argument is True (the default), current
1689
+ 'py:pytype' attributes will be ignored for the type annotation. Set to False
1690
+ if you want reuse existing 'py:pytype' information (iff appropriate for the
1691
+ element text value).
1692
+
1693
+ If the 'ignore_xsi' keyword argument is False (the default), existing
1694
+ 'xsi:type' attributes will be used for the type annotation, if they fit the
1695
+ element text values.
1696
+
1697
+ Note that the mapping from Python types to XSI types is usually ambiguous.
1698
+ Currently, only the first XSI type name in the corresponding PyType
1699
+ definition will be used for annotation. Thus, you should consider naming
1700
+ the widest type first if you define additional types.
1701
+
1702
+ The default 'py:pytype' annotation of empty elements can be set with the
1703
+ ``empty_pytype`` keyword argument. Pass 'str', for example, to make
1704
+ string values the default.
1705
+
1706
+ The default 'xsi:type' annotation of empty elements can be set with the
1707
+ ``empty_type`` keyword argument. The default is not to annotate empty
1708
+ elements. Pass 'string', for example, to make string values the default.
1709
+
1710
+ The keyword arguments 'annotate_xsi' (default: 0) and 'annotate_pytype'
1711
+ (default: 1) control which kind(s) of annotation to use.
1712
+ """
1713
+ cdef _Element element
1714
+ element = cetree.rootNodeOrRaise(element_or_tree)
1715
+ _annotate(element, annotate_xsi, annotate_pytype, ignore_xsi,
1716
+ ignore_old, empty_type, empty_pytype)
1717
+
1718
+
1719
+ cdef _annotate(_Element element, bint annotate_xsi, bint annotate_pytype,
1720
+ bint ignore_xsi, bint ignore_pytype,
1721
+ empty_type_name, empty_pytype_name):
1722
+ cdef _Document doc
1723
+ cdef tree.xmlNode* c_node
1724
+ cdef PyType empty_pytype, StrType, NoneType
1725
+
1726
+ if not annotate_xsi and not annotate_pytype:
1727
+ return
1728
+
1729
+ if empty_type_name is not None:
1730
+ if isinstance(empty_type_name, bytes):
1731
+ empty_type_name = (<bytes>empty_type_name).decode("ascii")
1732
+ empty_pytype = <PyType>_SCHEMA_TYPE_DICT.get(empty_type_name)
1733
+ elif empty_pytype_name is not None:
1734
+ if isinstance(empty_pytype_name, bytes):
1735
+ empty_pytype_name = (<bytes>empty_pytype_name).decode("ascii")
1736
+ empty_pytype = <PyType>_PYTYPE_DICT.get(empty_pytype_name)
1737
+ else:
1738
+ empty_pytype = None
1739
+
1740
+ StrType = <PyType>_PYTYPE_DICT.get('str')
1741
+ NoneType = <PyType>_PYTYPE_DICT.get('NoneType')
1742
+
1743
+ doc = element._doc
1744
+ c_node = element._c_node
1745
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
1746
+ if c_node.type == tree.XML_ELEMENT_NODE:
1747
+ _annotate_element(c_node, doc, annotate_xsi, annotate_pytype,
1748
+ ignore_xsi, ignore_pytype,
1749
+ empty_type_name, empty_pytype, StrType, NoneType)
1750
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
1751
+
1752
+ cdef int _annotate_element(tree.xmlNode* c_node, _Document doc,
1753
+ bint annotate_xsi, bint annotate_pytype,
1754
+ bint ignore_xsi, bint ignore_pytype,
1755
+ empty_type_name, PyType empty_pytype,
1756
+ PyType StrType, PyType NoneType) except -1:
1757
+ cdef tree.xmlNs* c_ns
1758
+ cdef PyType pytype = None
1759
+ typename = None
1760
+ istree = 0
1761
+
1762
+ # if element is defined as xsi:nil, represent it as None
1763
+ if cetree.attributeValueFromNsName(
1764
+ c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"nil") == "true":
1765
+ pytype = NoneType
1766
+
1767
+ if pytype is None and not ignore_xsi:
1768
+ # check that old xsi type value is valid
1769
+ typename = cetree.attributeValueFromNsName(
1770
+ c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
1771
+ if typename is not None:
1772
+ pytype = <PyType>_SCHEMA_TYPE_DICT.get(typename)
1773
+ if pytype is None and ':' in typename:
1774
+ prefix, typename = typename.split(':', 1)
1775
+ pytype = <PyType>_SCHEMA_TYPE_DICT.get(typename)
1776
+ if pytype is not None and pytype is not StrType:
1777
+ # StrType does not have a typecheck but is the default
1778
+ # anyway, so just accept it if given as type
1779
+ # information
1780
+ pytype = _check_type(c_node, pytype)
1781
+ if pytype is None:
1782
+ typename = None
1783
+
1784
+ if pytype is None and not ignore_pytype:
1785
+ # check that old pytype value is valid
1786
+ old_pytypename = cetree.attributeValueFromNsName(
1787
+ c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
1788
+ if old_pytypename is not None:
1789
+ if old_pytypename == TREE_PYTYPE_NAME:
1790
+ if not cetree.hasChild(c_node):
1791
+ # only case where we should keep it,
1792
+ # everything else is clear enough
1793
+ pytype = TREE_PYTYPE
1794
+ else:
1795
+ if old_pytypename == 'none':
1796
+ # transition from lxml 1.x
1797
+ old_pytypename = "NoneType"
1798
+ pytype = <PyType>_PYTYPE_DICT.get(old_pytypename)
1799
+ if pytype is not None and pytype is not StrType:
1800
+ # StrType does not have a typecheck but is the
1801
+ # default anyway, so just accept it if given as
1802
+ # type information
1803
+ pytype = _check_type(c_node, pytype)
1804
+
1805
+ if pytype is None:
1806
+ # try to guess type
1807
+ if not cetree.hasChild(c_node):
1808
+ # element has no children => data class
1809
+ pytype = _guessPyType(textOf(c_node), StrType)
1810
+ else:
1811
+ istree = 1
1812
+
1813
+ if pytype is None:
1814
+ # use default type for empty elements
1815
+ if cetree.hasText(c_node):
1816
+ pytype = StrType
1817
+ else:
1818
+ pytype = empty_pytype
1819
+ if typename is None:
1820
+ typename = empty_type_name
1821
+
1822
+ if pytype is not None:
1823
+ if typename is None:
1824
+ if not istree:
1825
+ if pytype._schema_types:
1826
+ # pytype->xsi:type is a 1:n mapping
1827
+ # simply take the first
1828
+ typename = pytype._schema_types[0]
1829
+ elif typename not in pytype._schema_types:
1830
+ typename = pytype._schema_types[0]
1831
+
1832
+ if annotate_xsi:
1833
+ if typename is None or istree:
1834
+ cetree.delAttributeFromNsName(
1835
+ c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>"type")
1836
+ else:
1837
+ # update or create attribute
1838
+ typename_utf8 = cetree.utf8(typename)
1839
+ c_ns = cetree.findOrBuildNodeNsPrefix(
1840
+ doc, c_node, _XML_SCHEMA_NS, <unsigned char*>'xsd')
1841
+ if c_ns is not NULL:
1842
+ if b':' in typename_utf8:
1843
+ prefix, name = typename_utf8.split(b':', 1)
1844
+ if c_ns.prefix is NULL or c_ns.prefix[0] == c'\0':
1845
+ typename_utf8 = name
1846
+ elif tree.xmlStrcmp(_xcstr(prefix), c_ns.prefix) != 0:
1847
+ typename_utf8 = (<unsigned char*>c_ns.prefix) + b':' + name
1848
+ elif c_ns.prefix is not NULL and c_ns.prefix[0] != c'\0':
1849
+ typename_utf8 = (<unsigned char*>c_ns.prefix) + b':' + typename_utf8
1850
+ c_ns = cetree.findOrBuildNodeNsPrefix(
1851
+ doc, c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>'xsi')
1852
+ tree.xmlSetNsProp(c_node, c_ns, <unsigned char*>"type", _xcstr(typename_utf8))
1853
+
1854
+ if annotate_pytype:
1855
+ if pytype is None:
1856
+ # delete attribute if it exists
1857
+ cetree.delAttributeFromNsName(
1858
+ c_node, _PYTYPE_NAMESPACE, _PYTYPE_ATTRIBUTE_NAME)
1859
+ else:
1860
+ # update or create attribute
1861
+ c_ns = cetree.findOrBuildNodeNsPrefix(
1862
+ doc, c_node, _PYTYPE_NAMESPACE, <unsigned char*>'py')
1863
+ pytype_name = cetree.utf8(pytype.name)
1864
+ tree.xmlSetNsProp(c_node, c_ns, _PYTYPE_ATTRIBUTE_NAME,
1865
+ _xcstr(pytype_name))
1866
+ if pytype is NoneType:
1867
+ c_ns = cetree.findOrBuildNodeNsPrefix(
1868
+ doc, c_node, _XML_SCHEMA_INSTANCE_NS, <unsigned char*>'xsi')
1869
+ tree.xmlSetNsProp(c_node, c_ns, <unsigned char*>"nil", <unsigned char*>"true")
1870
+
1871
+ return 0
1872
+
1873
+ cdef object _strip_attributes = etree.strip_attributes
1874
+ cdef object _cleanup_namespaces = etree.cleanup_namespaces
1875
+
1876
+ def deannotate(element_or_tree, *, bint pytype=True, bint xsi=True,
1877
+ bint xsi_nil=False, bint cleanup_namespaces=False):
1878
+ """deannotate(element_or_tree, pytype=True, xsi=True, xsi_nil=False, cleanup_namespaces=False)
1879
+
1880
+ Recursively de-annotate the elements of an XML tree by removing 'py:pytype'
1881
+ and/or 'xsi:type' attributes and/or 'xsi:nil' attributes.
1882
+
1883
+ If the 'pytype' keyword argument is True (the default), 'py:pytype'
1884
+ attributes will be removed. If the 'xsi' keyword argument is True (the
1885
+ default), 'xsi:type' attributes will be removed.
1886
+ If the 'xsi_nil' keyword argument is True (default: False), 'xsi:nil'
1887
+ attributes will be removed.
1888
+
1889
+ Note that this does not touch the namespace declarations by
1890
+ default. If you want to remove unused namespace declarations from
1891
+ the tree, pass the option ``cleanup_namespaces=True``.
1892
+ """
1893
+ cdef list attribute_names = []
1894
+
1895
+ if pytype:
1896
+ attribute_names.append(PYTYPE_ATTRIBUTE)
1897
+ if xsi:
1898
+ attribute_names.append(XML_SCHEMA_INSTANCE_TYPE_ATTR)
1899
+ if xsi_nil:
1900
+ attribute_names.append(XML_SCHEMA_INSTANCE_NIL_ATTR)
1901
+
1902
+ _strip_attributes(element_or_tree, *attribute_names)
1903
+ if cleanup_namespaces:
1904
+ _cleanup_namespaces(element_or_tree)
1905
+
1906
+ ################################################################################
1907
+ # Module level parser setup
1908
+
1909
+ cdef object __DEFAULT_PARSER
1910
+ __DEFAULT_PARSER = etree.XMLParser(remove_blank_text=True)
1911
+ __DEFAULT_PARSER.set_element_class_lookup( ObjectifyElementClassLookup() )
1912
+
1913
+ cdef object objectify_parser
1914
+ objectify_parser = __DEFAULT_PARSER
1915
+
1916
+ def set_default_parser(new_parser = None):
1917
+ """set_default_parser(new_parser = None)
1918
+
1919
+ Replace the default parser used by objectify's Element() and
1920
+ fromstring() functions.
1921
+
1922
+ The new parser must be an etree.XMLParser.
1923
+
1924
+ Call without arguments to reset to the original parser.
1925
+ """
1926
+ global objectify_parser
1927
+ if new_parser is None:
1928
+ objectify_parser = __DEFAULT_PARSER
1929
+ elif isinstance(new_parser, etree.XMLParser):
1930
+ objectify_parser = new_parser
1931
+ else:
1932
+ raise TypeError, "parser must inherit from lxml.etree.XMLParser"
1933
+
1934
+ def makeparser(**kw):
1935
+ """makeparser(remove_blank_text=True, **kw)
1936
+
1937
+ Create a new XML parser for objectify trees.
1938
+
1939
+ You can pass all keyword arguments that are supported by
1940
+ ``etree.XMLParser()``. Note that this parser defaults to removing
1941
+ blank text. You can disable this by passing the
1942
+ ``remove_blank_text`` boolean keyword option yourself.
1943
+ """
1944
+ if 'remove_blank_text' not in kw:
1945
+ kw['remove_blank_text'] = True
1946
+ parser = etree.XMLParser(**kw)
1947
+ parser.set_element_class_lookup( ObjectifyElementClassLookup() )
1948
+ return parser
1949
+
1950
+ cdef _Element _makeElement(tag, text, attrib, nsmap):
1951
+ return cetree.makeElement(tag, None, objectify_parser, text, None, attrib, nsmap)
1952
+
1953
+ ################################################################################
1954
+ # Module level factory functions
1955
+
1956
+ cdef object _fromstring
1957
+ _fromstring = etree.fromstring
1958
+
1959
+ SubElement = etree.SubElement
1960
+
1961
+ def fromstring(xml, parser=None, *, base_url=None):
1962
+ """fromstring(xml, parser=None, base_url=None)
1963
+
1964
+ Objectify specific version of the lxml.etree fromstring() function
1965
+ that uses the objectify parser.
1966
+
1967
+ You can pass a different parser as second argument.
1968
+
1969
+ The ``base_url`` keyword argument allows to set the original base URL of
1970
+ the document to support relative Paths when looking up external entities
1971
+ (DTD, XInclude, ...).
1972
+ """
1973
+ if parser is None:
1974
+ parser = objectify_parser
1975
+ return _fromstring(xml, parser, base_url=base_url)
1976
+
1977
+ def XML(xml, parser=None, *, base_url=None):
1978
+ """XML(xml, parser=None, base_url=None)
1979
+
1980
+ Objectify specific version of the lxml.etree XML() literal factory
1981
+ that uses the objectify parser.
1982
+
1983
+ You can pass a different parser as second argument.
1984
+
1985
+ The ``base_url`` keyword argument allows to set the original base URL of
1986
+ the document to support relative Paths when looking up external entities
1987
+ (DTD, XInclude, ...).
1988
+ """
1989
+ if parser is None:
1990
+ parser = objectify_parser
1991
+ return _fromstring(xml, parser, base_url=base_url)
1992
+
1993
+ cdef object _parse
1994
+ _parse = etree.parse
1995
+
1996
+ def parse(f, parser=None, *, base_url=None):
1997
+ """parse(f, parser=None, base_url=None)
1998
+
1999
+ Parse a file or file-like object with the objectify parser.
2000
+
2001
+ You can pass a different parser as second argument.
2002
+
2003
+ The ``base_url`` keyword allows setting a URL for the document
2004
+ when parsing from a file-like object. This is needed when looking
2005
+ up external entities (DTD, XInclude, ...) with relative paths.
2006
+ """
2007
+ if parser is None:
2008
+ parser = objectify_parser
2009
+ return _parse(f, parser, base_url=base_url)
2010
+
2011
+ cdef dict _DEFAULT_NSMAP = {
2012
+ "py" : PYTYPE_NAMESPACE,
2013
+ "xsi" : XML_SCHEMA_INSTANCE_NS,
2014
+ "xsd" : XML_SCHEMA_NS
2015
+ }
2016
+
2017
+ E = ElementMaker()
2018
+
2019
+ def Element(_tag, attrib=None, nsmap=None, *, _pytype=None, **_attributes):
2020
+ """Element(_tag, attrib=None, nsmap=None, _pytype=None, **_attributes)
2021
+
2022
+ Objectify specific version of the lxml.etree Element() factory that
2023
+ always creates a structural (tree) element.
2024
+
2025
+ NOTE: requires parser based element class lookup activated in lxml.etree!
2026
+ """
2027
+ if attrib is not None:
2028
+ if _attributes:
2029
+ attrib = dict(attrib)
2030
+ attrib.update(_attributes)
2031
+ _attributes = attrib
2032
+ if _pytype is None:
2033
+ _pytype = TREE_PYTYPE_NAME
2034
+ if nsmap is None:
2035
+ nsmap = _DEFAULT_NSMAP
2036
+ _attributes[PYTYPE_ATTRIBUTE] = _pytype
2037
+ return _makeElement(_tag, None, _attributes, nsmap)
2038
+
2039
+ def DataElement(_value, attrib=None, nsmap=None, *, _pytype=None, _xsi=None,
2040
+ **_attributes):
2041
+ """DataElement(_value, attrib=None, nsmap=None, _pytype=None, _xsi=None, **_attributes)
2042
+
2043
+ Create a new element from a Python value and XML attributes taken from
2044
+ keyword arguments or a dictionary passed as second argument.
2045
+
2046
+ Automatically adds a 'pytype' attribute for the Python type of the value,
2047
+ if the type can be identified. If '_pytype' or '_xsi' are among the
2048
+ keyword arguments, they will be used instead.
2049
+
2050
+ If the _value argument is an ObjectifiedDataElement instance, its py:pytype,
2051
+ xsi:type and other attributes and nsmap are reused unless they are redefined
2052
+ in attrib and/or keyword arguments.
2053
+ """
2054
+ if nsmap is None:
2055
+ nsmap = _DEFAULT_NSMAP
2056
+ if attrib is not None and attrib:
2057
+ if _attributes:
2058
+ attrib = dict(attrib)
2059
+ attrib.update(_attributes)
2060
+ _attributes = attrib
2061
+ if isinstance(_value, ObjectifiedElement):
2062
+ if _pytype is None:
2063
+ if _xsi is None and not _attributes and nsmap is _DEFAULT_NSMAP:
2064
+ # special case: no change!
2065
+ return _value.__copy__()
2066
+ if isinstance(_value, ObjectifiedDataElement):
2067
+ # reuse existing nsmap unless redefined in nsmap parameter
2068
+ temp = _value.nsmap
2069
+ if temp is not None and temp:
2070
+ temp = dict(temp)
2071
+ temp.update(nsmap)
2072
+ nsmap = temp
2073
+ # reuse existing attributes unless redefined in attrib/_attributes
2074
+ temp = _value.attrib
2075
+ if temp is not None and temp:
2076
+ temp = dict(temp)
2077
+ temp.update(_attributes)
2078
+ _attributes = temp
2079
+ # reuse existing xsi:type or py:pytype attributes, unless provided as
2080
+ # arguments
2081
+ if _xsi is None and _pytype is None:
2082
+ _xsi = _attributes.get(XML_SCHEMA_INSTANCE_TYPE_ATTR)
2083
+ _pytype = _attributes.get(PYTYPE_ATTRIBUTE)
2084
+
2085
+ if _xsi is not None:
2086
+ if ':' in _xsi:
2087
+ prefix, name = _xsi.split(':', 1)
2088
+ ns = nsmap.get(prefix)
2089
+ if ns != XML_SCHEMA_NS:
2090
+ raise ValueError, "XSD types require the XSD namespace"
2091
+ elif nsmap is _DEFAULT_NSMAP:
2092
+ name = _xsi
2093
+ _xsi = 'xsd:' + _xsi
2094
+ else:
2095
+ name = _xsi
2096
+ for prefix, ns in nsmap.items():
2097
+ if ns == XML_SCHEMA_NS:
2098
+ if prefix is not None and prefix:
2099
+ _xsi = prefix + ':' + _xsi
2100
+ break
2101
+ else:
2102
+ raise ValueError, "XSD types require the XSD namespace"
2103
+ _attributes[XML_SCHEMA_INSTANCE_TYPE_ATTR] = _xsi
2104
+ if _pytype is None:
2105
+ # allow using unregistered or even wrong xsi:type names
2106
+ py_type = <PyType>_SCHEMA_TYPE_DICT.get(_xsi)
2107
+ if py_type is None:
2108
+ py_type = <PyType>_SCHEMA_TYPE_DICT.get(name)
2109
+ if py_type is not None:
2110
+ _pytype = py_type.name
2111
+
2112
+ if _pytype is None:
2113
+ _pytype = _pytypename(_value)
2114
+
2115
+ if _value is None and _pytype != "str":
2116
+ _pytype = _pytype or "NoneType"
2117
+ strval = None
2118
+ elif python._isString(_value):
2119
+ strval = _value
2120
+ elif isinstance(_value, bool):
2121
+ if _value:
2122
+ strval = "true"
2123
+ else:
2124
+ strval = "false"
2125
+ else:
2126
+ py_type = <PyType>_PYTYPE_DICT.get(_pytype)
2127
+ stringify = unicode if py_type is None else py_type.stringify
2128
+ strval = stringify(_value)
2129
+
2130
+ if _pytype is not None:
2131
+ if _pytype == "NoneType" or _pytype == "none":
2132
+ strval = None
2133
+ _attributes[XML_SCHEMA_INSTANCE_NIL_ATTR] = "true"
2134
+ else:
2135
+ # check if type information from arguments is valid
2136
+ py_type = <PyType>_PYTYPE_DICT.get(_pytype)
2137
+ if py_type is not None:
2138
+ if py_type.type_check is not None:
2139
+ py_type.type_check(strval)
2140
+ _attributes[PYTYPE_ATTRIBUTE] = _pytype
2141
+
2142
+ return _makeElement("value", strval, _attributes, nsmap)
2143
+
2144
+
2145
+ ################################################################################
2146
+ # ObjectPath
2147
+
2148
+ include "objectpath.pxi"
.venv/lib/python3.12/site-packages/lxml/objectpath.pxi ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ################################################################################
2
+ # ObjectPath
3
+
4
+ ctypedef struct _ObjectPath:
5
+ const_xmlChar* href
6
+ const_xmlChar* name
7
+ Py_ssize_t index
8
+
9
+
10
+ cdef object _NO_DEFAULT = object()
11
+
12
+
13
+ cdef class ObjectPath:
14
+ """ObjectPath(path)
15
+ Immutable object that represents a compiled object path.
16
+
17
+ Example for a path: 'root.child[1].{other}child[25]'
18
+ """
19
+ cdef readonly object find
20
+ cdef list _path
21
+ cdef object _path_str
22
+ cdef _ObjectPath* _c_path
23
+ cdef Py_ssize_t _path_len
24
+ def __init__(self, path):
25
+ if python._isString(path):
26
+ self._path = _parse_object_path_string(path)
27
+ self._path_str = path
28
+ else:
29
+ self._path = _parse_object_path_list(path)
30
+ self._path_str = '.'.join(path)
31
+ self._path_len = len(self._path)
32
+ self._c_path = _build_object_path_segments(self._path)
33
+ self.find = self.__call__
34
+
35
+ def __dealloc__(self):
36
+ if self._c_path is not NULL:
37
+ python.lxml_free(self._c_path)
38
+
39
+ def __str__(self):
40
+ return self._path_str
41
+
42
+ def __call__(self, _Element root not None, *_default):
43
+ """Follow the attribute path in the object structure and return the
44
+ target attribute value.
45
+
46
+ If it it not found, either returns a default value (if one was passed
47
+ as second argument) or raises AttributeError.
48
+ """
49
+ if _default:
50
+ if len(_default) > 1:
51
+ raise TypeError, "invalid number of arguments: needs one or two"
52
+ default = _default[0]
53
+ else:
54
+ default = _NO_DEFAULT
55
+ return _find_object_path(root, self._c_path, self._path_len, default)
56
+
57
+ def hasattr(self, _Element root not None):
58
+ "hasattr(self, root)"
59
+ try:
60
+ _find_object_path(root, self._c_path, self._path_len, _NO_DEFAULT)
61
+ except AttributeError:
62
+ return False
63
+ return True
64
+
65
+ def setattr(self, _Element root not None, value):
66
+ """setattr(self, root, value)
67
+
68
+ Set the value of the target element in a subtree.
69
+
70
+ If any of the children on the path does not exist, it is created.
71
+ """
72
+ _create_object_path(root, self._c_path, self._path_len, 1, value)
73
+
74
+ def addattr(self, _Element root not None, value):
75
+ """addattr(self, root, value)
76
+
77
+ Append a value to the target element in a subtree.
78
+
79
+ If any of the children on the path does not exist, it is created.
80
+ """
81
+ _create_object_path(root, self._c_path, self._path_len, 0, value)
82
+
83
+
84
+ cdef object __MATCH_PATH_SEGMENT = re.compile(
85
+ r"(\.?)\s*(?:\{([^}]*)\})?\s*([^.{}\[\]\s]+)\s*(?:\[\s*([-0-9]+)\s*\])?",
86
+ re.U).match
87
+
88
+ cdef tuple _RELATIVE_PATH_SEGMENT = (None, None, 0)
89
+
90
+
91
+ cdef list _parse_object_path_string(_path):
92
+ """Parse object path string into a (ns, name, index) list.
93
+ """
94
+ cdef bint has_dot
95
+ cdef unicode path
96
+ new_path = []
97
+ if isinstance(_path, bytes):
98
+ path = (<bytes>_path).decode('ascii')
99
+ elif type(_path) is not unicode:
100
+ path = unicode(_path)
101
+ else:
102
+ path = _path
103
+ path = path.strip()
104
+ if path == '.':
105
+ return [_RELATIVE_PATH_SEGMENT]
106
+ path_pos = 0
107
+ while path:
108
+ match = __MATCH_PATH_SEGMENT(path, path_pos)
109
+ if match is None:
110
+ break
111
+
112
+ dot, ns, name, index = match.groups()
113
+ index = int(index) if index else 0
114
+ has_dot = dot == '.'
115
+ if not new_path:
116
+ if has_dot:
117
+ # path '.child' => ignore root
118
+ new_path.append(_RELATIVE_PATH_SEGMENT)
119
+ elif index:
120
+ raise ValueError, "index not allowed on root node"
121
+ elif not has_dot:
122
+ raise ValueError, "invalid path"
123
+ if ns is not None:
124
+ ns = python.PyUnicode_AsUTF8String(ns)
125
+ name = python.PyUnicode_AsUTF8String(name)
126
+ new_path.append( (ns, name, index) )
127
+
128
+ path_pos = match.end()
129
+ if not new_path or len(path) > path_pos:
130
+ raise ValueError, "invalid path"
131
+ return new_path
132
+
133
+
134
+ cdef list _parse_object_path_list(path):
135
+ """Parse object path sequence into a (ns, name, index) list.
136
+ """
137
+ new_path = []
138
+ for item in path:
139
+ item = item.strip()
140
+ if not new_path and item == '':
141
+ # path '.child' => ignore root
142
+ ns = name = None
143
+ index = 0
144
+ else:
145
+ ns, name = cetree.getNsTag(item)
146
+ c_name = _xcstr(name)
147
+ index_pos = tree.xmlStrchr(c_name, c'[')
148
+ if index_pos is NULL:
149
+ index = 0
150
+ else:
151
+ index_end = tree.xmlStrchr(index_pos + 1, c']')
152
+ if index_end is NULL:
153
+ raise ValueError, "index must be enclosed in []"
154
+ index = int(index_pos[1:index_end - index_pos])
155
+ if not new_path and index != 0:
156
+ raise ValueError, "index not allowed on root node"
157
+ name = <bytes>c_name[:index_pos - c_name]
158
+ new_path.append( (ns, name, index) )
159
+ if not new_path:
160
+ raise ValueError, "invalid path"
161
+ return new_path
162
+
163
+
164
+ cdef _ObjectPath* _build_object_path_segments(list path_list) except NULL:
165
+ cdef _ObjectPath* c_path
166
+ cdef _ObjectPath* c_path_segments
167
+ c_path_segments = <_ObjectPath*>python.lxml_malloc(len(path_list), sizeof(_ObjectPath))
168
+ if c_path_segments is NULL:
169
+ raise MemoryError()
170
+ c_path = c_path_segments
171
+ for href, name, index in path_list:
172
+ c_path[0].href = _xcstr(href) if href is not None else NULL
173
+ c_path[0].name = _xcstr(name) if name is not None else NULL
174
+ c_path[0].index = index
175
+ c_path += 1
176
+ return c_path_segments
177
+
178
+
179
+ cdef _find_object_path(_Element root, _ObjectPath* c_path, Py_ssize_t c_path_len, default_value):
180
+ """Follow the path to find the target element.
181
+ """
182
+ cdef tree.xmlNode* c_node
183
+ cdef Py_ssize_t c_index
184
+ c_node = root._c_node
185
+ c_name = c_path[0].name
186
+ c_href = c_path[0].href
187
+ if c_href is NULL or c_href[0] == c'\0':
188
+ c_href = tree._getNs(c_node)
189
+ if not cetree.tagMatches(c_node, c_href, c_name):
190
+ if default_value is not _NO_DEFAULT:
191
+ return default_value
192
+ else:
193
+ raise ValueError(
194
+ f"root element does not match: need {cetree.namespacedNameFromNsName(c_href, c_name)}, got {root.tag}")
195
+
196
+ while c_node is not NULL:
197
+ c_path_len -= 1
198
+ if c_path_len <= 0:
199
+ break
200
+
201
+ c_path += 1
202
+ if c_path[0].href is not NULL:
203
+ c_href = c_path[0].href # otherwise: keep parent namespace
204
+ c_name = tree.xmlDictExists(c_node.doc.dict, c_path[0].name, -1)
205
+ if c_name is NULL:
206
+ c_name = c_path[0].name
207
+ c_node = NULL
208
+ break
209
+ c_index = c_path[0].index
210
+ c_node = c_node.last if c_index < 0 else c_node.children
211
+ c_node = _findFollowingSibling(c_node, c_href, c_name, c_index)
212
+
213
+ if c_node is not NULL:
214
+ return cetree.elementFactory(root._doc, c_node)
215
+ elif default_value is not _NO_DEFAULT:
216
+ return default_value
217
+ else:
218
+ tag = cetree.namespacedNameFromNsName(c_href, c_name)
219
+ raise AttributeError, f"no such child: {tag}"
220
+
221
+
222
+ cdef _create_object_path(_Element root, _ObjectPath* c_path,
223
+ Py_ssize_t c_path_len, int replace, value):
224
+ """Follow the path to find the target element, build the missing children
225
+ as needed and set the target element to 'value'. If replace is true, an
226
+ existing value is replaced, otherwise the new value is added.
227
+ """
228
+ cdef _Element child
229
+ cdef tree.xmlNode* c_node
230
+ cdef tree.xmlNode* c_child
231
+ cdef Py_ssize_t c_index
232
+ if c_path_len == 1:
233
+ raise TypeError, "cannot update root node"
234
+
235
+ c_node = root._c_node
236
+ c_name = c_path[0].name
237
+ c_href = c_path[0].href
238
+ if c_href is NULL or c_href[0] == c'\0':
239
+ c_href = tree._getNs(c_node)
240
+ if not cetree.tagMatches(c_node, c_href, c_name):
241
+ raise ValueError(
242
+ f"root element does not match: need {cetree.namespacedNameFromNsName(c_href, c_name)}, got {root.tag}")
243
+
244
+ while c_path_len > 1:
245
+ c_path_len -= 1
246
+ c_path += 1
247
+ if c_path[0].href is not NULL:
248
+ c_href = c_path[0].href # otherwise: keep parent namespace
249
+ c_index = c_path[0].index
250
+ c_name = tree.xmlDictExists(c_node.doc.dict, c_path[0].name, -1)
251
+ if c_name is NULL:
252
+ c_name = c_path[0].name
253
+ c_child = NULL
254
+ else:
255
+ c_child = c_node.last if c_index < 0 else c_node.children
256
+ c_child = _findFollowingSibling(c_child, c_href, c_name, c_index)
257
+
258
+ if c_child is not NULL:
259
+ c_node = c_child
260
+ elif c_index != 0:
261
+ raise TypeError, "creating indexed path attributes is not supported"
262
+ elif c_path_len == 1:
263
+ _appendValue(cetree.elementFactory(root._doc, c_node),
264
+ cetree.namespacedNameFromNsName(c_href, c_name),
265
+ value)
266
+ return
267
+ else:
268
+ child = cetree.makeSubElement(
269
+ cetree.elementFactory(root._doc, c_node),
270
+ cetree.namespacedNameFromNsName(c_href, c_name),
271
+ None, None, None, None)
272
+ c_node = child._c_node
273
+
274
+ # if we get here, the entire path was already there
275
+ if replace:
276
+ element = cetree.elementFactory(root._doc, c_node)
277
+ _replaceElement(element, value)
278
+ else:
279
+ _appendValue(cetree.elementFactory(root._doc, c_node.parent),
280
+ cetree.namespacedName(c_node), value)
281
+
282
+
283
+ cdef list _build_descendant_paths(tree.xmlNode* c_node, prefix_string):
284
+ """Returns a list of all descendant paths.
285
+ """
286
+ cdef list path, path_list
287
+ tag = cetree.namespacedName(c_node)
288
+ if prefix_string:
289
+ if prefix_string[-1] != '.':
290
+ prefix_string += '.'
291
+ prefix_string = prefix_string + tag
292
+ else:
293
+ prefix_string = tag
294
+ path = [prefix_string]
295
+ path_list = []
296
+ _recursive_build_descendant_paths(c_node, path, path_list)
297
+ return path_list
298
+
299
+
300
+ cdef int _recursive_build_descendant_paths(tree.xmlNode* c_node,
301
+ list path, list path_list) except -1:
302
+ """Fills the list 'path_list' with all descendant paths, initial prefix
303
+ being in the list 'path'.
304
+ """
305
+ cdef tree.xmlNode* c_child
306
+ tags = {}
307
+ path_list.append('.'.join(path))
308
+ c_href = tree._getNs(c_node)
309
+ c_child = c_node.children
310
+ while c_child is not NULL:
311
+ while c_child.type != tree.XML_ELEMENT_NODE:
312
+ c_child = c_child.next
313
+ if c_child is NULL:
314
+ return 0
315
+ if c_href is tree._getNs(c_child):
316
+ tag = pyunicode(c_child.name)
317
+ elif c_href is not NULL and tree._getNs(c_child) is NULL:
318
+ # special case: parent has namespace, child does not
319
+ tag = '{}' + pyunicode(c_child.name)
320
+ else:
321
+ tag = cetree.namespacedName(c_child)
322
+ count = tags.get(tag)
323
+ if count is None:
324
+ tags[tag] = 1
325
+ else:
326
+ tags[tag] = count + 1
327
+ tag += f'[{count}]'
328
+ path.append(tag)
329
+ _recursive_build_descendant_paths(c_child, path, path_list)
330
+ del path[-1]
331
+ c_child = c_child.next
332
+ return 0
.venv/lib/python3.12/site-packages/lxml/parser.pxi ADDED
@@ -0,0 +1,2085 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Parsers for XML and HTML
2
+
3
+ from lxml.includes cimport xmlparser
4
+ from lxml.includes cimport htmlparser
5
+
6
+ cdef object _GenericAlias
7
+ try:
8
+ from types import GenericAlias as _GenericAlias
9
+ except ImportError:
10
+ # Python 3.8 - we only need this as return value from "__class_getitem__"
11
+ def _GenericAlias(cls, item):
12
+ return f"{cls.__name__}[{item.__name__}]"
13
+
14
+
15
+ class ParseError(LxmlSyntaxError):
16
+ """Syntax error while parsing an XML document.
17
+
18
+ For compatibility with ElementTree 1.3 and later.
19
+ """
20
+ def __init__(self, message, code, line, column, filename=None):
21
+ super(_ParseError, self).__init__(message)
22
+ self.lineno, self.offset = (line, column - 1)
23
+ self.code = code
24
+ self.filename = filename
25
+
26
+ @property
27
+ def position(self):
28
+ return self.lineno, self.offset + 1
29
+
30
+ @position.setter
31
+ def position(self, new_pos):
32
+ self.lineno, column = new_pos
33
+ self.offset = column - 1
34
+
35
+ cdef object _ParseError = ParseError
36
+
37
+
38
+ class XMLSyntaxError(ParseError):
39
+ """Syntax error while parsing an XML document.
40
+ """
41
+
42
+ cdef class ParserError(LxmlError):
43
+ """Internal lxml parser error.
44
+ """
45
+
46
+
47
+ @cython.final
48
+ @cython.internal
49
+ cdef class _ParserDictionaryContext:
50
+ # Global parser context to share the string dictionary.
51
+ #
52
+ # This class is a delegate singleton!
53
+ #
54
+ # It creates _ParserDictionaryContext objects for each thread to keep thread state,
55
+ # but those must never be used directly. Always stick to using the static
56
+ # __GLOBAL_PARSER_CONTEXT as defined below the class.
57
+ #
58
+
59
+ cdef tree.xmlDict* _c_dict
60
+ cdef _BaseParser _default_parser
61
+ cdef list _implied_parser_contexts
62
+
63
+ def __cinit__(self):
64
+ self._implied_parser_contexts = []
65
+
66
+ def __dealloc__(self):
67
+ if self._c_dict is not NULL:
68
+ xmlparser.xmlDictFree(self._c_dict)
69
+
70
+ cdef int initMainParserContext(self) except -1:
71
+ """Put the global context into the thread dictionary of the main
72
+ thread. To be called once and only in the main thread."""
73
+ thread_dict = python.PyThreadState_GetDict()
74
+ if thread_dict is not NULL:
75
+ (<dict>thread_dict)["_ParserDictionaryContext"] = self
76
+
77
+ cdef _ParserDictionaryContext _findThreadParserContext(self):
78
+ "Find (or create) the _ParserDictionaryContext object for the current thread"
79
+ cdef _ParserDictionaryContext context
80
+ thread_dict = python.PyThreadState_GetDict()
81
+ if thread_dict is NULL:
82
+ return self
83
+ d = <dict>thread_dict
84
+ result = python.PyDict_GetItem(d, "_ParserDictionaryContext")
85
+ if result is not NULL:
86
+ return <object>result
87
+ context = <_ParserDictionaryContext>_ParserDictionaryContext.__new__(_ParserDictionaryContext)
88
+ d["_ParserDictionaryContext"] = context
89
+ return context
90
+
91
+ cdef int setDefaultParser(self, _BaseParser parser) except -1:
92
+ "Set the default parser for the current thread"
93
+ cdef _ParserDictionaryContext context
94
+ context = self._findThreadParserContext()
95
+ context._default_parser = parser
96
+
97
+ cdef _BaseParser getDefaultParser(self):
98
+ "Return (or create) the default parser of the current thread"
99
+ cdef _ParserDictionaryContext context
100
+ context = self._findThreadParserContext()
101
+ if context._default_parser is None:
102
+ if self._default_parser is None:
103
+ self._default_parser = __DEFAULT_XML_PARSER._copy()
104
+ if context is not self:
105
+ context._default_parser = self._default_parser._copy()
106
+ return context._default_parser
107
+
108
+ cdef tree.xmlDict* _getThreadDict(self, tree.xmlDict* default):
109
+ "Return the thread-local dict or create a new one if necessary."
110
+ cdef _ParserDictionaryContext context
111
+ context = self._findThreadParserContext()
112
+ if context._c_dict is NULL:
113
+ # thread dict not yet set up => use default or create a new one
114
+ if default is not NULL:
115
+ context._c_dict = default
116
+ xmlparser.xmlDictReference(default)
117
+ return default
118
+ if self._c_dict is NULL:
119
+ self._c_dict = xmlparser.xmlDictCreate()
120
+ if context is not self:
121
+ context._c_dict = xmlparser.xmlDictCreateSub(self._c_dict)
122
+ return context._c_dict
123
+
124
+ cdef int initThreadDictRef(self, tree.xmlDict** c_dict_ref) except -1:
125
+ c_dict = c_dict_ref[0]
126
+ c_thread_dict = self._getThreadDict(c_dict)
127
+ if c_dict is c_thread_dict:
128
+ return 0
129
+ if c_dict is not NULL:
130
+ xmlparser.xmlDictFree(c_dict)
131
+ c_dict_ref[0] = c_thread_dict
132
+ xmlparser.xmlDictReference(c_thread_dict)
133
+
134
+ cdef int initParserDict(self, xmlparser.xmlParserCtxt* pctxt) except -1:
135
+ "Assure we always use the same string dictionary."
136
+ self.initThreadDictRef(&pctxt.dict)
137
+ pctxt.dictNames = 1
138
+
139
+ cdef int initXPathParserDict(self, xpath.xmlXPathContext* pctxt) except -1:
140
+ "Assure we always use the same string dictionary."
141
+ self.initThreadDictRef(&pctxt.dict)
142
+
143
+ cdef int initDocDict(self, xmlDoc* result) except -1:
144
+ "Store dict of last object parsed if no shared dict yet"
145
+ # XXX We also free the result dict here if there already was one.
146
+ # This case should only occur for new documents with empty dicts,
147
+ # otherwise we'd free data that's in use => segfault
148
+ self.initThreadDictRef(&result.dict)
149
+
150
+ cdef _ParserContext findImpliedContext(self):
151
+ """Return any current implied xml parser context for the current
152
+ thread. This is used when the resolver functions are called
153
+ with an xmlParserCtxt that was generated from within libxml2
154
+ (i.e. without a _ParserContext) - which happens when parsing
155
+ schema and xinclude external references."""
156
+ cdef _ParserDictionaryContext context
157
+ cdef _ParserContext implied_context
158
+
159
+ # see if we have a current implied parser
160
+ context = self._findThreadParserContext()
161
+ if context._implied_parser_contexts:
162
+ implied_context = context._implied_parser_contexts[-1]
163
+ return implied_context
164
+ return None
165
+
166
+ cdef int pushImpliedContextFromParser(self, _BaseParser parser) except -1:
167
+ "Push a new implied context object taken from the parser."
168
+ if parser is not None:
169
+ self.pushImpliedContext(parser._getParserContext())
170
+ else:
171
+ self.pushImpliedContext(None)
172
+
173
+ cdef int pushImpliedContext(self, _ParserContext parser_context) except -1:
174
+ "Push a new implied context object."
175
+ cdef _ParserDictionaryContext context
176
+ context = self._findThreadParserContext()
177
+ context._implied_parser_contexts.append(parser_context)
178
+
179
+ cdef int popImpliedContext(self) except -1:
180
+ "Pop the current implied context object."
181
+ cdef _ParserDictionaryContext context
182
+ context = self._findThreadParserContext()
183
+ context._implied_parser_contexts.pop()
184
+
185
+ cdef _ParserDictionaryContext __GLOBAL_PARSER_CONTEXT = _ParserDictionaryContext()
186
+ __GLOBAL_PARSER_CONTEXT.initMainParserContext()
187
+
188
+ ############################################################
189
+ ## support for Python unicode I/O
190
+ ############################################################
191
+
192
+ # name of Python Py_UNICODE encoding as known to libxml2
193
+ cdef const_char* _PY_UNICODE_ENCODING = NULL
194
+
195
+ cdef int _setupPythonUnicode() except -1:
196
+ """Sets _PY_UNICODE_ENCODING to the internal encoding name of Python unicode
197
+ strings if libxml2 supports reading native Python unicode. This depends
198
+ on iconv and the local Python installation, so we simply check if we find
199
+ a matching encoding handler.
200
+ """
201
+ cdef tree.xmlCharEncodingHandler* enchandler
202
+ cdef Py_ssize_t l
203
+ cdef const_char* enc
204
+ cdef Py_UNICODE *uchars = [c'<', c't', c'e', c's', c't', c'/', c'>']
205
+ cdef const_xmlChar* buffer = <const_xmlChar*>uchars
206
+ # apparently, libxml2 can't detect UTF-16 on some systems
207
+ if (buffer[0] == c'<' and buffer[1] == c'\0' and
208
+ buffer[2] == c't' and buffer[3] == c'\0'):
209
+ enc = "UTF-16LE"
210
+ elif (buffer[0] == c'\0' and buffer[1] == c'<' and
211
+ buffer[2] == c'\0' and buffer[3] == c't'):
212
+ enc = "UTF-16BE"
213
+ else:
214
+ # let libxml2 give it a try
215
+ enc = _findEncodingName(buffer, sizeof(Py_UNICODE) * 7)
216
+ if enc is NULL:
217
+ # not my fault, it's YOUR broken system :)
218
+ return 0
219
+ enchandler = tree.xmlFindCharEncodingHandler(enc)
220
+ if enchandler is not NULL:
221
+ global _PY_UNICODE_ENCODING
222
+ tree.xmlCharEncCloseFunc(enchandler)
223
+ _PY_UNICODE_ENCODING = enc
224
+ return 0
225
+
226
+ cdef const_char* _findEncodingName(const_xmlChar* buffer, int size) noexcept:
227
+ "Work around bug in libxml2: find iconv name of encoding on our own."
228
+ cdef tree.xmlCharEncoding enc
229
+ enc = tree.xmlDetectCharEncoding(buffer, size)
230
+ if enc == tree.XML_CHAR_ENCODING_UTF16LE:
231
+ if size >= 4 and (buffer[0] == <const_xmlChar> b'\xFF' and
232
+ buffer[1] == <const_xmlChar> b'\xFE' and
233
+ buffer[2] == 0 and buffer[3] == 0):
234
+ return "UTF-32LE" # according to BOM
235
+ else:
236
+ return "UTF-16LE"
237
+ elif enc == tree.XML_CHAR_ENCODING_UTF16BE:
238
+ return "UTF-16BE"
239
+ elif enc == tree.XML_CHAR_ENCODING_UCS4LE:
240
+ return "UCS-4LE"
241
+ elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
242
+ return "UCS-4BE"
243
+ elif enc == tree.XML_CHAR_ENCODING_NONE:
244
+ return NULL
245
+ else:
246
+ # returns a constant char*, no need to free it
247
+ return tree.xmlGetCharEncodingName(enc)
248
+
249
+ # Python 3.12 removed support for "Py_UNICODE".
250
+ if python.PY_VERSION_HEX < 0x030C0000:
251
+ _setupPythonUnicode()
252
+
253
+
254
+ cdef unicode _find_PyUCS4EncodingName():
255
+ """
256
+ Find a suitable encoding for Py_UCS4 PyUnicode strings in libxml2.
257
+ """
258
+ ustring = "<xml>\U0001F92A</xml>"
259
+ cdef const xmlChar* buffer = <const xmlChar*> python.PyUnicode_DATA(ustring)
260
+ cdef Py_ssize_t py_buffer_len = python.PyUnicode_GET_LENGTH(ustring)
261
+
262
+ encoding_name = ''
263
+ cdef tree.xmlCharEncoding enc = tree.xmlDetectCharEncoding(buffer, py_buffer_len)
264
+ enchandler = tree.xmlGetCharEncodingHandler(enc)
265
+ if enchandler is not NULL:
266
+ try:
267
+ if enchandler.name:
268
+ encoding_name = enchandler.name.decode('UTF-8')
269
+ finally:
270
+ tree.xmlCharEncCloseFunc(enchandler)
271
+ else:
272
+ c_name = tree.xmlGetCharEncodingName(enc)
273
+ if c_name:
274
+ encoding_name = c_name.decode('UTF-8')
275
+
276
+
277
+ if encoding_name and not encoding_name.endswith('LE') and not encoding_name.endswith('BE'):
278
+ encoding_name += 'BE' if python.PY_BIG_ENDIAN else 'LE'
279
+ return encoding_name or None
280
+
281
+ _pyucs4_encoding_name = _find_PyUCS4EncodingName()
282
+
283
+
284
+ ############################################################
285
+ ## support for file-like objects
286
+ ############################################################
287
+
288
+ @cython.final
289
+ @cython.internal
290
+ cdef class _FileReaderContext:
291
+ cdef object _filelike
292
+ cdef object _encoding
293
+ cdef object _url
294
+ cdef object _bytes
295
+ cdef _ExceptionContext _exc_context
296
+ cdef Py_ssize_t _bytes_read
297
+ cdef char* _c_url
298
+ cdef bint _close_file_after_read
299
+
300
+ def __cinit__(self, filelike, exc_context not None, url, encoding=None, bint close_file=False):
301
+ self._exc_context = exc_context
302
+ self._filelike = filelike
303
+ self._close_file_after_read = close_file
304
+ self._encoding = encoding
305
+ if url is not None:
306
+ url = _encodeFilename(url)
307
+ self._c_url = _cstr(url)
308
+ self._url = url
309
+ self._bytes = b''
310
+ self._bytes_read = 0
311
+
312
+ cdef _close_file(self):
313
+ if self._filelike is None or not self._close_file_after_read:
314
+ return
315
+ try:
316
+ close = self._filelike.close
317
+ except AttributeError:
318
+ close = None
319
+ finally:
320
+ self._filelike = None
321
+ if close is not None:
322
+ close()
323
+
324
+ cdef xmlparser.xmlParserInputBuffer* _createParserInputBuffer(self) noexcept:
325
+ cdef xmlparser.xmlParserInputBuffer* c_buffer = xmlparser.xmlAllocParserInputBuffer(0)
326
+ if c_buffer:
327
+ c_buffer.readcallback = _readFilelikeParser
328
+ c_buffer.context = <python.PyObject*> self
329
+ return c_buffer
330
+
331
+ cdef xmlparser.xmlParserInput* _createParserInput(
332
+ self, xmlparser.xmlParserCtxt* ctxt) noexcept:
333
+ cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
334
+ if not c_buffer:
335
+ return NULL
336
+ return xmlparser.xmlNewIOInputStream(ctxt, c_buffer, 0)
337
+
338
+ cdef tree.xmlDtd* _readDtd(self) noexcept:
339
+ cdef xmlparser.xmlParserInputBuffer* c_buffer = self._createParserInputBuffer()
340
+ if not c_buffer:
341
+ return NULL
342
+ with nogil:
343
+ return xmlparser.xmlIOParseDTD(NULL, c_buffer, 0)
344
+
345
+ cdef xmlDoc* _readDoc(self, xmlparser.xmlParserCtxt* ctxt, int options) noexcept:
346
+ cdef xmlDoc* result
347
+ cdef void* c_callback_context = <python.PyObject*> self
348
+ cdef char* c_encoding = _cstr(self._encoding) if self._encoding is not None else NULL
349
+
350
+ orig_options = ctxt.options
351
+ with nogil:
352
+ if ctxt.html:
353
+ result = htmlparser.htmlCtxtReadIO(
354
+ ctxt, _readFilelikeParser, NULL, c_callback_context,
355
+ self._c_url, c_encoding, options)
356
+ if result is not NULL:
357
+ if _fixHtmlDictNames(ctxt.dict, result) < 0:
358
+ tree.xmlFreeDoc(result)
359
+ result = NULL
360
+ else:
361
+ result = xmlparser.xmlCtxtReadIO(
362
+ ctxt, _readFilelikeParser, NULL, c_callback_context,
363
+ self._c_url, c_encoding, options)
364
+ ctxt.options = orig_options # work around libxml2 problem
365
+
366
+ try:
367
+ self._close_file()
368
+ except:
369
+ self._exc_context._store_raised()
370
+ finally:
371
+ return result # swallow any exceptions
372
+
373
+ cdef int copyToBuffer(self, char* c_buffer, int c_requested) noexcept:
374
+ cdef int c_byte_count = 0
375
+ cdef char* c_start
376
+ cdef Py_ssize_t byte_count, remaining
377
+ if self._bytes_read < 0:
378
+ return 0
379
+ try:
380
+ byte_count = python.PyBytes_GET_SIZE(self._bytes)
381
+ remaining = byte_count - self._bytes_read
382
+ while c_requested > remaining:
383
+ c_start = _cstr(self._bytes) + self._bytes_read
384
+ cstring_h.memcpy(c_buffer, c_start, remaining)
385
+ c_byte_count += remaining
386
+ c_buffer += remaining
387
+ c_requested -= remaining
388
+
389
+ self._bytes = self._filelike.read(c_requested)
390
+ if not isinstance(self._bytes, bytes):
391
+ if isinstance(self._bytes, unicode):
392
+ if self._encoding is None:
393
+ self._bytes = (<unicode>self._bytes).encode('utf8')
394
+ else:
395
+ self._bytes = python.PyUnicode_AsEncodedString(
396
+ self._bytes, _cstr(self._encoding), NULL)
397
+ else:
398
+ self._close_file()
399
+ raise TypeError, \
400
+ "reading from file-like objects must return byte strings or unicode strings"
401
+
402
+ remaining = python.PyBytes_GET_SIZE(self._bytes)
403
+ if remaining == 0:
404
+ self._bytes_read = -1
405
+ self._close_file()
406
+ return c_byte_count
407
+ self._bytes_read = 0
408
+
409
+ if c_requested > 0:
410
+ c_start = _cstr(self._bytes) + self._bytes_read
411
+ cstring_h.memcpy(c_buffer, c_start, c_requested)
412
+ c_byte_count += c_requested
413
+ self._bytes_read += c_requested
414
+ except:
415
+ c_byte_count = -1
416
+ self._exc_context._store_raised()
417
+ try:
418
+ self._close_file()
419
+ except:
420
+ self._exc_context._store_raised()
421
+ finally:
422
+ return c_byte_count # swallow any exceptions
423
+
424
+ cdef int _readFilelikeParser(void* ctxt, char* c_buffer, int c_size) noexcept with gil:
425
+ return (<_FileReaderContext>ctxt).copyToBuffer(c_buffer, c_size)
426
+
427
+
428
+ ############################################################
429
+ ## support for custom document loaders
430
+ ############################################################
431
+
432
+ cdef xmlparser.xmlParserInput* _local_resolver(const_char* c_url, const_char* c_pubid,
433
+ xmlparser.xmlParserCtxt* c_context) noexcept with gil:
434
+ cdef _ResolverContext context
435
+ cdef xmlparser.xmlParserInput* c_input
436
+ cdef _InputDocument doc_ref
437
+ cdef _FileReaderContext file_context
438
+ # if there is no _ParserContext associated with the xmlParserCtxt
439
+ # passed, check to see if the thread state object has an implied
440
+ # context.
441
+ if c_context._private is not NULL:
442
+ context = <_ResolverContext>c_context._private
443
+ else:
444
+ context = __GLOBAL_PARSER_CONTEXT.findImpliedContext()
445
+
446
+ if context is None:
447
+ if __DEFAULT_ENTITY_LOADER is NULL:
448
+ return NULL
449
+ with nogil:
450
+ # free the GIL as we might do serious I/O here (e.g. HTTP)
451
+ c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
452
+ return c_input
453
+
454
+ try:
455
+ if c_url is NULL:
456
+ url = None
457
+ else:
458
+ # parsing a related document (DTD etc.) => UTF-8 encoded URL?
459
+ url = _decodeFilename(<const_xmlChar*>c_url)
460
+ if c_pubid is NULL:
461
+ pubid = None
462
+ else:
463
+ pubid = funicode(<const_xmlChar*>c_pubid) # always UTF-8
464
+
465
+ doc_ref = context._resolvers.resolve(url, pubid, context)
466
+ except:
467
+ context._store_raised()
468
+ return NULL
469
+
470
+ if doc_ref is not None:
471
+ if doc_ref._type == PARSER_DATA_STRING:
472
+ data = doc_ref._data_bytes
473
+ filename = doc_ref._filename
474
+ if not filename:
475
+ filename = None
476
+ elif not isinstance(filename, bytes):
477
+ # most likely a text URL
478
+ filename = filename.encode('utf8')
479
+ if not isinstance(filename, bytes):
480
+ filename = None
481
+
482
+ if tree.LIBXML_VERSION >= 21400:
483
+ c_filename = <char *>tree.xmlStrdup(_xcstr(filename)) if filename is not None else NULL
484
+ c_input = xmlparser.xmlNewInputFromMemory(
485
+ c_filename, _xcstr(data), <size_t> python.PyBytes_GET_SIZE(data), 0)
486
+ else:
487
+ c_input = xmlparser.xmlNewInputStream(c_context)
488
+ if c_input is not NULL:
489
+ if filename is not None:
490
+ c_input.filename = <char *>tree.xmlStrdup(_xcstr(filename))
491
+ c_input.base = _xcstr(data)
492
+ c_input.length = python.PyBytes_GET_SIZE(data)
493
+ c_input.cur = c_input.base
494
+ c_input.end = c_input.base + c_input.length
495
+ elif doc_ref._type == PARSER_DATA_FILENAME:
496
+ data = None
497
+ c_filename = _cstr(doc_ref._filename)
498
+ with nogil:
499
+ # free the GIL as we might do serious I/O here
500
+ c_input = xmlparser.xmlNewInputFromFile(
501
+ c_context, c_filename)
502
+ elif doc_ref._type == PARSER_DATA_FILE:
503
+ file_context = _FileReaderContext(doc_ref._file, context, url,
504
+ None, doc_ref._close_file)
505
+ c_input = file_context._createParserInput(c_context)
506
+ data = file_context
507
+ else:
508
+ data = None
509
+ c_input = NULL
510
+
511
+ if data is not None:
512
+ context._storage.add(data)
513
+ if c_input is not NULL:
514
+ return c_input
515
+
516
+ if __DEFAULT_ENTITY_LOADER is NULL:
517
+ return NULL
518
+
519
+ with nogil:
520
+ # free the GIL as we might do serious I/O here (e.g. HTTP)
521
+ c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
522
+ return c_input
523
+
524
+ cdef xmlparser.xmlExternalEntityLoader __DEFAULT_ENTITY_LOADER
525
+ __DEFAULT_ENTITY_LOADER = xmlparser.xmlGetExternalEntityLoader()
526
+
527
+
528
+ cdef xmlparser.xmlExternalEntityLoader _register_document_loader() noexcept nogil:
529
+ cdef xmlparser.xmlExternalEntityLoader old = xmlparser.xmlGetExternalEntityLoader()
530
+ xmlparser.xmlSetExternalEntityLoader(<xmlparser.xmlExternalEntityLoader> _local_resolver)
531
+ return old
532
+
533
+ cdef void _reset_document_loader(xmlparser.xmlExternalEntityLoader old) noexcept nogil:
534
+ xmlparser.xmlSetExternalEntityLoader(old)
535
+
536
+
537
+ ############################################################
538
+ ## Parsers
539
+ ############################################################
540
+
541
+ @cython.no_gc_clear # May have to call "self._validator.disconnect()" on dealloc.
542
+ @cython.internal
543
+ cdef class _ParserContext(_ResolverContext):
544
+ cdef _ErrorLog _error_log
545
+ cdef _ParserSchemaValidationContext _validator
546
+ cdef xmlparser.xmlParserCtxt* _c_ctxt
547
+ cdef xmlparser.xmlExternalEntityLoader _orig_loader
548
+ cdef python.PyThread_type_lock _lock
549
+ cdef _Document _doc
550
+ cdef bint _collect_ids
551
+
552
+ def __cinit__(self):
553
+ self._collect_ids = True
554
+ if config.ENABLE_THREADING:
555
+ self._lock = python.PyThread_allocate_lock()
556
+ self._error_log = _ErrorLog()
557
+
558
+ def __dealloc__(self):
559
+ if config.ENABLE_THREADING and self._lock is not NULL:
560
+ python.PyThread_free_lock(self._lock)
561
+ self._lock = NULL
562
+ if self._c_ctxt is not NULL:
563
+ if <void*>self._validator is not NULL and self._validator is not None:
564
+ # If the parser was not closed correctly (e.g. interrupted iterparse()),
565
+ # and the schema validator wasn't freed and cleaned up yet, the libxml2 SAX
566
+ # validator plug might still be in place, which will make xmlFreeParserCtxt()
567
+ # crash when trying to xmlFree() a static SAX handler.
568
+ # Thus, make sure we disconnect the handler interceptor here at the latest.
569
+ self._validator.disconnect()
570
+ xmlparser.xmlFreeParserCtxt(self._c_ctxt)
571
+
572
+ cdef _ParserContext _copy(self):
573
+ cdef _ParserContext context
574
+ context = self.__class__()
575
+ context._collect_ids = self._collect_ids
576
+ context._validator = self._validator.copy()
577
+ _initParserContext(context, self._resolvers._copy(), NULL)
578
+ return context
579
+
580
+ cdef void _initParserContext(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
581
+ """
582
+ Connects the libxml2-level context to the lxml-level parser context.
583
+ """
584
+ self._c_ctxt = c_ctxt
585
+ c_ctxt._private = <void*>self
586
+
587
+ cdef void _resetParserContext(self) noexcept:
588
+ if self._c_ctxt is not NULL:
589
+ if self._c_ctxt.html:
590
+ htmlparser.htmlCtxtReset(self._c_ctxt)
591
+ self._c_ctxt.disableSAX = 0 # work around bug in libxml2
592
+ else:
593
+ xmlparser.xmlClearParserCtxt(self._c_ctxt)
594
+ # work around bug in libxml2 [2.9.10 .. 2.9.14]:
595
+ # https://gitlab.gnome.org/GNOME/libxml2/-/issues/378
596
+ self._c_ctxt.nsNr = 0
597
+
598
+ cdef int prepare(self, bint set_document_loader=True) except -1:
599
+ cdef int result
600
+ if config.ENABLE_THREADING and self._lock is not NULL:
601
+ with nogil:
602
+ result = python.PyThread_acquire_lock(
603
+ self._lock, python.WAIT_LOCK)
604
+ if result == 0:
605
+ raise ParserError, "parser locking failed"
606
+ self._error_log.clear()
607
+ self._doc = None
608
+ # Connect the lxml error log with libxml2's error handling. In the case of parsing
609
+ # HTML, ctxt->sax is not set to null, so this always works. The libxml2 function
610
+ # that does this is htmlInitParserCtxt in HTMLparser.c. For HTML (and possibly XML
611
+ # too), libxml2's SAX's serror is set to be the place where errors are sent when
612
+ # schannel is set to ctxt->sax->serror in xmlCtxtErrMemory in libxml2's
613
+ # parserInternals.c.
614
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
615
+ self._c_ctxt.sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
616
+ self._orig_loader = _register_document_loader() if set_document_loader else NULL
617
+ if self._validator is not None:
618
+ self._validator.connect(self._c_ctxt, self._error_log)
619
+ return 0
620
+
621
+ cdef int cleanup(self) except -1:
622
+ if self._orig_loader is not NULL:
623
+ _reset_document_loader(self._orig_loader)
624
+ try:
625
+ if self._validator is not None:
626
+ self._validator.disconnect()
627
+ self._resetParserContext()
628
+ self.clear()
629
+ self._doc = None
630
+ self._c_ctxt.sax.serror = NULL
631
+ finally:
632
+ if config.ENABLE_THREADING and self._lock is not NULL:
633
+ python.PyThread_release_lock(self._lock)
634
+ return 0
635
+
636
+ cdef object _handleParseResult(self, _BaseParser parser,
637
+ xmlDoc* result, filename):
638
+ c_doc = self._handleParseResultDoc(parser, result, filename)
639
+ if self._doc is not None and self._doc._c_doc is c_doc:
640
+ return self._doc
641
+ else:
642
+ return _documentFactory(c_doc, parser)
643
+
644
+ cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser,
645
+ xmlDoc* result, filename) except NULL:
646
+ recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
647
+ return _handleParseResult(self, self._c_ctxt, result,
648
+ filename, recover,
649
+ free_doc=self._doc is None)
650
+
651
+ cdef _initParserContext(_ParserContext context,
652
+ _ResolverRegistry resolvers,
653
+ xmlparser.xmlParserCtxt* c_ctxt):
654
+ _initResolverContext(context, resolvers)
655
+ if c_ctxt is not NULL:
656
+ context._initParserContext(c_ctxt)
657
+
658
+ cdef void _forwardParserError(xmlparser.xmlParserCtxt* _parser_context, const xmlerror.xmlError* error) noexcept with gil:
659
+ """
660
+ Add an error created by libxml2 to the lxml-level error_log.
661
+ """
662
+ (<_ParserContext>_parser_context._private)._error_log._receive(error)
663
+
664
+ cdef void _receiveParserError(void* c_context, const xmlerror.xmlError* error) noexcept nogil:
665
+ if __DEBUG:
666
+ if c_context is NULL or (<xmlparser.xmlParserCtxt*>c_context)._private is NULL:
667
+ _forwardError(NULL, error)
668
+ else:
669
+ _forwardParserError(<xmlparser.xmlParserCtxt*>c_context, error)
670
+
671
+ cdef int _raiseParseError(xmlparser.xmlParserCtxt* ctxt, filename,
672
+ _ErrorLog error_log) except -1:
673
+ if filename is not None and \
674
+ ctxt.lastError.domain == xmlerror.XML_FROM_IO:
675
+ if isinstance(filename, bytes):
676
+ filename = _decodeFilenameWithLength(
677
+ <bytes>filename, len(<bytes>filename))
678
+ if ctxt.lastError.message is not NULL:
679
+ try:
680
+ message = ctxt.lastError.message.decode('utf-8')
681
+ except UnicodeDecodeError:
682
+ # the filename may be in there => play it safe
683
+ message = ctxt.lastError.message.decode('iso8859-1')
684
+ message = f"Error reading file '{filename}': {message.strip()}"
685
+ else:
686
+ message = f"Error reading '{filename}'"
687
+ raise IOError, message
688
+ elif error_log:
689
+ raise error_log._buildParseException(
690
+ XMLSyntaxError, "Document is not well formed")
691
+ elif ctxt.lastError.message is not NULL:
692
+ message = ctxt.lastError.message.strip()
693
+ code = ctxt.lastError.code
694
+ line = ctxt.lastError.line
695
+ column = ctxt.lastError.int2
696
+ if ctxt.lastError.line > 0:
697
+ message = f"line {line}: {message}"
698
+ raise XMLSyntaxError(message, code, line, column, filename)
699
+ else:
700
+ raise XMLSyntaxError(None, xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
701
+ filename)
702
+
703
+ cdef xmlDoc* _handleParseResult(_ParserContext context,
704
+ xmlparser.xmlParserCtxt* c_ctxt,
705
+ xmlDoc* result, filename,
706
+ bint recover, bint free_doc) except NULL:
707
+ # The C-level argument xmlDoc* result is passed in as NULL if the parser was not able
708
+ # to parse the document.
709
+ cdef bint well_formed
710
+ if result is not NULL:
711
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
712
+
713
+ if c_ctxt.myDoc is not NULL:
714
+ if c_ctxt.myDoc is not result:
715
+ __GLOBAL_PARSER_CONTEXT.initDocDict(c_ctxt.myDoc)
716
+ tree.xmlFreeDoc(c_ctxt.myDoc)
717
+ c_ctxt.myDoc = NULL
718
+
719
+ if result is not NULL:
720
+ # "wellFormed" in libxml2 is 0 if the parser found fatal errors. It still returns a
721
+ # parse result document if 'recover=True'. Here, we determine if we can present
722
+ # the document to the user or consider it incorrect or broken enough to raise an error.
723
+ if (context._validator is not None and
724
+ not context._validator.isvalid()):
725
+ well_formed = 0 # actually not 'valid', but anyway ...
726
+ elif (not c_ctxt.wellFormed and not c_ctxt.html and
727
+ c_ctxt.charset == tree.XML_CHAR_ENCODING_8859_1 and
728
+ [1 for error in context._error_log
729
+ if error.type == ErrorTypes.ERR_INVALID_CHAR]):
730
+ # An encoding error occurred and libxml2 switched from UTF-8
731
+ # input to (undecoded) Latin-1, at some arbitrary point in the
732
+ # document. Better raise an error than allowing for a broken
733
+ # tree with mixed encodings. This is fixed in libxml2 2.12.
734
+ well_formed = 0
735
+ elif recover or (c_ctxt.wellFormed and
736
+ c_ctxt.lastError.level < xmlerror.XML_ERR_ERROR):
737
+ well_formed = 1
738
+ elif not c_ctxt.replaceEntities and not c_ctxt.validate \
739
+ and context is not None:
740
+ # in this mode, we ignore errors about undefined entities
741
+ for error in context._error_log.filter_from_errors():
742
+ if error.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
743
+ error.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
744
+ well_formed = 0
745
+ break
746
+ else:
747
+ well_formed = 1
748
+ else:
749
+ well_formed = 0
750
+
751
+ if not well_formed:
752
+ if free_doc:
753
+ tree.xmlFreeDoc(result)
754
+ result = NULL
755
+
756
+ if context is not None and context._has_raised():
757
+ if result is not NULL:
758
+ if free_doc:
759
+ tree.xmlFreeDoc(result)
760
+ result = NULL
761
+ context._raise_if_stored()
762
+
763
+ if result is NULL:
764
+ if context is not None:
765
+ _raiseParseError(c_ctxt, filename, context._error_log)
766
+ else:
767
+ _raiseParseError(c_ctxt, filename, None)
768
+ else:
769
+ if result.URL is NULL and filename is not None:
770
+ result.URL = tree.xmlStrdup(_xcstr(filename))
771
+ if result.encoding is NULL:
772
+ result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
773
+
774
+ if context._validator is not None and \
775
+ context._validator._add_default_attributes:
776
+ # we currently need to do this here as libxml2 does not
777
+ # support inserting default attributes during parse-time
778
+ # validation
779
+ context._validator.inject_default_attributes(result)
780
+
781
+ return result
782
+
783
+ cdef int _fixHtmlDictNames(tree.xmlDict* c_dict, xmlDoc* c_doc) noexcept nogil:
784
+ cdef xmlNode* c_node
785
+ if c_doc is NULL:
786
+ return 0
787
+ c_node = c_doc.children
788
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
789
+ if c_node.type == tree.XML_ELEMENT_NODE:
790
+ if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
791
+ return -1
792
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
793
+ return 0
794
+
795
+ cdef int _fixHtmlDictSubtreeNames(tree.xmlDict* c_dict, xmlDoc* c_doc,
796
+ xmlNode* c_start_node) noexcept nogil:
797
+ """
798
+ Move names to the dict, iterating in document order, starting at
799
+ c_start_node. This is used in incremental parsing after each chunk.
800
+ """
801
+ cdef xmlNode* c_node
802
+ if not c_doc:
803
+ return 0
804
+ if not c_start_node:
805
+ return _fixHtmlDictNames(c_dict, c_doc)
806
+ c_node = c_start_node
807
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
808
+ if c_node.type == tree.XML_ELEMENT_NODE:
809
+ if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
810
+ return -1
811
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
812
+ return 0
813
+
814
+ cdef inline int _fixHtmlDictNodeNames(tree.xmlDict* c_dict,
815
+ xmlNode* c_node) noexcept nogil:
816
+ cdef xmlNode* c_attr
817
+ c_name = tree.xmlDictLookup(c_dict, c_node.name, -1)
818
+ if c_name is NULL:
819
+ return -1
820
+ if c_name is not c_node.name:
821
+ tree.xmlFree(<char*>c_node.name)
822
+ c_node.name = c_name
823
+ c_attr = <xmlNode*>c_node.properties
824
+ while c_attr is not NULL:
825
+ c_name = tree.xmlDictLookup(c_dict, c_attr.name, -1)
826
+ if c_name is NULL:
827
+ return -1
828
+ if c_name is not c_attr.name:
829
+ tree.xmlFree(<char*>c_attr.name)
830
+ c_attr.name = c_name
831
+ c_attr = c_attr.next
832
+ return 0
833
+
834
+
835
+ @cython.internal
836
+ cdef class _BaseParser:
837
+ cdef ElementClassLookup _class_lookup
838
+ cdef _ResolverRegistry _resolvers
839
+ cdef _ParserContext _parser_context
840
+ cdef _ParserContext _push_parser_context
841
+ cdef int _parse_options
842
+ cdef bint _for_html
843
+ cdef bint _remove_comments
844
+ cdef bint _remove_pis
845
+ cdef bint _strip_cdata
846
+ cdef bint _collect_ids
847
+ cdef bint _resolve_external_entities
848
+ cdef XMLSchema _schema
849
+ cdef bytes _filename
850
+ cdef readonly object target
851
+ cdef object _default_encoding
852
+ cdef tuple _events_to_collect # (event_types, tag)
853
+
854
+ def __init__(self, int parse_options, bint for_html, XMLSchema schema,
855
+ remove_comments, remove_pis, strip_cdata, collect_ids,
856
+ target, encoding, bint resolve_external_entities=True):
857
+ cdef tree.xmlCharEncodingHandler* enchandler
858
+ cdef int c_encoding
859
+ if not isinstance(self, (XMLParser, HTMLParser)):
860
+ raise TypeError, "This class cannot be instantiated"
861
+
862
+ if not collect_ids and tree.LIBXML_VERSION >= 21500:
863
+ parse_options |= xmlparser.XML_PARSE_SKIP_IDS
864
+
865
+ self._parse_options = parse_options
866
+ self.target = target
867
+ self._for_html = for_html
868
+ self._remove_comments = remove_comments
869
+ self._remove_pis = remove_pis
870
+ self._strip_cdata = strip_cdata
871
+ self._collect_ids = collect_ids
872
+ self._resolve_external_entities = resolve_external_entities
873
+ self._schema = schema
874
+
875
+ self._resolvers = _ResolverRegistry()
876
+
877
+ if encoding is None:
878
+ self._default_encoding = None
879
+ else:
880
+ encoding = _utf8(encoding)
881
+ enchandler = tree.xmlFindCharEncodingHandler(_cstr(encoding))
882
+ if enchandler is NULL:
883
+ raise LookupError, f"unknown encoding: '{encoding}'"
884
+ tree.xmlCharEncCloseFunc(enchandler)
885
+ self._default_encoding = encoding
886
+
887
+ cdef _setBaseURL(self, base_url):
888
+ self._filename = _encodeFilename(base_url)
889
+
890
+ cdef _collectEvents(self, event_types, tag):
891
+ if event_types is None:
892
+ event_types = ()
893
+ else:
894
+ event_types = tuple(set(event_types))
895
+ _buildParseEventFilter(event_types) # purely for validation
896
+ self._events_to_collect = (event_types, tag)
897
+
898
+ cdef _ParserContext _getParserContext(self):
899
+ cdef xmlparser.xmlParserCtxt* pctxt
900
+ if self._parser_context is None:
901
+ self._parser_context = self._createContext(self.target, None)
902
+ self._parser_context._collect_ids = self._collect_ids
903
+ if self._schema is not None:
904
+ self._parser_context._validator = \
905
+ self._schema._newSaxValidator(
906
+ self._parse_options & xmlparser.XML_PARSE_DTDATTR)
907
+ pctxt = self._newParserCtxt()
908
+ _initParserContext(self._parser_context, self._resolvers, pctxt)
909
+ self._configureSaxContext(pctxt)
910
+ return self._parser_context
911
+
912
+ cdef _ParserContext _getPushParserContext(self):
913
+ cdef xmlparser.xmlParserCtxt* pctxt
914
+ if self._push_parser_context is None:
915
+ self._push_parser_context = self._createContext(
916
+ self.target, self._events_to_collect)
917
+ self._push_parser_context._collect_ids = self._collect_ids
918
+ if self._schema is not None:
919
+ self._push_parser_context._validator = \
920
+ self._schema._newSaxValidator(
921
+ self._parse_options & xmlparser.XML_PARSE_DTDATTR)
922
+ pctxt = self._newPushParserCtxt()
923
+ _initParserContext(
924
+ self._push_parser_context, self._resolvers, pctxt)
925
+ self._configureSaxContext(pctxt)
926
+ return self._push_parser_context
927
+
928
+ cdef _ParserContext _createContext(self, target, events_to_collect):
929
+ """
930
+ This method creates and configures the lxml-level parser.
931
+ """
932
+ cdef _SaxParserContext sax_context
933
+ if target is not None:
934
+ sax_context = _TargetParserContext(self)
935
+ (<_TargetParserContext>sax_context)._setTarget(target)
936
+ elif events_to_collect:
937
+ sax_context = _SaxParserContext(self)
938
+ else:
939
+ # nothing special to configure
940
+ return _ParserContext()
941
+ if events_to_collect:
942
+ events, tag = events_to_collect
943
+ sax_context._setEventFilter(events, tag)
944
+ return sax_context
945
+
946
+ @cython.final
947
+ cdef int _configureSaxContext(self, xmlparser.xmlParserCtxt* pctxt) except -1:
948
+ if self._remove_comments:
949
+ pctxt.sax.comment = NULL
950
+ if self._remove_pis:
951
+ pctxt.sax.processingInstruction = NULL
952
+ if self._strip_cdata:
953
+ # hard switch-off for CDATA nodes => makes them plain text
954
+ pctxt.sax.cdataBlock = NULL
955
+ if not self._resolve_external_entities:
956
+ pctxt.sax.getEntity = _getInternalEntityOnly
957
+ pctxt.sax.getParameterEntity = NULL # Disable parameter entities completely.
958
+
959
+ cdef int _registerHtmlErrorHandler(self, xmlparser.xmlParserCtxt* c_ctxt) except -1:
960
+ cdef xmlparser.xmlSAXHandler* sax = c_ctxt.sax
961
+ if sax is not NULL and sax.initialized and sax.initialized != xmlparser.XML_SAX2_MAGIC:
962
+ # need to extend SAX1 context to SAX2 to get proper error reports
963
+ if <xmlparser.xmlSAXHandlerV1*>sax is &htmlparser.htmlDefaultSAXHandler:
964
+ sax = <xmlparser.xmlSAXHandler*> tree.xmlMalloc(sizeof(xmlparser.xmlSAXHandler))
965
+ if sax is NULL:
966
+ raise MemoryError()
967
+ cstring_h.memcpy(sax, &htmlparser.htmlDefaultSAXHandler,
968
+ sizeof(htmlparser.htmlDefaultSAXHandler))
969
+ c_ctxt.sax = sax
970
+ sax.initialized = xmlparser.XML_SAX2_MAGIC
971
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
972
+ sax.serror = <xmlerror.xmlStructuredErrorFunc> _receiveParserError
973
+ sax.startElementNs = NULL
974
+ sax.endElementNs = NULL
975
+ sax._private = NULL
976
+ return 0
977
+
978
+ cdef xmlparser.xmlParserCtxt* _newParserCtxt(self) except NULL:
979
+ """
980
+ Create and initialise a libxml2-level parser context.
981
+ """
982
+ cdef xmlparser.xmlParserCtxt* c_ctxt
983
+ if self._for_html:
984
+ c_ctxt = htmlparser.htmlCreateMemoryParserCtxt('dummy', 5)
985
+ if c_ctxt is not NULL:
986
+ self._registerHtmlErrorHandler(c_ctxt)
987
+ else:
988
+ c_ctxt = xmlparser.xmlNewParserCtxt()
989
+ if c_ctxt is NULL:
990
+ raise MemoryError
991
+ c_ctxt.sax.startDocument = _initSaxDocument
992
+ return c_ctxt
993
+
994
+ cdef xmlparser.xmlParserCtxt* _newPushParserCtxt(self) except NULL:
995
+ cdef xmlparser.xmlParserCtxt* c_ctxt
996
+ cdef char* c_filename = _cstr(self._filename) if self._filename is not None else NULL
997
+ if self._for_html:
998
+ c_ctxt = htmlparser.htmlCreatePushParserCtxt(
999
+ NULL, NULL, NULL, 0, c_filename, tree.XML_CHAR_ENCODING_NONE)
1000
+ if c_ctxt is not NULL:
1001
+ self._registerHtmlErrorHandler(c_ctxt)
1002
+ htmlparser.htmlCtxtUseOptions(c_ctxt, self._parse_options)
1003
+ else:
1004
+ c_ctxt = xmlparser.xmlCreatePushParserCtxt(
1005
+ NULL, NULL, NULL, 0, c_filename)
1006
+ if c_ctxt is not NULL:
1007
+ xmlparser.xmlCtxtUseOptions(c_ctxt, self._parse_options)
1008
+ if c_ctxt is NULL:
1009
+ raise MemoryError()
1010
+ c_ctxt.sax.startDocument = _initSaxDocument
1011
+ return c_ctxt
1012
+
1013
+ @property
1014
+ def error_log(self):
1015
+ """The error log of the last parser run.
1016
+ """
1017
+ cdef _ParserContext context
1018
+ context = self._getParserContext()
1019
+ return context._error_log.copy()
1020
+
1021
+ @property
1022
+ def resolvers(self):
1023
+ """The custom resolver registry of this parser."""
1024
+ return self._resolvers
1025
+
1026
+ @property
1027
+ def version(self):
1028
+ """The version of the underlying XML parser."""
1029
+ return "libxml2 %d.%d.%d" % LIBXML_VERSION
1030
+
1031
+ def set_element_class_lookup(self, ElementClassLookup lookup = None):
1032
+ """set_element_class_lookup(self, lookup = None)
1033
+
1034
+ Set a lookup scheme for element classes generated from this parser.
1035
+
1036
+ Reset it by passing None or nothing.
1037
+ """
1038
+ self._class_lookup = lookup
1039
+
1040
+ cdef _BaseParser _copy(self):
1041
+ "Create a new parser with the same configuration."
1042
+ cdef _BaseParser parser
1043
+ parser = self.__class__()
1044
+ parser._parse_options = self._parse_options
1045
+ parser._for_html = self._for_html
1046
+ parser._remove_comments = self._remove_comments
1047
+ parser._remove_pis = self._remove_pis
1048
+ parser._strip_cdata = self._strip_cdata
1049
+ parser._filename = self._filename
1050
+ parser._resolvers = self._resolvers
1051
+ parser.target = self.target
1052
+ parser._class_lookup = self._class_lookup
1053
+ parser._default_encoding = self._default_encoding
1054
+ parser._schema = self._schema
1055
+ parser._events_to_collect = self._events_to_collect
1056
+ return parser
1057
+
1058
+ def copy(self):
1059
+ """copy(self)
1060
+
1061
+ Create a new parser with the same configuration.
1062
+ """
1063
+ return self._copy()
1064
+
1065
+ def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
1066
+ """makeelement(self, _tag, attrib=None, nsmap=None, **_extra)
1067
+
1068
+ Creates a new element associated with this parser.
1069
+ """
1070
+ return _makeElement(_tag, NULL, None, self, None, None,
1071
+ attrib, nsmap, _extra)
1072
+
1073
+ # internal parser methods
1074
+
1075
+ cdef xmlDoc* _parseUnicodeDoc(self, utext, char* c_filename) except NULL:
1076
+ """Parse unicode document, share dictionary if possible.
1077
+ """
1078
+ cdef _ParserContext context
1079
+ cdef xmlDoc* result
1080
+ cdef xmlparser.xmlParserCtxt* pctxt
1081
+ cdef Py_ssize_t py_buffer_len
1082
+ cdef int buffer_len, c_kind
1083
+ cdef const_char* c_text
1084
+ cdef const_char* c_encoding = _PY_UNICODE_ENCODING
1085
+ if python.PyUnicode_IS_READY(utext):
1086
+ # PEP-393 string
1087
+ c_text = <const_char*>python.PyUnicode_DATA(utext)
1088
+ py_buffer_len = python.PyUnicode_GET_LENGTH(utext)
1089
+ c_kind = python.PyUnicode_KIND(utext)
1090
+ if c_kind == 1:
1091
+ if python.PyUnicode_MAX_CHAR_VALUE(utext) <= 127:
1092
+ c_encoding = 'UTF-8'
1093
+ else:
1094
+ c_encoding = 'ISO-8859-1'
1095
+ elif c_kind == 2:
1096
+ py_buffer_len *= 2
1097
+ if python.PY_BIG_ENDIAN:
1098
+ c_encoding = 'UTF-16BE' # actually UCS-2
1099
+ else:
1100
+ c_encoding = 'UTF-16LE' # actually UCS-2
1101
+ elif c_kind == 4:
1102
+ py_buffer_len *= 4
1103
+ if python.PY_BIG_ENDIAN:
1104
+ c_encoding = 'UTF-32BE' # actually UCS-4
1105
+ else:
1106
+ c_encoding = 'UTF-32LE' # actually UCS-4
1107
+ else:
1108
+ assert False, f"Illegal Unicode kind {c_kind}"
1109
+ else:
1110
+ # old Py_UNICODE string
1111
+ py_buffer_len = python.PyUnicode_GET_DATA_SIZE(utext)
1112
+ c_text = python.PyUnicode_AS_DATA(utext)
1113
+ assert 0 <= py_buffer_len <= limits.INT_MAX
1114
+ buffer_len = py_buffer_len
1115
+
1116
+ context = self._getParserContext()
1117
+ context.prepare()
1118
+ try:
1119
+ pctxt = context._c_ctxt
1120
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1121
+ orig_options = pctxt.options
1122
+ with nogil:
1123
+ if self._for_html:
1124
+ result = htmlparser.htmlCtxtReadMemory(
1125
+ pctxt, c_text, buffer_len, c_filename, c_encoding,
1126
+ self._parse_options)
1127
+ if result is not NULL:
1128
+ if _fixHtmlDictNames(pctxt.dict, result) < 0:
1129
+ tree.xmlFreeDoc(result)
1130
+ result = NULL
1131
+ else:
1132
+ result = xmlparser.xmlCtxtReadMemory(
1133
+ pctxt, c_text, buffer_len, c_filename, c_encoding,
1134
+ self._parse_options)
1135
+ pctxt.options = orig_options # work around libxml2 problem
1136
+
1137
+ return context._handleParseResultDoc(self, result, None)
1138
+ finally:
1139
+ context.cleanup()
1140
+
1141
+ cdef xmlDoc* _parseDoc(self, const char* c_text, int c_len, char* c_filename) except NULL:
1142
+ """Parse document, share dictionary if possible.
1143
+ """
1144
+ cdef _ParserContext context
1145
+ cdef xmlDoc* result
1146
+ cdef xmlparser.xmlParserCtxt* pctxt
1147
+ cdef char* c_encoding
1148
+ cdef tree.xmlCharEncoding enc
1149
+ context = self._getParserContext()
1150
+ context.prepare()
1151
+ try:
1152
+ pctxt = context._c_ctxt
1153
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1154
+
1155
+ if self._default_encoding is None:
1156
+ c_encoding = NULL
1157
+ # libxml2 (at least 2.9.3) does not recognise UTF-32 BOMs
1158
+ # NOTE: limit to problematic cases because it changes character offsets
1159
+ if c_len >= 4 and (c_text[0] == b'\xFF' and c_text[1] == b'\xFE' and
1160
+ c_text[2] == 0 and c_text[3] == 0):
1161
+ c_encoding = "UTF-32LE"
1162
+ c_text += 4
1163
+ c_len -= 4
1164
+ elif c_len >= 4 and (c_text[0] == 0 and c_text[1] == 0 and
1165
+ c_text[2] == b'\xFE' and c_text[3] == b'\xFF'):
1166
+ c_encoding = "UTF-32BE"
1167
+ c_text += 4
1168
+ c_len -= 4
1169
+ else:
1170
+ # no BOM => try to determine encoding
1171
+ enc = tree.xmlDetectCharEncoding(<const_xmlChar*>c_text, c_len)
1172
+ if enc == tree.XML_CHAR_ENCODING_UCS4LE:
1173
+ c_encoding = 'UTF-32LE'
1174
+ elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
1175
+ c_encoding = 'UTF-32BE'
1176
+ else:
1177
+ c_encoding = _cstr(self._default_encoding)
1178
+
1179
+ orig_options = pctxt.options
1180
+ with nogil:
1181
+ if self._for_html:
1182
+ result = htmlparser.htmlCtxtReadMemory(
1183
+ pctxt, c_text, c_len, c_filename,
1184
+ c_encoding, self._parse_options)
1185
+ if result is not NULL:
1186
+ if _fixHtmlDictNames(pctxt.dict, result) < 0:
1187
+ tree.xmlFreeDoc(result)
1188
+ result = NULL
1189
+ else:
1190
+ result = xmlparser.xmlCtxtReadMemory(
1191
+ pctxt, c_text, c_len, c_filename,
1192
+ c_encoding, self._parse_options)
1193
+ pctxt.options = orig_options # work around libxml2 problem
1194
+
1195
+ return context._handleParseResultDoc(self, result, None)
1196
+ finally:
1197
+ context.cleanup()
1198
+
1199
+ cdef xmlDoc* _parseDocFromFile(self, char* c_filename) except NULL:
1200
+ cdef _ParserContext context
1201
+ cdef xmlDoc* result
1202
+ cdef xmlparser.xmlParserCtxt* pctxt
1203
+ cdef char* c_encoding
1204
+ result = NULL
1205
+
1206
+ context = self._getParserContext()
1207
+ context.prepare()
1208
+ try:
1209
+ pctxt = context._c_ctxt
1210
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1211
+
1212
+ if self._default_encoding is None:
1213
+ c_encoding = NULL
1214
+ else:
1215
+ c_encoding = _cstr(self._default_encoding)
1216
+
1217
+ orig_options = pctxt.options
1218
+ with nogil:
1219
+ if self._for_html:
1220
+ result = htmlparser.htmlCtxtReadFile(
1221
+ pctxt, c_filename, c_encoding, self._parse_options)
1222
+ if result is not NULL:
1223
+ if _fixHtmlDictNames(pctxt.dict, result) < 0:
1224
+ tree.xmlFreeDoc(result)
1225
+ result = NULL
1226
+ else:
1227
+ result = xmlparser.xmlCtxtReadFile(
1228
+ pctxt, c_filename, c_encoding, self._parse_options)
1229
+ pctxt.options = orig_options # work around libxml2 problem
1230
+
1231
+ return context._handleParseResultDoc(self, result, c_filename)
1232
+ finally:
1233
+ context.cleanup()
1234
+
1235
+ cdef xmlDoc* _parseDocFromFilelike(self, filelike, filename,
1236
+ encoding) except NULL:
1237
+ cdef _ParserContext context
1238
+ cdef _FileReaderContext file_context
1239
+ cdef xmlDoc* result
1240
+ cdef xmlparser.xmlParserCtxt* pctxt
1241
+ cdef char* c_filename
1242
+ if not filename:
1243
+ filename = None
1244
+
1245
+ context = self._getParserContext()
1246
+ context.prepare()
1247
+ try:
1248
+ pctxt = context._c_ctxt
1249
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1250
+ file_context = _FileReaderContext(
1251
+ filelike, context, filename,
1252
+ encoding or self._default_encoding)
1253
+ result = file_context._readDoc(pctxt, self._parse_options)
1254
+
1255
+ return context._handleParseResultDoc(
1256
+ self, result, filename)
1257
+ finally:
1258
+ context.cleanup()
1259
+
1260
+
1261
+ cdef tree.xmlEntity* _getInternalEntityOnly(void* ctxt, const_xmlChar* name) noexcept nogil:
1262
+ """
1263
+ Callback function to intercept the entity resolution when external entity loading is disabled.
1264
+ """
1265
+ cdef tree.xmlEntity* entity = xmlparser.xmlSAX2GetEntity(ctxt, name)
1266
+ if not entity:
1267
+ return NULL
1268
+ if entity.etype not in (
1269
+ tree.xmlEntityType.XML_EXTERNAL_GENERAL_PARSED_ENTITY,
1270
+ tree.xmlEntityType.XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,
1271
+ tree.xmlEntityType.XML_EXTERNAL_PARAMETER_ENTITY):
1272
+ return entity
1273
+
1274
+ # Reject all external entities and fail the parsing instead. There is currently
1275
+ # no way in libxml2 to just prevent the entity resolution in this case.
1276
+ cdef xmlerror.xmlError c_error
1277
+ cdef xmlerror.xmlStructuredErrorFunc err_func
1278
+ cdef xmlparser.xmlParserInput* parser_input
1279
+ cdef void* err_context
1280
+
1281
+ c_ctxt = <xmlparser.xmlParserCtxt *> ctxt
1282
+ err_func = xmlerror.xmlStructuredError
1283
+ if err_func:
1284
+ parser_input = c_ctxt.input
1285
+ # Copied from xmlVErrParser() in libxml2: get current input from stack.
1286
+ if parser_input and parser_input.filename is NULL and c_ctxt.inputNr > 1:
1287
+ parser_input = c_ctxt.inputTab[c_ctxt.inputNr - 2]
1288
+
1289
+ c_error = xmlerror.xmlError(
1290
+ domain=xmlerror.xmlErrorDomain.XML_FROM_PARSER,
1291
+ code=xmlerror.xmlParserErrors.XML_ERR_EXT_ENTITY_STANDALONE,
1292
+ level=xmlerror.xmlErrorLevel.XML_ERR_FATAL,
1293
+ message=b"External entity resolution is disabled for security reasons "
1294
+ b"when resolving '&%s;'. Use 'XMLParser(resolve_entities=True)' "
1295
+ b"if you consider it safe to enable it.",
1296
+ file=parser_input.filename,
1297
+ node=entity,
1298
+ str1=<char*> name,
1299
+ str2=NULL,
1300
+ str3=NULL,
1301
+ line=parser_input.line if parser_input else 0,
1302
+ int1=0,
1303
+ int2=parser_input.col if parser_input else 0,
1304
+ )
1305
+ err_context = xmlerror.xmlStructuredErrorContext
1306
+ err_func(err_context, &c_error)
1307
+
1308
+ c_ctxt.wellFormed = 0
1309
+ # The entity was looked up and does not need to be freed.
1310
+ return NULL
1311
+
1312
+
1313
+ cdef void _initSaxDocument(void* ctxt) noexcept with gil:
1314
+ xmlparser.xmlSAX2StartDocument(ctxt)
1315
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
1316
+ c_doc = c_ctxt.myDoc
1317
+
1318
+ # set up document dict
1319
+ if c_doc and c_ctxt.dict and not c_doc.dict:
1320
+ # I have no idea why libxml2 disables this - we need it
1321
+ c_ctxt.dictNames = 1
1322
+ c_doc.dict = c_ctxt.dict
1323
+ xmlparser.xmlDictReference(c_ctxt.dict)
1324
+
1325
+ # set up XML ID hash table
1326
+ if c_ctxt._private:
1327
+ context = <_ParserContext>c_ctxt._private
1328
+ if context._collect_ids:
1329
+ # keep the global parser dict from filling up with XML IDs
1330
+ if c_doc and not c_doc.ids:
1331
+ # memory errors are not fatal here
1332
+ c_dict = xmlparser.xmlDictCreate()
1333
+ if c_dict:
1334
+ c_doc.ids = tree.xmlHashCreateDict(0, c_dict)
1335
+ xmlparser.xmlDictFree(c_dict)
1336
+ else:
1337
+ c_doc.ids = tree.xmlHashCreate(0)
1338
+ else:
1339
+ c_ctxt.loadsubset |= xmlparser.XML_SKIP_IDS
1340
+ if c_doc and c_doc.ids and not tree.xmlHashSize(c_doc.ids):
1341
+ # already initialised but empty => clear
1342
+ tree.xmlHashFree(c_doc.ids, NULL)
1343
+ c_doc.ids = NULL
1344
+
1345
+
1346
+ ############################################################
1347
+ ## ET feed parser
1348
+ ############################################################
1349
+
1350
+ cdef class _FeedParser(_BaseParser):
1351
+ cdef bint _feed_parser_running
1352
+
1353
+ @property
1354
+ def feed_error_log(self):
1355
+ """The error log of the last (or current) run of the feed parser.
1356
+
1357
+ Note that this is local to the feed parser and thus is
1358
+ different from what the ``error_log`` property returns.
1359
+ """
1360
+ return self._getPushParserContext()._error_log.copy()
1361
+
1362
+ cpdef feed(self, data):
1363
+ """feed(self, data)
1364
+
1365
+ Feeds data to the parser. The argument should be an 8-bit string
1366
+ buffer containing encoded data, although Unicode is supported as long
1367
+ as both string types are not mixed.
1368
+
1369
+ This is the main entry point to the consumer interface of a
1370
+ parser. The parser will parse as much of the XML stream as it
1371
+ can on each call. To finish parsing or to reset the parser,
1372
+ call the ``close()`` method. Both methods may raise
1373
+ ParseError if errors occur in the input data. If an error is
1374
+ raised, there is no longer a need to call ``close()``.
1375
+
1376
+ The feed parser interface is independent of the normal parser
1377
+ usage. You can use the same parser as a feed parser and in
1378
+ the ``parse()`` function concurrently.
1379
+ """
1380
+ cdef _ParserContext context
1381
+ cdef bytes bstring
1382
+ cdef xmlparser.xmlParserCtxt* pctxt
1383
+ cdef Py_ssize_t py_buffer_len, ustart
1384
+ cdef const_char* char_data
1385
+ cdef const_char* c_encoding
1386
+ cdef int buffer_len
1387
+ cdef int error
1388
+ cdef bint recover = self._parse_options & xmlparser.XML_PARSE_RECOVER
1389
+
1390
+ if isinstance(data, bytes):
1391
+ if self._default_encoding is None:
1392
+ c_encoding = NULL
1393
+ else:
1394
+ c_encoding = self._default_encoding
1395
+ char_data = _cstr(data)
1396
+ py_buffer_len = python.PyBytes_GET_SIZE(data)
1397
+ ustart = 0
1398
+ elif isinstance(data, unicode):
1399
+ c_encoding = b"UTF-8"
1400
+ char_data = NULL
1401
+ py_buffer_len = len(<unicode> data)
1402
+ ustart = 0
1403
+ else:
1404
+ raise TypeError, "Parsing requires string data"
1405
+
1406
+ context = self._getPushParserContext()
1407
+ pctxt = context._c_ctxt
1408
+ error = 0
1409
+ if not self._feed_parser_running:
1410
+ context.prepare(set_document_loader=False)
1411
+ self._feed_parser_running = 1
1412
+ c_filename = (_cstr(self._filename)
1413
+ if self._filename is not None else NULL)
1414
+
1415
+ # We have to give *mlCtxtResetPush() enough input to figure
1416
+ # out the character encoding (at least four bytes),
1417
+ # however if we give it all we got, we'll have nothing for
1418
+ # *mlParseChunk() and things go wrong.
1419
+ buffer_len = 0
1420
+ if char_data is not NULL:
1421
+ buffer_len = 4 if py_buffer_len > 4 else <int>py_buffer_len
1422
+ orig_loader = _register_document_loader()
1423
+ if self._for_html:
1424
+ error = _htmlCtxtResetPush(
1425
+ pctxt, char_data, buffer_len, c_filename, c_encoding,
1426
+ self._parse_options)
1427
+ else:
1428
+ xmlparser.xmlCtxtUseOptions(pctxt, self._parse_options)
1429
+ error = xmlparser.xmlCtxtResetPush(
1430
+ pctxt, char_data, buffer_len, c_filename, c_encoding)
1431
+ _reset_document_loader(orig_loader)
1432
+ py_buffer_len -= buffer_len
1433
+ char_data += buffer_len
1434
+ if error:
1435
+ raise MemoryError()
1436
+ __GLOBAL_PARSER_CONTEXT.initParserDict(pctxt)
1437
+
1438
+ #print pctxt.charset, 'NONE' if c_encoding is NULL else c_encoding
1439
+
1440
+ fixup_error = 0
1441
+ while py_buffer_len > 0 and (error == 0 or recover):
1442
+ if char_data is NULL:
1443
+ # Unicode parsing by converting chunks to UTF-8
1444
+ buffer_len = 2**19 # len(bytes) <= 4 * (2**19) == 2 MiB
1445
+ bstring = (<unicode> data)[ustart : ustart+buffer_len].encode('UTF-8')
1446
+ ustart += buffer_len
1447
+ py_buffer_len -= buffer_len # may end up < 0
1448
+ error, fixup_error = _parse_data_chunk(pctxt, <const char*> bstring, <int> len(bstring))
1449
+ else:
1450
+ # Direct byte string parsing.
1451
+ buffer_len = <int>py_buffer_len if py_buffer_len <= limits.INT_MAX else limits.INT_MAX
1452
+ error, fixup_error = _parse_data_chunk(pctxt, char_data, buffer_len)
1453
+ py_buffer_len -= buffer_len
1454
+ char_data += buffer_len
1455
+
1456
+ if fixup_error:
1457
+ context.store_exception(MemoryError())
1458
+
1459
+ if context._has_raised():
1460
+ # propagate Python exceptions immediately
1461
+ recover = 0
1462
+ error = 1
1463
+ break
1464
+
1465
+ if error and not pctxt.replaceEntities and not pctxt.validate:
1466
+ # in this mode, we ignore errors about undefined entities
1467
+ for entry in context._error_log.filter_from_errors():
1468
+ if entry.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
1469
+ entry.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
1470
+ break
1471
+ else:
1472
+ error = 0
1473
+
1474
+ if not pctxt.wellFormed and xmlparser.xmlCtxtIsStopped(pctxt) and context._has_raised():
1475
+ # propagate Python exceptions immediately
1476
+ recover = 0
1477
+ error = 1
1478
+
1479
+ if fixup_error or not recover and (error or not pctxt.wellFormed):
1480
+ self._feed_parser_running = 0
1481
+ try:
1482
+ context._handleParseResult(self, pctxt.myDoc, None)
1483
+ finally:
1484
+ context.cleanup()
1485
+
1486
+ cpdef close(self):
1487
+ """close(self)
1488
+
1489
+ Terminates feeding data to this parser. This tells the parser to
1490
+ process any remaining data in the feed buffer, and then returns the
1491
+ root Element of the tree that was parsed.
1492
+
1493
+ This method must be called after passing the last chunk of data into
1494
+ the ``feed()`` method. It should only be called when using the feed
1495
+ parser interface, all other usage is undefined.
1496
+ """
1497
+ if not self._feed_parser_running:
1498
+ raise XMLSyntaxError("no element found",
1499
+ xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
1500
+ self._filename)
1501
+
1502
+ context = self._getPushParserContext()
1503
+ pctxt = context._c_ctxt
1504
+
1505
+ self._feed_parser_running = 0
1506
+ if self._for_html:
1507
+ htmlparser.htmlParseChunk(pctxt, NULL, 0, 1)
1508
+ else:
1509
+ xmlparser.xmlParseChunk(pctxt, NULL, 0, 1)
1510
+
1511
+ if (pctxt.recovery and not xmlparser.xmlCtxtIsStopped(pctxt) and
1512
+ isinstance(context, _SaxParserContext)):
1513
+ # apply any left-over 'end' events
1514
+ (<_SaxParserContext>context).flushEvents()
1515
+
1516
+ try:
1517
+ result = context._handleParseResult(self, pctxt.myDoc, None)
1518
+ finally:
1519
+ context.cleanup()
1520
+
1521
+ if isinstance(result, _Document):
1522
+ return (<_Document>result).getroot()
1523
+ else:
1524
+ return result
1525
+
1526
+
1527
+ cdef (int, int) _parse_data_chunk(xmlparser.xmlParserCtxt* c_ctxt,
1528
+ const char* char_data, int buffer_len):
1529
+ fixup_error = 0
1530
+ with nogil:
1531
+ if c_ctxt.html:
1532
+ c_node = c_ctxt.node # last node where the parser stopped
1533
+ orig_loader = _register_document_loader()
1534
+ error = htmlparser.htmlParseChunk(c_ctxt, char_data, buffer_len, 0)
1535
+ _reset_document_loader(orig_loader)
1536
+ # and now for the fun part: move node names to the dict
1537
+ if c_ctxt.myDoc:
1538
+ fixup_error = _fixHtmlDictSubtreeNames(
1539
+ c_ctxt.dict, c_ctxt.myDoc, c_node)
1540
+ if c_ctxt.myDoc.dict and c_ctxt.myDoc.dict is not c_ctxt.dict:
1541
+ xmlparser.xmlDictFree(c_ctxt.myDoc.dict)
1542
+ c_ctxt.myDoc.dict = c_ctxt.dict
1543
+ xmlparser.xmlDictReference(c_ctxt.dict)
1544
+ else:
1545
+ orig_loader = _register_document_loader()
1546
+ error = xmlparser.xmlParseChunk(c_ctxt, char_data, buffer_len, 0)
1547
+ _reset_document_loader(orig_loader)
1548
+ return (error, fixup_error)
1549
+
1550
+
1551
+ cdef int _htmlCtxtResetPush(xmlparser.xmlParserCtxt* c_ctxt,
1552
+ const_char* c_data, int buffer_len,
1553
+ const_char* c_filename, const_char* c_encoding,
1554
+ int parse_options) except -1:
1555
+ cdef xmlparser.xmlParserInput* c_input_stream
1556
+ # libxml2 lacks an HTML push parser setup function
1557
+ error = xmlparser.xmlCtxtResetPush(
1558
+ c_ctxt, c_data, buffer_len, c_filename, c_encoding)
1559
+ if error:
1560
+ return error
1561
+
1562
+ # fix libxml2 setup for HTML
1563
+ if tree.LIBXML_VERSION < 21400:
1564
+ c_ctxt.progressive = 1 # TODO: remove
1565
+ c_ctxt.html = 1
1566
+ htmlparser.htmlCtxtUseOptions(c_ctxt, parse_options)
1567
+
1568
+ return 0
1569
+
1570
+
1571
+ ############################################################
1572
+ ## XML parser
1573
+ ############################################################
1574
+
1575
+ cdef int _XML_DEFAULT_PARSE_OPTIONS
1576
+ _XML_DEFAULT_PARSE_OPTIONS = (
1577
+ xmlparser.XML_PARSE_NOENT |
1578
+ xmlparser.XML_PARSE_NOCDATA |
1579
+ xmlparser.XML_PARSE_NONET |
1580
+ xmlparser.XML_PARSE_COMPACT |
1581
+ xmlparser.XML_PARSE_BIG_LINES
1582
+ )
1583
+
1584
+ cdef class XMLParser(_FeedParser):
1585
+ """XMLParser(self, encoding=None, attribute_defaults=False, dtd_validation=False, \
1586
+ load_dtd=False, no_network=True, decompress=False, ns_clean=False, \
1587
+ recover=False, schema: XMLSchema =None, huge_tree=False, \
1588
+ remove_blank_text=False, resolve_entities='internal', \
1589
+ remove_comments=False, remove_pis=False, strip_cdata=True, \
1590
+ collect_ids=True, target=None, compact=True)
1591
+
1592
+ The XML parser.
1593
+
1594
+ Parsers can be supplied as additional argument to various parse
1595
+ functions of the lxml API. A default parser is always available
1596
+ and can be replaced by a call to the global function
1597
+ 'set_default_parser'. New parsers can be created at any time
1598
+ without a major run-time overhead.
1599
+
1600
+ The keyword arguments in the constructor are mainly based on the
1601
+ libxml2 parser configuration. A DTD will also be loaded if DTD
1602
+ validation or attribute default values are requested (unless you
1603
+ additionally provide an XMLSchema from which the default
1604
+ attributes can be read).
1605
+
1606
+ Available boolean keyword arguments:
1607
+
1608
+ - attribute_defaults - inject default attributes from DTD or XMLSchema
1609
+ - dtd_validation - validate against a DTD referenced by the document
1610
+ - load_dtd - use DTD for parsing
1611
+ - no_network - prevent network access for related files (default: True)
1612
+ - decompress - automatically decompress gzip input
1613
+ (default: False, changed in lxml 6.0, disabling only affects libxml2 2.15+)
1614
+ - ns_clean - clean up redundant namespace declarations
1615
+ - recover - try hard to parse through broken XML
1616
+ - remove_blank_text - discard blank text nodes that appear ignorable
1617
+ - remove_comments - discard comments
1618
+ - remove_pis - discard processing instructions
1619
+ - strip_cdata - replace CDATA sections by normal text content (default: True)
1620
+ - compact - save memory for short text content (default: True)
1621
+ - collect_ids - use a hash table of XML IDs for fast access
1622
+ (default: True, always True with DTD validation)
1623
+ - huge_tree - disable security restrictions and support very deep trees
1624
+ and very long text content
1625
+
1626
+ Other keyword arguments:
1627
+
1628
+ - resolve_entities - replace entities by their text value: False for keeping the
1629
+ entity references, True for resolving them, and 'internal' for resolving
1630
+ internal definitions only (no external file/URL access).
1631
+ The default used to be True and was changed to 'internal' in lxml 5.0.
1632
+ - encoding - override the document encoding (note: libiconv encoding name)
1633
+ - target - a parser target object that will receive the parse events
1634
+ - schema - an XMLSchema to validate against
1635
+
1636
+ Note that you should avoid sharing parsers between threads. While this is
1637
+ not harmful, it is more efficient to use separate parsers. This does not
1638
+ apply to the default parser.
1639
+ """
1640
+ def __init__(self, *, encoding=None, attribute_defaults=False,
1641
+ dtd_validation=False, load_dtd=False, no_network=True, decompress=False,
1642
+ ns_clean=False, recover=False, XMLSchema schema=None,
1643
+ huge_tree=False, remove_blank_text=False, resolve_entities='internal',
1644
+ remove_comments=False, remove_pis=False, strip_cdata=True,
1645
+ collect_ids=True, target=None, compact=True):
1646
+ cdef int parse_options
1647
+ cdef bint resolve_external = True
1648
+ parse_options = _XML_DEFAULT_PARSE_OPTIONS
1649
+ if load_dtd:
1650
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
1651
+ if dtd_validation:
1652
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDVALID | \
1653
+ xmlparser.XML_PARSE_DTDLOAD
1654
+ if attribute_defaults:
1655
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDATTR
1656
+ if schema is None:
1657
+ parse_options = parse_options | xmlparser.XML_PARSE_DTDLOAD
1658
+ if ns_clean:
1659
+ parse_options = parse_options | xmlparser.XML_PARSE_NSCLEAN
1660
+ if recover:
1661
+ parse_options = parse_options | xmlparser.XML_PARSE_RECOVER
1662
+ if remove_blank_text:
1663
+ parse_options = parse_options | xmlparser.XML_PARSE_NOBLANKS
1664
+ if huge_tree:
1665
+ parse_options = parse_options | xmlparser.XML_PARSE_HUGE
1666
+ if not no_network:
1667
+ parse_options = parse_options ^ xmlparser.XML_PARSE_NONET
1668
+ if not compact:
1669
+ parse_options = parse_options ^ xmlparser.XML_PARSE_COMPACT
1670
+ if not resolve_entities:
1671
+ parse_options = parse_options ^ xmlparser.XML_PARSE_NOENT
1672
+ elif resolve_entities == 'internal':
1673
+ resolve_external = False
1674
+ if not strip_cdata:
1675
+ parse_options = parse_options ^ xmlparser.XML_PARSE_NOCDATA
1676
+ if decompress:
1677
+ parse_options |= xmlparser.XML_PARSE_UNZIP
1678
+
1679
+ _BaseParser.__init__(self, parse_options, False, schema,
1680
+ remove_comments, remove_pis, strip_cdata,
1681
+ collect_ids, target, encoding, resolve_external)
1682
+
1683
+ # Allow subscripting XMLParser in type annotations (PEP 560)
1684
+ def __class_getitem__(cls, item):
1685
+ return _GenericAlias(cls, item)
1686
+
1687
+
1688
+ cdef class XMLPullParser(XMLParser):
1689
+ """XMLPullParser(self, events=None, *, tag=None, **kwargs)
1690
+
1691
+ XML parser that collects parse events in an iterator.
1692
+
1693
+ The collected events are the same as for iterparse(), but the
1694
+ parser itself is non-blocking in the sense that it receives
1695
+ data chunks incrementally through its .feed() method, instead
1696
+ of reading them directly from a file(-like) object all by itself.
1697
+
1698
+ By default, it collects Element end events. To change that,
1699
+ pass any subset of the available events into the ``events``
1700
+ argument: ``'start'``, ``'end'``, ``'start-ns'``,
1701
+ ``'end-ns'``, ``'comment'``, ``'pi'``.
1702
+
1703
+ To support loading external dependencies relative to the input
1704
+ source, you can pass the ``base_url``.
1705
+ """
1706
+ def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
1707
+ XMLParser.__init__(self, **kwargs)
1708
+ if events is None:
1709
+ events = ('end',)
1710
+ self._setBaseURL(base_url)
1711
+ self._collectEvents(events, tag)
1712
+
1713
+ def read_events(self):
1714
+ return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
1715
+
1716
+
1717
+ cdef class ETCompatXMLParser(XMLParser):
1718
+ """ETCompatXMLParser(self, encoding=None, attribute_defaults=False, \
1719
+ dtd_validation=False, load_dtd=False, no_network=True, decompress=False, \
1720
+ ns_clean=False, recover=False, schema=None, \
1721
+ huge_tree=False, remove_blank_text=False, resolve_entities='internal', \
1722
+ remove_comments=True, remove_pis=True, strip_cdata=True, \
1723
+ target=None, compact=True)
1724
+
1725
+ An XML parser with an ElementTree compatible default setup.
1726
+
1727
+ See the XMLParser class for details.
1728
+
1729
+ This parser has ``remove_comments`` and ``remove_pis`` enabled by default
1730
+ and thus ignores comments and processing instructions.
1731
+
1732
+ The default value of ``resolve_entities`` used to be True and was changed to
1733
+ 'internal' in lxml 6.1.
1734
+ """
1735
+ def __init__(self, *, encoding=None, attribute_defaults=False,
1736
+ dtd_validation=False, load_dtd=False, no_network=True, decompress=False,
1737
+ ns_clean=False, recover=False, schema=None,
1738
+ huge_tree=False, remove_blank_text=False, resolve_entities='internal',
1739
+ remove_comments=True, remove_pis=True, strip_cdata=True,
1740
+ target=None, compact=True):
1741
+ XMLParser.__init__(self,
1742
+ attribute_defaults=attribute_defaults,
1743
+ dtd_validation=dtd_validation,
1744
+ load_dtd=load_dtd,
1745
+ no_network=no_network,
1746
+ decompress=decompress,
1747
+ ns_clean=ns_clean,
1748
+ recover=recover,
1749
+ remove_blank_text=remove_blank_text,
1750
+ huge_tree=huge_tree,
1751
+ compact=compact,
1752
+ resolve_entities=resolve_entities,
1753
+ remove_comments=remove_comments,
1754
+ remove_pis=remove_pis,
1755
+ strip_cdata=strip_cdata,
1756
+ target=target,
1757
+ encoding=encoding,
1758
+ schema=schema,
1759
+ )
1760
+
1761
+ # ET 1.2 compatible name
1762
+ XMLTreeBuilder = ETCompatXMLParser
1763
+
1764
+
1765
+ cdef XMLParser __DEFAULT_XML_PARSER
1766
+ __DEFAULT_XML_PARSER = XMLParser()
1767
+
1768
+ __GLOBAL_PARSER_CONTEXT.setDefaultParser(__DEFAULT_XML_PARSER)
1769
+
1770
+ def set_default_parser(_BaseParser parser=None):
1771
+ """set_default_parser(parser=None)
1772
+
1773
+ Set a default parser for the current thread. This parser is used
1774
+ globally whenever no parser is supplied to the various parse functions of
1775
+ the lxml API. If this function is called without a parser (or if it is
1776
+ None), the default parser is reset to the original configuration.
1777
+
1778
+ Note that the pre-installed default parser is not thread-safe. Avoid the
1779
+ default parser in multi-threaded environments. You can create a separate
1780
+ parser for each thread explicitly or use a parser pool.
1781
+ """
1782
+ if parser is None:
1783
+ parser = __DEFAULT_XML_PARSER
1784
+ __GLOBAL_PARSER_CONTEXT.setDefaultParser(parser)
1785
+
1786
+ def get_default_parser():
1787
+ "get_default_parser()"
1788
+ return __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1789
+
1790
+ ############################################################
1791
+ ## HTML parser
1792
+ ############################################################
1793
+
1794
+ cdef int _HTML_DEFAULT_PARSE_OPTIONS
1795
+ _HTML_DEFAULT_PARSE_OPTIONS = (
1796
+ htmlparser.HTML_PARSE_RECOVER |
1797
+ htmlparser.HTML_PARSE_NONET |
1798
+ htmlparser.HTML_PARSE_COMPACT
1799
+ )
1800
+
1801
+ cdef object _UNUSED = object()
1802
+
1803
+ cdef class HTMLParser(_FeedParser):
1804
+ """HTMLParser(self, encoding=None, remove_blank_text=False, \
1805
+ remove_comments=False, remove_pis=False, \
1806
+ no_network=True, decompress=False, target=None, schema: XMLSchema =None, \
1807
+ recover=True, compact=True, collect_ids=True, huge_tree=False)
1808
+
1809
+ The HTML parser.
1810
+
1811
+ This parser allows reading HTML into a normal XML tree. By
1812
+ default, it can read broken (non well-formed) HTML, depending on
1813
+ the capabilities of libxml2. Use the 'recover' option to switch
1814
+ this off.
1815
+
1816
+ Available boolean keyword arguments:
1817
+
1818
+ - recover - try hard to parse through broken HTML (default: True)
1819
+ - no_network - prevent network access for related files (default: True)
1820
+ - decompress - automatically decompress gzip input
1821
+ (default: False, changed in lxml 6.0, disabling only affects libxml2 2.15+)
1822
+ - remove_blank_text - discard empty text nodes that are ignorable (i.e. not actual text content)
1823
+ - remove_comments - discard comments
1824
+ - remove_pis - discard processing instructions
1825
+ - compact - save memory for short text content (default: True)
1826
+ - default_doctype - add a default doctype even if it is not found in the HTML (default: True)
1827
+ - collect_ids - use a hash table of XML IDs for fast access (default: True)
1828
+ - huge_tree - disable security restrictions and support very deep trees
1829
+ and very long text content
1830
+
1831
+ Other keyword arguments:
1832
+
1833
+ - encoding - override the document encoding (note: libiconv encoding name)
1834
+ - target - a parser target object that will receive the parse events
1835
+ - schema - an XMLSchema to validate against
1836
+
1837
+ Note that you should avoid sharing parsers between threads for performance
1838
+ reasons.
1839
+ """
1840
+ def __init__(self, *, encoding=None, remove_blank_text=False,
1841
+ remove_comments=False, remove_pis=False, strip_cdata=_UNUSED,
1842
+ no_network=True, decompress=False, target=None, XMLSchema schema=None,
1843
+ recover=True, compact=True, default_doctype=True,
1844
+ collect_ids=True, huge_tree=False):
1845
+ cdef int parse_options
1846
+ parse_options = _HTML_DEFAULT_PARSE_OPTIONS
1847
+ if remove_blank_text:
1848
+ parse_options = parse_options | htmlparser.HTML_PARSE_NOBLANKS
1849
+ if not recover:
1850
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_RECOVER
1851
+ if not no_network:
1852
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_NONET
1853
+ if not compact:
1854
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_COMPACT
1855
+ if not default_doctype:
1856
+ parse_options = parse_options ^ htmlparser.HTML_PARSE_NODEFDTD
1857
+ if huge_tree:
1858
+ parse_options = parse_options | xmlparser.XML_PARSE_HUGE
1859
+ if decompress:
1860
+ parse_options |= xmlparser.XML_PARSE_UNZIP
1861
+
1862
+ if strip_cdata is not _UNUSED:
1863
+ import warnings
1864
+ warnings.warn(
1865
+ "The 'strip_cdata' option of HTMLParser() has never done anything and will eventually be removed.",
1866
+ DeprecationWarning)
1867
+ _BaseParser.__init__(self, parse_options, True, schema,
1868
+ remove_comments, remove_pis, strip_cdata,
1869
+ collect_ids, target, encoding)
1870
+
1871
+ # Allow subscripting HTMLParser in type annotations (PEP 560)
1872
+ def __class_getitem__(cls, item):
1873
+ return _GenericAlias(cls, item)
1874
+
1875
+
1876
+ cdef HTMLParser __DEFAULT_HTML_PARSER
1877
+ __DEFAULT_HTML_PARSER = HTMLParser()
1878
+
1879
+
1880
+ cdef class HTMLPullParser(HTMLParser):
1881
+ """HTMLPullParser(self, events=None, *, tag=None, base_url=None, **kwargs)
1882
+
1883
+ HTML parser that collects parse events in an iterator.
1884
+
1885
+ The collected events are the same as for iterparse(), but the
1886
+ parser itself is non-blocking in the sense that it receives
1887
+ data chunks incrementally through its .feed() method, instead
1888
+ of reading them directly from a file(-like) object all by itself.
1889
+
1890
+ By default, it collects Element end events. To change that,
1891
+ pass any subset of the available events into the ``events``
1892
+ argument: ``'start'``, ``'end'``, ``'start-ns'``,
1893
+ ``'end-ns'``, ``'comment'``, ``'pi'``.
1894
+
1895
+ To support loading external dependencies relative to the input
1896
+ source, you can pass the ``base_url``.
1897
+ """
1898
+ def __init__(self, events=None, *, tag=None, base_url=None, **kwargs):
1899
+ HTMLParser.__init__(self, **kwargs)
1900
+ if events is None:
1901
+ events = ('end',)
1902
+ self._setBaseURL(base_url)
1903
+ self._collectEvents(events, tag)
1904
+
1905
+ def read_events(self):
1906
+ return (<_SaxParserContext?>self._getPushParserContext()).events_iterator
1907
+
1908
+
1909
+ ############################################################
1910
+ ## helper functions for document creation
1911
+ ############################################################
1912
+
1913
+ cdef xmlDoc* _parseDoc(text, filename, _BaseParser parser) except NULL:
1914
+ cdef char* c_filename
1915
+ if parser is None:
1916
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1917
+ if not filename:
1918
+ c_filename = NULL
1919
+ else:
1920
+ filename_utf = _encodeFilenameUTF8(filename)
1921
+ c_filename = _cstr(filename_utf)
1922
+ if isinstance(text, bytes):
1923
+ return _parseDoc_bytes(<bytes> text, filename, c_filename, parser)
1924
+ elif isinstance(text, unicode):
1925
+ return _parseDoc_unicode(<unicode> text, filename, c_filename, parser)
1926
+ else:
1927
+ return _parseDoc_charbuffer(text, filename, c_filename, parser)
1928
+
1929
+
1930
+ cdef xmlDoc* _parseDoc_unicode(unicode text, filename, char* c_filename, _BaseParser parser) except NULL:
1931
+ cdef Py_ssize_t c_len
1932
+ if python.PyUnicode_IS_READY(text):
1933
+ # PEP-393 Unicode string
1934
+ c_len = python.PyUnicode_GET_LENGTH(text) * python.PyUnicode_KIND(text)
1935
+ else:
1936
+ # old Py_UNICODE string
1937
+ c_len = python.PyUnicode_GET_DATA_SIZE(text)
1938
+ if c_len > limits.INT_MAX:
1939
+ return parser._parseDocFromFilelike(
1940
+ StringIO(text), filename, None)
1941
+ return parser._parseUnicodeDoc(text, c_filename)
1942
+
1943
+
1944
+ cdef xmlDoc* _parseDoc_bytes(bytes text, filename, char* c_filename, _BaseParser parser) except NULL:
1945
+ cdef Py_ssize_t c_len = len(text)
1946
+ if c_len > limits.INT_MAX:
1947
+ return parser._parseDocFromFilelike(BytesIO(text), filename, None)
1948
+ return parser._parseDoc(text, c_len, c_filename)
1949
+
1950
+
1951
+ cdef xmlDoc* _parseDoc_charbuffer(text, filename, char* c_filename, _BaseParser parser) except NULL:
1952
+ cdef const unsigned char[::1] data = memoryview(text).cast('B') # cast to 'unsigned char' buffer
1953
+ cdef Py_ssize_t c_len = len(data)
1954
+ if c_len > limits.INT_MAX:
1955
+ return parser._parseDocFromFilelike(BytesIO(text), filename, None)
1956
+ return parser._parseDoc(<const char*>&data[0], c_len, c_filename)
1957
+
1958
+
1959
+ cdef xmlDoc* _parseDocFromFile(filename8, _BaseParser parser) except NULL:
1960
+ if parser is None:
1961
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1962
+ return (<_BaseParser>parser)._parseDocFromFile(_cstr(filename8))
1963
+
1964
+
1965
+ cdef xmlDoc* _parseDocFromFilelike(source, filename,
1966
+ _BaseParser parser) except NULL:
1967
+ if parser is None:
1968
+ parser = __GLOBAL_PARSER_CONTEXT.getDefaultParser()
1969
+ return (<_BaseParser>parser)._parseDocFromFilelike(source, filename, None)
1970
+
1971
+
1972
+ cdef xmlDoc* _newXMLDoc() except NULL:
1973
+ cdef xmlDoc* result
1974
+ result = tree.xmlNewDoc(NULL)
1975
+ if result is NULL:
1976
+ raise MemoryError()
1977
+ if result.encoding is NULL:
1978
+ result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
1979
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
1980
+ return result
1981
+
1982
+ cdef xmlDoc* _newHTMLDoc() except NULL:
1983
+ cdef xmlDoc* result
1984
+ result = tree.htmlNewDoc(NULL, NULL)
1985
+ if result is NULL:
1986
+ raise MemoryError()
1987
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
1988
+ return result
1989
+
1990
+
1991
+ cdef xmlDoc* _copyDoc(xmlDoc* c_doc, int recursive) except NULL:
1992
+ """Return a copy of c_doc, without moving the names into the dict."""
1993
+ cdef xmlDoc* result
1994
+ if recursive:
1995
+ with nogil:
1996
+ result = tree.xmlCopyDoc(c_doc, recursive)
1997
+ else:
1998
+ result = tree.xmlCopyDoc(c_doc, 0)
1999
+ if result is NULL:
2000
+ raise MemoryError()
2001
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
2002
+ return result
2003
+
2004
+
2005
+ cdef xmlDoc* _copyDocRoot(xmlDoc* c_doc, xmlNode* c_new_root) except NULL:
2006
+ """Recursively copy the document and make c_new_root the new root node."""
2007
+ cdef xmlDoc* result
2008
+ cdef xmlNode* c_node
2009
+ result = tree.xmlCopyDoc(c_doc, 0) # non recursive
2010
+ if result is NULL:
2011
+ raise MemoryError()
2012
+ __GLOBAL_PARSER_CONTEXT.initDocDict(result)
2013
+
2014
+ with nogil:
2015
+ c_node = tree.xmlDocCopyNode(c_new_root, result, 1) # recursive
2016
+ if c_node is NULL:
2017
+ tree.xmlFreeDoc(result)
2018
+ raise MemoryError()
2019
+
2020
+ tree.xmlDocSetRootElement(result, c_node)
2021
+ # Copy the tail text after setting the root element since libxml2 otherwise unlinks the tail.
2022
+ _copyTail(c_new_root.next, c_node)
2023
+ return result
2024
+
2025
+
2026
+ cdef xmlNode* _copyNodeToDoc(xmlNode* c_node, xmlDoc* c_doc) except NULL:
2027
+ """Recursively copy the element into the document. c_doc is not modified."""
2028
+ cdef xmlNode* c_root
2029
+ c_root = tree.xmlDocCopyNode(c_node, c_doc, 1) # recursive
2030
+ if c_root is NULL:
2031
+ raise MemoryError()
2032
+ _copyTail(c_node.next, c_root)
2033
+ return c_root
2034
+
2035
+
2036
+ ############################################################
2037
+ ## API level helper functions for _Document creation
2038
+ ############################################################
2039
+
2040
+ cdef _Document _parseDocument(source, _BaseParser parser, base_url):
2041
+ cdef _Document doc
2042
+ source = _getFSPathOrObject(source)
2043
+ if _isString(source):
2044
+ # parse the file directly from the filesystem
2045
+ doc = _parseDocumentFromURL(_encodeFilename(source), parser)
2046
+ # fix base URL if requested
2047
+ if base_url is not None:
2048
+ base_url = _encodeFilenameUTF8(base_url)
2049
+ if doc._c_doc.URL is not NULL:
2050
+ tree.xmlFree(<char*>doc._c_doc.URL)
2051
+ doc._c_doc.URL = tree.xmlStrdup(_xcstr(base_url))
2052
+ return doc
2053
+
2054
+ if base_url is not None:
2055
+ url = base_url
2056
+ else:
2057
+ url = _getFilenameForFile(source)
2058
+
2059
+ if hasattr(source, 'getvalue') and hasattr(source, 'tell'):
2060
+ # StringIO - reading from start?
2061
+ if source.tell() == 0:
2062
+ return _parseMemoryDocument(source.getvalue(), url, parser)
2063
+
2064
+ # Support for file-like objects (urlgrabber.urlopen, ...)
2065
+ if hasattr(source, 'read'):
2066
+ return _parseFilelikeDocument(source, url, parser)
2067
+
2068
+ raise TypeError, f"cannot parse from '{python._fqtypename(source).decode('UTF-8')}'"
2069
+
2070
+ cdef _Document _parseDocumentFromURL(url, _BaseParser parser):
2071
+ c_doc = _parseDocFromFile(url, parser)
2072
+ return _documentFactory(c_doc, parser)
2073
+
2074
+ cdef _Document _parseMemoryDocument(text, url, _BaseParser parser):
2075
+ if isinstance(text, unicode):
2076
+ if _hasEncodingDeclaration(text):
2077
+ raise ValueError(
2078
+ "Unicode strings with encoding declaration are not supported. "
2079
+ "Please use bytes input or XML fragments without declaration.")
2080
+ c_doc = _parseDoc(text, url, parser)
2081
+ return _documentFactory(c_doc, parser)
2082
+
2083
+ cdef _Document _parseFilelikeDocument(source, url, _BaseParser parser):
2084
+ c_doc = _parseDocFromFilelike(source, url, parser)
2085
+ return _documentFactory(c_doc, parser)
.venv/lib/python3.12/site-packages/lxml/parsertarget.pxi ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Parser target context (ET target interface)
2
+
3
+ cdef object inspect_getargspec
4
+ try:
5
+ from inspect import getfullargspec as inspect_getargspec
6
+ except ImportError:
7
+ from inspect import getargspec as inspect_getargspec
8
+
9
+
10
+ class _TargetParserResult(Exception):
11
+ # Admittedly, this is somewhat ugly, but it's the easiest way
12
+ # to push the Python level parser result through the parser
13
+ # machinery towards the API level functions
14
+ def __init__(self, result):
15
+ self.result = result
16
+
17
+
18
+ @cython.final
19
+ @cython.internal
20
+ cdef class _PythonSaxParserTarget(_SaxParserTarget):
21
+ cdef object _target_start
22
+ cdef object _target_end
23
+ cdef object _target_data
24
+ cdef object _target_start_ns
25
+ cdef object _target_end_ns
26
+ cdef object _target_doctype
27
+ cdef object _target_pi
28
+ cdef object _target_comment
29
+ cdef bint _start_takes_nsmap
30
+
31
+ def __cinit__(self, target):
32
+ cdef int event_filter
33
+ event_filter = 0
34
+ self._start_takes_nsmap = 0
35
+ try:
36
+ self._target_start = target.start
37
+ if self._target_start is not None:
38
+ event_filter |= SAX_EVENT_START
39
+ except AttributeError:
40
+ pass
41
+ else:
42
+ try:
43
+ arguments = inspect_getargspec(self._target_start)
44
+ if len(arguments[0]) > 3 or arguments[1] is not None:
45
+ self._start_takes_nsmap = 1
46
+ except TypeError:
47
+ pass
48
+ try:
49
+ self._target_end = target.end
50
+ if self._target_end is not None:
51
+ event_filter |= SAX_EVENT_END
52
+ except AttributeError:
53
+ pass
54
+ try:
55
+ self._target_start_ns = target.start_ns
56
+ if self._target_start_ns is not None:
57
+ event_filter |= SAX_EVENT_START_NS
58
+ except AttributeError:
59
+ pass
60
+ try:
61
+ self._target_end_ns = target.end_ns
62
+ if self._target_end_ns is not None:
63
+ event_filter |= SAX_EVENT_END_NS
64
+ except AttributeError:
65
+ pass
66
+ try:
67
+ self._target_data = target.data
68
+ if self._target_data is not None:
69
+ event_filter |= SAX_EVENT_DATA
70
+ except AttributeError:
71
+ pass
72
+ try:
73
+ self._target_doctype = target.doctype
74
+ if self._target_doctype is not None:
75
+ event_filter |= SAX_EVENT_DOCTYPE
76
+ except AttributeError:
77
+ pass
78
+ try:
79
+ self._target_pi = target.pi
80
+ if self._target_pi is not None:
81
+ event_filter |= SAX_EVENT_PI
82
+ except AttributeError:
83
+ pass
84
+ try:
85
+ self._target_comment = target.comment
86
+ if self._target_comment is not None:
87
+ event_filter |= SAX_EVENT_COMMENT
88
+ except AttributeError:
89
+ pass
90
+ self._sax_event_filter = event_filter
91
+
92
+ cdef _handleSaxStart(self, tag, attrib, nsmap):
93
+ if self._start_takes_nsmap:
94
+ return self._target_start(tag, attrib, nsmap)
95
+ else:
96
+ return self._target_start(tag, attrib)
97
+
98
+ cdef _handleSaxEnd(self, tag):
99
+ return self._target_end(tag)
100
+
101
+ cdef _handleSaxStartNs(self, prefix, uri):
102
+ return self._target_start_ns(prefix, uri)
103
+
104
+ cdef _handleSaxEndNs(self, prefix):
105
+ return self._target_end_ns(prefix)
106
+
107
+ cdef int _handleSaxData(self, data) except -1:
108
+ self._target_data(data)
109
+
110
+ cdef int _handleSaxDoctype(self, root_tag, public_id, system_id) except -1:
111
+ self._target_doctype(root_tag, public_id, system_id)
112
+
113
+ cdef _handleSaxPi(self, target, data):
114
+ return self._target_pi(target, data)
115
+
116
+ cdef _handleSaxComment(self, comment):
117
+ return self._target_comment(comment)
118
+
119
+
120
+ @cython.final
121
+ @cython.internal
122
+ @cython.no_gc_clear # Required because parent class uses it - Cython bug.
123
+ cdef class _TargetParserContext(_SaxParserContext):
124
+ """This class maps SAX2 events to the ET parser target interface.
125
+ """
126
+ cdef object _python_target
127
+ cdef int _setTarget(self, target) except -1:
128
+ self._python_target = target
129
+ if not isinstance(target, _SaxParserTarget) or \
130
+ hasattr(target, '__dict__'):
131
+ target = _PythonSaxParserTarget(target)
132
+ self._setSaxParserTarget(target)
133
+ return 0
134
+
135
+ cdef _ParserContext _copy(self):
136
+ cdef _TargetParserContext context
137
+ context = _ParserContext._copy(self)
138
+ context._setTarget(self._python_target)
139
+ return context
140
+
141
+ cdef void _cleanupTargetParserContext(self, xmlDoc* result) noexcept:
142
+ if self._c_ctxt.myDoc is not NULL:
143
+ if self._c_ctxt.myDoc is not result and \
144
+ self._c_ctxt.myDoc._private is NULL:
145
+ # no _Document proxy => orphen
146
+ tree.xmlFreeDoc(self._c_ctxt.myDoc)
147
+ self._c_ctxt.myDoc = NULL
148
+
149
+ cdef object _handleParseResult(self, _BaseParser parser, xmlDoc* result,
150
+ filename):
151
+ cdef bint recover
152
+ recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
153
+ try:
154
+ if self._has_raised():
155
+ self._cleanupTargetParserContext(result)
156
+ self._raise_if_stored()
157
+ if not self._c_ctxt.wellFormed and not recover:
158
+ _raiseParseError(self._c_ctxt, filename, self._error_log)
159
+ except:
160
+ self._python_target.close()
161
+ raise
162
+ return self._python_target.close()
163
+
164
+ cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser,
165
+ xmlDoc* result, filename) except NULL:
166
+ cdef bint recover
167
+ recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
168
+ if result is not NULL and result._private is NULL:
169
+ # no _Document proxy => orphen
170
+ tree.xmlFreeDoc(result)
171
+ try:
172
+ self._cleanupTargetParserContext(result)
173
+ self._raise_if_stored()
174
+ if not self._c_ctxt.wellFormed and not recover:
175
+ _raiseParseError(self._c_ctxt, filename, self._error_log)
176
+ except:
177
+ self._python_target.close()
178
+ raise
179
+ parse_result = self._python_target.close()
180
+ raise _TargetParserResult(parse_result)
.venv/lib/python3.12/site-packages/lxml/proxy.pxi ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Proxy functions and low level node allocation stuff
2
+
3
+ # Proxies represent elements, their reference is stored in the C
4
+ # structure of the respective node to avoid multiple instantiation of
5
+ # the Python class.
6
+
7
+ @cython.linetrace(False)
8
+ @cython.profile(False)
9
+ cdef inline _Element getProxy(xmlNode* c_node):
10
+ """Get a proxy for a given node.
11
+ """
12
+ #print "getProxy for:", <int>c_node
13
+ if c_node is not NULL and c_node._private is not NULL:
14
+ return <_Element>c_node._private
15
+ else:
16
+ return None
17
+
18
+
19
+ @cython.linetrace(False)
20
+ @cython.profile(False)
21
+ cdef inline bint hasProxy(xmlNode* c_node):
22
+ if c_node._private is NULL:
23
+ return False
24
+ return True
25
+
26
+
27
+ @cython.linetrace(False)
28
+ @cython.profile(False)
29
+ cdef inline int _registerProxy(_Element proxy, _Document doc,
30
+ xmlNode* c_node) except -1:
31
+ """Register a proxy and type for the node it's proxying for.
32
+ """
33
+ #print "registering for:", <int>proxy._c_node
34
+ assert not hasProxy(c_node), "double registering proxy!"
35
+ proxy._doc = doc
36
+ proxy._c_node = c_node
37
+ c_node._private = <void*>proxy
38
+ return 0
39
+
40
+
41
+ @cython.linetrace(False)
42
+ @cython.profile(False)
43
+ cdef inline int _unregisterProxy(_Element proxy) except -1:
44
+ """Unregister a proxy for the node it's proxying for.
45
+ """
46
+ cdef xmlNode* c_node = proxy._c_node
47
+ assert c_node._private is <void*>proxy, "Tried to unregister unknown proxy"
48
+ c_node._private = NULL
49
+ return 0
50
+
51
+
52
+ ################################################################################
53
+ # temporarily make a node the root node of its document
54
+
55
+ cdef xmlDoc* _fakeRootDoc(xmlDoc* c_base_doc, xmlNode* c_node) except NULL:
56
+ return _plainFakeRootDoc(c_base_doc, c_node, 1)
57
+
58
+ cdef xmlDoc* _plainFakeRootDoc(xmlDoc* c_base_doc, xmlNode* c_node,
59
+ bint with_siblings) except NULL:
60
+ # build a temporary document that has the given node as root node
61
+ # note that copy and original must not be modified during its lifetime!!
62
+ # always call _destroyFakeDoc() after use!
63
+ cdef xmlNode* c_child
64
+ cdef xmlNode* c_root
65
+ cdef xmlNode* c_new_root
66
+ cdef xmlDoc* c_doc
67
+ if with_siblings or (c_node.prev is NULL and c_node.next is NULL):
68
+ c_root = tree.xmlDocGetRootElement(c_base_doc)
69
+ if c_root is c_node:
70
+ # already the root node, no siblings
71
+ return c_base_doc
72
+
73
+ c_doc = _copyDoc(c_base_doc, 0) # non recursive!
74
+ c_new_root = tree.xmlDocCopyNode(c_node, c_doc, 2) if c_doc is not NULL else NULL # non recursive!
75
+ if c_new_root is NULL:
76
+ raise MemoryError()
77
+ tree.xmlDocSetRootElement(c_doc, c_new_root)
78
+ _copyParentNamespaces(c_node, c_new_root)
79
+
80
+ c_new_root.children = c_node.children
81
+ c_new_root.last = c_node.last
82
+ c_new_root.next = c_new_root.prev = NULL
83
+
84
+ # store original node
85
+ c_doc._private = c_node
86
+
87
+ # divert parent pointers of children
88
+ c_child = c_new_root.children
89
+ while c_child is not NULL:
90
+ c_child.parent = c_new_root
91
+ c_child = c_child.next
92
+
93
+ c_doc.children = c_new_root
94
+ return c_doc
95
+
96
+ cdef void _destroyFakeDoc(xmlDoc* c_base_doc, xmlDoc* c_doc) noexcept:
97
+ # delete a temporary document
98
+ cdef xmlNode* c_child
99
+ cdef xmlNode* c_parent
100
+ cdef xmlNode* c_root
101
+ if c_doc is c_base_doc:
102
+ return
103
+ c_root = tree.xmlDocGetRootElement(c_doc)
104
+
105
+ # restore parent pointers of children
106
+ c_parent = <xmlNode*>c_doc._private
107
+ c_child = c_root.children
108
+ while c_child is not NULL:
109
+ c_child.parent = c_parent
110
+ c_child = c_child.next
111
+
112
+ # prevent recursive removal of children
113
+ c_root.children = c_root.last = NULL
114
+ tree.xmlFreeDoc(c_doc)
115
+
116
+ cdef _Element _fakeDocElementFactory(_Document doc, xmlNode* c_element):
117
+ """Special element factory for cases where we need to create a fake
118
+ root document, but still need to instantiate arbitrary nodes from
119
+ it. If we instantiate the fake root node, things will turn bad
120
+ when it's destroyed.
121
+
122
+ Instead, if we are asked to instantiate the fake root node, we
123
+ instantiate the original node instead.
124
+ """
125
+ if c_element.doc is not doc._c_doc:
126
+ if c_element.doc._private is not NULL:
127
+ if c_element is c_element.doc.children:
128
+ c_element = <xmlNode*>c_element.doc._private
129
+ #assert c_element.type == tree.XML_ELEMENT_NODE
130
+ return _elementFactory(doc, c_element)
131
+
132
+ ################################################################################
133
+ # support for freeing tree elements when proxy objects are destroyed
134
+
135
+ cdef int attemptDeallocation(xmlNode* c_node) noexcept:
136
+ """Attempt deallocation of c_node (or higher up in tree).
137
+ """
138
+ cdef xmlNode* c_top
139
+ # could be we actually aren't referring to the tree at all
140
+ if c_node is NULL:
141
+ #print "not freeing, node is NULL"
142
+ return 0
143
+ c_top = getDeallocationTop(c_node)
144
+ if c_top is not NULL:
145
+ #print "freeing:", c_top.name
146
+ _removeText(c_top.next) # tail
147
+ tree.xmlFreeNode(c_top)
148
+ return 1
149
+ return 0
150
+
151
+ cdef xmlNode* getDeallocationTop(xmlNode* c_node) noexcept:
152
+ """Return the top of the tree that can be deallocated, or NULL.
153
+ """
154
+ cdef xmlNode* c_next
155
+ #print "trying to do deallocating:", c_node.type
156
+ if hasProxy(c_node):
157
+ #print "Not freeing: proxies still exist"
158
+ return NULL
159
+ while c_node.parent is not NULL:
160
+ c_node = c_node.parent
161
+ #print "checking:", c_current.type
162
+ if c_node.type == tree.XML_DOCUMENT_NODE or \
163
+ c_node.type == tree.XML_HTML_DOCUMENT_NODE:
164
+ #print "not freeing: still in doc"
165
+ return NULL
166
+ # if we're still attached to the document, don't deallocate
167
+ if hasProxy(c_node):
168
+ #print "Not freeing: proxies still exist"
169
+ return NULL
170
+ # see whether we have children to deallocate
171
+ if not canDeallocateChildNodes(c_node):
172
+ return NULL
173
+ # see whether we have siblings to deallocate
174
+ c_next = c_node.prev
175
+ while c_next:
176
+ if _isElement(c_next):
177
+ if hasProxy(c_next) or not canDeallocateChildNodes(c_next):
178
+ return NULL
179
+ c_next = c_next.prev
180
+ c_next = c_node.next
181
+ while c_next:
182
+ if _isElement(c_next):
183
+ if hasProxy(c_next) or not canDeallocateChildNodes(c_next):
184
+ return NULL
185
+ c_next = c_next.next
186
+ return c_node
187
+
188
+ cdef int canDeallocateChildNodes(xmlNode* c_parent) noexcept:
189
+ cdef xmlNode* c_node
190
+ c_node = c_parent.children
191
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_parent, c_node, 1)
192
+ if hasProxy(c_node):
193
+ return 0
194
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
195
+ return 1
196
+
197
+ ################################################################################
198
+ # fix _Document references and namespaces when a node changes documents
199
+
200
+ cdef void _copyParentNamespaces(xmlNode* c_from_node, xmlNode* c_to_node) noexcept nogil:
201
+ """Copy the namespaces of all ancestors of c_from_node to c_to_node.
202
+ """
203
+ cdef xmlNode* c_parent
204
+ cdef xmlNs* c_ns
205
+ cdef xmlNs* c_new_ns
206
+ cdef int prefix_known
207
+ c_parent = c_from_node.parent
208
+ while c_parent and (tree._isElementOrXInclude(c_parent) or
209
+ c_parent.type == tree.XML_DOCUMENT_NODE):
210
+ c_new_ns = c_parent.nsDef
211
+ while c_new_ns:
212
+ # libxml2 will check if the prefix is already defined
213
+ tree.xmlNewNs(c_to_node, c_new_ns.href, c_new_ns.prefix)
214
+ c_new_ns = c_new_ns.next
215
+ c_parent = c_parent.parent
216
+
217
+
218
+ ctypedef struct _ns_update_map:
219
+ xmlNs* old
220
+ xmlNs* new
221
+
222
+
223
+ ctypedef struct _nscache:
224
+ _ns_update_map* ns_map
225
+ size_t size
226
+ size_t last
227
+
228
+
229
+ cdef int _growNsCache(_nscache* c_ns_cache) except -1:
230
+ cdef _ns_update_map* ns_map_ptr
231
+ if c_ns_cache.size == 0:
232
+ c_ns_cache.size = 20
233
+ else:
234
+ c_ns_cache.size *= 2
235
+ ns_map_ptr = <_ns_update_map*> python.lxml_realloc(
236
+ c_ns_cache.ns_map, c_ns_cache.size, sizeof(_ns_update_map))
237
+ if not ns_map_ptr:
238
+ python.lxml_free(c_ns_cache.ns_map)
239
+ c_ns_cache.ns_map = NULL
240
+ raise MemoryError()
241
+ c_ns_cache.ns_map = ns_map_ptr
242
+ return 0
243
+
244
+
245
+ cdef inline int _appendToNsCache(_nscache* c_ns_cache,
246
+ xmlNs* c_old_ns, xmlNs* c_new_ns) except -1:
247
+ if c_ns_cache.last >= c_ns_cache.size:
248
+ _growNsCache(c_ns_cache)
249
+ c_ns_cache.ns_map[c_ns_cache.last] = _ns_update_map(old=c_old_ns, new=c_new_ns)
250
+ c_ns_cache.last += 1
251
+
252
+
253
+ cdef int _stripRedundantNamespaceDeclarations(xmlNode* c_element, _nscache* c_ns_cache,
254
+ xmlNs** c_del_ns_list) except -1:
255
+ """Removes namespace declarations from an element that are already
256
+ defined in its parents. Does not free the xmlNs's, just prepends
257
+ them to the c_del_ns_list.
258
+ """
259
+ cdef xmlNs* c_ns
260
+ cdef xmlNs* c_ns_next
261
+ cdef xmlNs** c_nsdef
262
+ # use a xmlNs** to handle assignments to "c_element.nsDef" correctly
263
+ c_nsdef = &c_element.nsDef
264
+ while c_nsdef[0] is not NULL:
265
+ c_ns = tree.xmlSearchNsByHref(
266
+ c_element.doc, c_element.parent, c_nsdef[0].href)
267
+ if c_ns is NULL:
268
+ # new namespace href => keep and cache the ns declaration
269
+ _appendToNsCache(c_ns_cache, c_nsdef[0], c_nsdef[0])
270
+ c_nsdef = &c_nsdef[0].next
271
+ else:
272
+ # known namespace href => cache mapping and strip old ns
273
+ _appendToNsCache(c_ns_cache, c_nsdef[0], c_ns)
274
+ # cut out c_nsdef.next and prepend it to garbage chain
275
+ c_ns_next = c_nsdef[0].next
276
+ c_nsdef[0].next = c_del_ns_list[0]
277
+ c_del_ns_list[0] = c_nsdef[0]
278
+ c_nsdef[0] = c_ns_next
279
+ return 0
280
+
281
+
282
+ cdef void _cleanUpFromNamespaceAdaptation(xmlNode* c_start_node,
283
+ _nscache* c_ns_cache, xmlNs* c_del_ns_list) noexcept:
284
+ # Try to recover from exceptions with really bad timing. We were in the middle
285
+ # of ripping out xmlNS-es and likely ran out of memory. Try to fix up the tree
286
+ # by re-adding the original xmlNs declarations (which might still be used in some
287
+ # places).
288
+ if c_ns_cache.ns_map:
289
+ python.lxml_free(c_ns_cache.ns_map)
290
+ if c_del_ns_list:
291
+ if not c_start_node.nsDef:
292
+ c_start_node.nsDef = c_del_ns_list
293
+ else:
294
+ c_ns = c_start_node.nsDef
295
+ while c_ns.next:
296
+ c_ns = c_ns.next
297
+ c_ns.next = c_del_ns_list
298
+
299
+
300
+ cdef int moveNodeToDocument(_Document doc, xmlDoc* c_source_doc,
301
+ xmlNode* c_element) except -1:
302
+ """Fix the xmlNs pointers of a node and its subtree that were moved.
303
+
304
+ Originally copied from libxml2's xmlReconciliateNs(). Expects
305
+ libxml2 doc pointers of node to be correct already, but fixes
306
+ _Document references.
307
+
308
+ For each node in the subtree, we do this:
309
+
310
+ 1) Remove redundant declarations of namespace that are already
311
+ defined in its parents.
312
+
313
+ 2) Replace namespaces that are *not* defined on the node or its
314
+ parents by the equivalent namespace declarations that *are*
315
+ defined on the node or its parents (possibly using a different
316
+ prefix). If a namespace is unknown, declare a new one on the
317
+ node.
318
+
319
+ 3) Reassign the names of tags and attribute from the dict of the
320
+ target document *iff* it is different from the dict used in the
321
+ source subtree.
322
+
323
+ 4) Set the Document reference to the new Document (if different).
324
+ This is done on backtracking to keep the original Document
325
+ alive as long as possible, until all its elements are updated.
326
+
327
+ Note that the namespace declarations are removed from the tree in
328
+ step 1), but freed only after the complete subtree was traversed
329
+ and all occurrences were replaced by tree-internal pointers.
330
+ """
331
+ cdef xmlNode* c_start_node
332
+ cdef xmlNode* c_node
333
+ cdef xmlDoc* c_doc = doc._c_doc
334
+ cdef tree.xmlAttr* c_attr
335
+ cdef char* c_name
336
+ cdef _nscache c_ns_cache = [NULL, 0, 0]
337
+ cdef xmlNs* c_del_ns_list = NULL
338
+ cdef proxy_count = 0
339
+
340
+ if not tree._isElementOrXInclude(c_element):
341
+ return 0
342
+
343
+ c_start_node = c_element
344
+
345
+ tree.BEGIN_FOR_EACH_FROM(c_element, c_element, 1)
346
+ if tree._isElementOrXInclude(c_element):
347
+ if hasProxy(c_element):
348
+ proxy_count += 1
349
+
350
+ # 1) cut out namespaces defined here that are already known by
351
+ # the ancestors
352
+ if c_element.nsDef is not NULL:
353
+ try:
354
+ _stripRedundantNamespaceDeclarations(c_element, &c_ns_cache, &c_del_ns_list)
355
+ except:
356
+ _cleanUpFromNamespaceAdaptation(c_start_node, &c_ns_cache, c_del_ns_list)
357
+ raise
358
+
359
+ # 2) make sure the namespaces of an element and its attributes
360
+ # are declared in this document (i.e. on the node or its parents)
361
+ if c_element.ns is not NULL:
362
+ _fixCNs(doc, c_start_node, c_element, &c_ns_cache, c_del_ns_list)
363
+
364
+ c_node = <xmlNode*>c_element.properties
365
+ while c_node is not NULL:
366
+ if c_node.ns is not NULL:
367
+ _fixCNs(doc, c_start_node, c_node, &c_ns_cache, c_del_ns_list)
368
+ c_node = c_node.next
369
+
370
+ tree.END_FOR_EACH_FROM(c_element)
371
+
372
+ # free now unused namespace declarations
373
+ if c_del_ns_list is not NULL:
374
+ tree.xmlFreeNsList(c_del_ns_list)
375
+
376
+ # cleanup
377
+ if c_ns_cache.ns_map is not NULL:
378
+ python.lxml_free(c_ns_cache.ns_map)
379
+
380
+ # 3) fix the names in the tree if we moved it from a different thread
381
+ if doc._c_doc.dict is not c_source_doc.dict:
382
+ fixThreadDictNames(c_start_node, c_source_doc.dict, doc._c_doc.dict)
383
+
384
+ # 4) fix _Document references
385
+ # (and potentially deallocate the source document)
386
+ if proxy_count > 0:
387
+ if proxy_count == 1 and c_start_node._private is not NULL:
388
+ proxy = getProxy(c_start_node)
389
+ if proxy is not None:
390
+ if proxy._doc is not doc:
391
+ proxy._doc = doc
392
+ else:
393
+ fixElementDocument(c_start_node, doc, proxy_count)
394
+ else:
395
+ fixElementDocument(c_start_node, doc, proxy_count)
396
+
397
+ return 0
398
+
399
+
400
+ cdef void _setTreeDoc(xmlNode* c_node, xmlDoc* c_doc) noexcept:
401
+ """Adaptation of 'xmlSetTreeDoc()' that deep-fixes the document links iteratively.
402
+ It avoids https://gitlab.gnome.org/GNOME/libxml2/issues/42
403
+ """
404
+ tree.BEGIN_FOR_EACH_FROM(c_node, c_node, 1)
405
+ if c_node.type == tree.XML_ELEMENT_NODE:
406
+ c_attr = <tree.xmlAttr*>c_node.properties
407
+ while c_attr:
408
+ if c_attr.atype == tree.XML_ATTRIBUTE_ID:
409
+ tree.xmlRemoveID(c_node.doc, c_attr)
410
+ c_attr.doc = c_doc
411
+ _fixDocChildren(c_attr.children, c_doc)
412
+ c_attr = c_attr.next
413
+ # Set doc link for all nodes, not only elements.
414
+ c_node.doc = c_doc
415
+ tree.END_FOR_EACH_FROM(c_node)
416
+
417
+
418
+ cdef inline void _fixDocChildren(xmlNode* c_child, xmlDoc* c_doc) noexcept:
419
+ while c_child:
420
+ c_child.doc = c_doc
421
+ if c_child.children:
422
+ _fixDocChildren(c_child.children, c_doc)
423
+ c_child = c_child.next
424
+
425
+
426
+ cdef int _fixCNs(_Document doc, xmlNode* c_start_node, xmlNode* c_node,
427
+ _nscache* c_ns_cache, xmlNs* c_del_ns_list) except -1:
428
+ cdef xmlNs* c_ns = NULL
429
+ cdef bint is_prefixed_attr = (c_node.type == tree.XML_ATTRIBUTE_NODE and c_node.ns.prefix)
430
+
431
+ for ns_map in c_ns_cache.ns_map[:c_ns_cache.last]:
432
+ if c_node.ns is ns_map.old:
433
+ if is_prefixed_attr and not ns_map.new.prefix:
434
+ # avoid dropping prefix from attributes
435
+ continue
436
+ c_ns = ns_map.new
437
+ break
438
+
439
+ if c_ns:
440
+ c_node.ns = c_ns
441
+ else:
442
+ # not in cache or not acceptable
443
+ # => find a replacement from this document
444
+ try:
445
+ c_ns = doc._findOrBuildNodeNs(
446
+ c_start_node, c_node.ns.href, c_node.ns.prefix,
447
+ c_node.type == tree.XML_ATTRIBUTE_NODE)
448
+ c_node.ns = c_ns
449
+ _appendToNsCache(c_ns_cache, c_node.ns, c_ns)
450
+ except:
451
+ _cleanUpFromNamespaceAdaptation(c_start_node, c_ns_cache, c_del_ns_list)
452
+ raise
453
+ return 0
454
+
455
+
456
+ cdef int fixElementDocument(xmlNode* c_element, _Document doc,
457
+ size_t proxy_count) except -1:
458
+ cdef xmlNode* c_node = c_element
459
+ cdef _Element proxy = None # init-to-None required due to fake-loop below
460
+ tree.BEGIN_FOR_EACH_FROM(c_element, c_node, 1)
461
+ if c_node._private is not NULL:
462
+ proxy = getProxy(c_node)
463
+ if proxy is not None:
464
+ if proxy._doc is not doc:
465
+ proxy._doc = doc
466
+ proxy_count -= 1
467
+ if proxy_count == 0:
468
+ return 0
469
+ tree.END_FOR_EACH_FROM(c_node)
470
+
471
+
472
+ cdef void fixThreadDictNames(xmlNode* c_element,
473
+ tree.xmlDict* c_src_dict,
474
+ tree.xmlDict* c_dict) noexcept nogil:
475
+ # re-assign the names of tags and attributes
476
+ #
477
+ # this should only be called when the element is based on a
478
+ # different libxml2 tag name dictionary
479
+ if c_element.type == tree.XML_DOCUMENT_NODE or \
480
+ c_element.type == tree.XML_HTML_DOCUMENT_NODE:
481
+ # may define "xml" namespace
482
+ fixThreadDictNsForNode(c_element, c_src_dict, c_dict)
483
+ if c_element.doc.extSubset:
484
+ fixThreadDictNamesForDtd(c_element.doc.extSubset, c_src_dict, c_dict)
485
+ if c_element.doc.intSubset:
486
+ fixThreadDictNamesForDtd(c_element.doc.intSubset, c_src_dict, c_dict)
487
+ c_element = c_element.children
488
+ while c_element is not NULL:
489
+ fixThreadDictNamesForNode(c_element, c_src_dict, c_dict)
490
+ c_element = c_element.next
491
+ elif tree._isElementOrXInclude(c_element):
492
+ fixThreadDictNamesForNode(c_element, c_src_dict, c_dict)
493
+
494
+
495
+ cdef inline void _fixThreadDictPtr(const_xmlChar** c_ptr,
496
+ tree.xmlDict* c_src_dict,
497
+ tree.xmlDict* c_dict) noexcept nogil:
498
+ c_str = c_ptr[0]
499
+ if c_str and c_src_dict and tree.xmlDictOwns(c_src_dict, c_str):
500
+ # return value can be NULL on memory error, but we don't handle that here
501
+ c_str = tree.xmlDictLookup(c_dict, c_str, -1)
502
+ if c_str:
503
+ c_ptr[0] = c_str
504
+
505
+
506
+ cdef void fixThreadDictNamesForNode(xmlNode* c_element,
507
+ tree.xmlDict* c_src_dict,
508
+ tree.xmlDict* c_dict) noexcept nogil:
509
+ cdef xmlNode* c_node = c_element
510
+ tree.BEGIN_FOR_EACH_FROM(c_element, c_node, 1)
511
+ if c_node.type in (tree.XML_ELEMENT_NODE, tree.XML_XINCLUDE_START):
512
+ fixThreadDictNamesForAttributes(
513
+ c_node.properties, c_src_dict, c_dict)
514
+ fixThreadDictNsForNode(c_node, c_src_dict, c_dict)
515
+ _fixThreadDictPtr(&c_node.name, c_src_dict, c_dict)
516
+ elif c_node.type == tree.XML_TEXT_NODE:
517
+ # libxml2's SAX2 parser interns some indentation space
518
+ fixThreadDictContentForNode(c_node, c_src_dict, c_dict)
519
+ elif c_node.type == tree.XML_COMMENT_NODE:
520
+ pass # don't touch c_node.name
521
+ else:
522
+ _fixThreadDictPtr(&c_node.name, c_src_dict, c_dict)
523
+ tree.END_FOR_EACH_FROM(c_node)
524
+
525
+
526
+ cdef inline void fixThreadDictNamesForAttributes(tree.xmlAttr* c_attr,
527
+ tree.xmlDict* c_src_dict,
528
+ tree.xmlDict* c_dict) noexcept nogil:
529
+ cdef xmlNode* c_child
530
+ cdef xmlNode* c_node = <xmlNode*>c_attr
531
+ while c_node is not NULL:
532
+ if c_node.type not in (tree.XML_TEXT_NODE, tree.XML_COMMENT_NODE):
533
+ _fixThreadDictPtr(&c_node.name, c_src_dict, c_dict)
534
+ # libxml2 keeps some (!) attribute values in the dict
535
+ c_child = c_node.children
536
+ while c_child is not NULL:
537
+ fixThreadDictContentForNode(c_child, c_src_dict, c_dict)
538
+ c_child = c_child.next
539
+ c_node = c_node.next
540
+
541
+
542
+ cdef inline void fixThreadDictContentForNode(xmlNode* c_node,
543
+ tree.xmlDict* c_src_dict,
544
+ tree.xmlDict* c_dict) noexcept nogil:
545
+ if c_node.content is not NULL and \
546
+ c_node.content is not <xmlChar*>&c_node.properties:
547
+ if tree.xmlDictOwns(c_src_dict, c_node.content):
548
+ # result can be NULL on memory error, but we don't handle that here
549
+ c_node.content = <xmlChar*>tree.xmlDictLookup(c_dict, c_node.content, -1)
550
+
551
+
552
+ cdef inline void fixThreadDictNsForNode(xmlNode* c_node,
553
+ tree.xmlDict* c_src_dict,
554
+ tree.xmlDict* c_dict) noexcept nogil:
555
+ cdef xmlNs* c_ns = c_node.nsDef
556
+ while c_ns is not NULL:
557
+ _fixThreadDictPtr(&c_ns.href, c_src_dict, c_dict)
558
+ _fixThreadDictPtr(&c_ns.prefix, c_src_dict, c_dict)
559
+ c_ns = c_ns.next
560
+
561
+
562
+ cdef void fixThreadDictNamesForDtd(tree.xmlDtd* c_dtd,
563
+ tree.xmlDict* c_src_dict,
564
+ tree.xmlDict* c_dict) noexcept nogil:
565
+ cdef xmlNode* c_node
566
+ cdef tree.xmlElement* c_element
567
+ cdef tree.xmlAttribute* c_attribute
568
+ cdef tree.xmlEntity* c_entity
569
+
570
+ c_node = c_dtd.children
571
+ while c_node:
572
+ if c_node.type == tree.XML_ELEMENT_DECL:
573
+ c_element = <tree.xmlElement*>c_node
574
+ if c_element.content:
575
+ _fixThreadDictPtr(&c_element.content.name, c_src_dict, c_dict)
576
+ _fixThreadDictPtr(&c_element.content.prefix, c_src_dict, c_dict)
577
+ c_attribute = c_element.attributes
578
+ while c_attribute:
579
+ if tree.LIBXML_VERSION < 21500:
580
+ # libxml2 2.15 no longer stores default values in the dict.
581
+ # See https://gitlab.gnome.org/GNOME/libxml2/-/commit/24628f25
582
+ _fixThreadDictPtr(<const_xmlChar**>&c_attribute.defaultValue, c_src_dict, c_dict)
583
+ _fixThreadDictPtr(&c_attribute.name, c_src_dict, c_dict)
584
+ _fixThreadDictPtr(&c_attribute.prefix, c_src_dict, c_dict)
585
+ _fixThreadDictPtr(&c_attribute.elem, c_src_dict, c_dict)
586
+ c_attribute = c_attribute.nexth
587
+ elif c_node.type == tree.XML_ENTITY_DECL:
588
+ c_entity = <tree.xmlEntity*>c_node
589
+ _fixThreadDictPtr(&c_entity.name, c_src_dict, c_dict)
590
+ _fixThreadDictPtr(&c_entity.ExternalID, c_src_dict, c_dict)
591
+ _fixThreadDictPtr(&c_entity.SystemID, c_src_dict, c_dict)
592
+ _fixThreadDictPtr(<const_xmlChar**>&c_entity.content, c_src_dict, c_dict)
593
+ c_node = c_node.next
594
+
595
+
596
+ ################################################################################
597
+ # adopt an xmlDoc from an external libxml2 document source
598
+
599
+ cdef _Document _adoptForeignDoc(xmlDoc* c_doc, _BaseParser parser=None, bint is_owned=True):
600
+ """Convert and wrap an externally produced xmlDoc for use in lxml.
601
+ Assures that all '_private' pointers are NULL to prevent accidental
602
+ dereference into lxml proxy objects.
603
+ """
604
+ if c_doc is NULL:
605
+ raise ValueError("Illegal document provided: NULL")
606
+ if c_doc.type not in (tree.XML_DOCUMENT_NODE, tree.XML_HTML_DOCUMENT_NODE):
607
+ doc_type = c_doc.type
608
+ if is_owned:
609
+ tree.xmlFreeDoc(c_doc)
610
+ raise ValueError(f"Illegal document provided: expected XML or HTML, found {doc_type}")
611
+
612
+ cdef xmlNode* c_node = <xmlNode*>c_doc
613
+
614
+ if is_owned:
615
+ tree.BEGIN_FOR_EACH_FROM(<xmlNode*>c_doc, c_node, 1)
616
+ c_node._private = NULL
617
+ tree.END_FOR_EACH_FROM(c_node)
618
+ else:
619
+ # create a fresh copy that lxml owns
620
+ c_doc = tree.xmlCopyDoc(c_doc, 1)
621
+ if c_doc is NULL:
622
+ raise MemoryError()
623
+
624
+ return _documentFactory(c_doc, parser)
.venv/lib/python3.12/site-packages/lxml/public-api.pxi ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Public C API for lxml.etree
2
+
3
+ cdef public api _Element deepcopyNodeToDocument(_Document doc, xmlNode* c_root):
4
+ "Recursively copy the element into the document. doc is not modified."
5
+ cdef xmlNode* c_node
6
+ c_node = _copyNodeToDoc(c_root, doc._c_doc)
7
+ return _elementFactory(doc, c_node)
8
+
9
+ cdef public api _ElementTree elementTreeFactory(_Element context_node):
10
+ _assertValidNode(context_node)
11
+ return newElementTree(context_node, _ElementTree)
12
+
13
+ cdef public api _ElementTree newElementTree(_Element context_node,
14
+ object subclass):
15
+ if <void*>context_node is NULL or context_node is None:
16
+ raise TypeError
17
+ _assertValidNode(context_node)
18
+ return _newElementTree(context_node._doc, context_node, subclass)
19
+
20
+ cdef public api _ElementTree adoptExternalDocument(xmlDoc* c_doc, parser, bint is_owned):
21
+ if c_doc is NULL:
22
+ raise TypeError
23
+ doc = _adoptForeignDoc(c_doc, parser, is_owned)
24
+ return _elementTreeFactory(doc, None)
25
+
26
+ cdef public api _Element elementFactory(_Document doc, xmlNode* c_node):
27
+ if c_node is NULL or doc is None:
28
+ raise TypeError
29
+ return _elementFactory(doc, c_node)
30
+
31
+ cdef public api _Element makeElement(tag, _Document doc, parser,
32
+ text, tail, attrib, nsmap):
33
+ return _makeElement(tag, NULL, doc, parser, text, tail, attrib, nsmap, None)
34
+
35
+ cdef public api _Element makeSubElement(_Element parent, tag, text, tail,
36
+ attrib, nsmap):
37
+ _assertValidNode(parent)
38
+ return _makeSubElement(parent, tag, text, tail, attrib, nsmap, None)
39
+
40
+ cdef public api void setElementClassLookupFunction(
41
+ _element_class_lookup_function function, state):
42
+ _setElementClassLookupFunction(function, state)
43
+
44
+ cdef public api object lookupDefaultElementClass(state, doc, xmlNode* c_node):
45
+ return _lookupDefaultElementClass(state, doc, c_node)
46
+
47
+ cdef public api object lookupNamespaceElementClass(state, doc, xmlNode* c_node):
48
+ return _find_nselement_class(state, doc, c_node)
49
+
50
+ cdef public api object callLookupFallback(FallbackElementClassLookup lookup,
51
+ _Document doc, xmlNode* c_node):
52
+ return _callLookupFallback(lookup, doc, c_node)
53
+
54
+ cdef public api int tagMatches(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
55
+ if c_node is NULL:
56
+ return -1
57
+ return _tagMatches(c_node, c_href, c_name)
58
+
59
+ cdef public api _Document documentOrRaise(object input):
60
+ return _documentOrRaise(input)
61
+
62
+ cdef public api _Element rootNodeOrRaise(object input):
63
+ return _rootNodeOrRaise(input)
64
+
65
+ cdef public api bint hasText(xmlNode* c_node) noexcept:
66
+ return _hasText(c_node)
67
+
68
+ cdef public api bint hasTail(xmlNode* c_node) noexcept:
69
+ return _hasTail(c_node)
70
+
71
+ cdef public api unicode textOf(xmlNode* c_node):
72
+ if c_node is NULL:
73
+ return None
74
+ return _collectText(c_node.children)
75
+
76
+ cdef public api unicode tailOf(xmlNode* c_node):
77
+ if c_node is NULL:
78
+ return None
79
+ return _collectText(c_node.next)
80
+
81
+ cdef public api int setNodeText(xmlNode* c_node, text) except -1:
82
+ if c_node is NULL:
83
+ raise ValueError
84
+ return _setNodeText(c_node, text)
85
+
86
+ cdef public api int setTailText(xmlNode* c_node, text) except -1:
87
+ if c_node is NULL:
88
+ raise ValueError
89
+ return _setTailText(c_node, text)
90
+
91
+ cdef public api unicode attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node):
92
+ return _attributeValue(c_element, c_attrib_node)
93
+
94
+ cdef public api unicode attributeValueFromNsName(xmlNode* c_element,
95
+ const_xmlChar* ns, const_xmlChar* name):
96
+ return _attributeValueFromNsName(c_element, ns, name)
97
+
98
+ cdef public api object getAttributeValue(_Element element, key, default):
99
+ _assertValidNode(element)
100
+ return _getAttributeValue(element, key, default)
101
+
102
+ cdef public api object iterattributes(_Element element, int keysvalues):
103
+ _assertValidNode(element)
104
+ return _attributeIteratorFactory(element, keysvalues)
105
+
106
+ cdef public api list collectAttributes(xmlNode* c_element, int keysvalues):
107
+ return _collectAttributes(c_element, keysvalues)
108
+
109
+ cdef public api int setAttributeValue(_Element element, key, value) except -1:
110
+ _assertValidNode(element)
111
+ return _setAttributeValue(element, key, value)
112
+
113
+ cdef public api int delAttribute(_Element element, key) except -1:
114
+ _assertValidNode(element)
115
+ return _delAttribute(element, key)
116
+
117
+ cdef public api int delAttributeFromNsName(tree.xmlNode* c_element,
118
+ const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
119
+ return _delAttributeFromNsName(c_element, c_href, c_name)
120
+
121
+ cdef public api bint hasChild(xmlNode* c_node) noexcept:
122
+ return _hasChild(c_node)
123
+
124
+ cdef public api xmlNode* findChild(xmlNode* c_node, Py_ssize_t index) noexcept:
125
+ return _findChild(c_node, index)
126
+
127
+ cdef public api xmlNode* findChildForwards(xmlNode* c_node, Py_ssize_t index) noexcept:
128
+ return _findChildForwards(c_node, index)
129
+
130
+ cdef public api xmlNode* findChildBackwards(xmlNode* c_node, Py_ssize_t index) noexcept:
131
+ return _findChildBackwards(c_node, index)
132
+
133
+ cdef public api xmlNode* nextElement(xmlNode* c_node) noexcept:
134
+ return _nextElement(c_node)
135
+
136
+ cdef public api xmlNode* previousElement(xmlNode* c_node) noexcept:
137
+ return _previousElement(c_node)
138
+
139
+ cdef public api void appendChild(_Element parent, _Element child):
140
+ # deprecated, use appendChildToElement() instead!
141
+ _appendChild(parent, child)
142
+
143
+ cdef public api int appendChildToElement(_Element parent, _Element child) except -1:
144
+ return _appendChild(parent, child)
145
+
146
+ cdef public api unicode pyunicode(const_xmlChar* s):
147
+ if s is NULL:
148
+ raise TypeError
149
+ return funicode(s)
150
+
151
+ cdef public api bytes utf8(object s):
152
+ return _utf8(s)
153
+
154
+ cdef public api tuple getNsTag(object tag):
155
+ return _getNsTag(tag)
156
+
157
+ cdef public api tuple getNsTagWithEmptyNs(object tag):
158
+ return _getNsTagWithEmptyNs(tag)
159
+
160
+ cdef public api unicode namespacedName(xmlNode* c_node):
161
+ return _namespacedName(c_node)
162
+
163
+ cdef public api unicode namespacedNameFromNsName(const_xmlChar* href, const_xmlChar* name):
164
+ return _namespacedNameFromNsName(href, name)
165
+
166
+ cdef public api void iteratorStoreNext(_ElementIterator iterator, _Element node):
167
+ # deprecated!
168
+ iterator._storeNext(node)
169
+
170
+ cdef public api void initTagMatch(_ElementTagMatcher matcher, tag):
171
+ # deprecated!
172
+ matcher._initTagMatch(tag)
173
+
174
+ cdef public api tree.xmlNs* findOrBuildNodeNsPrefix(
175
+ _Document doc, xmlNode* c_node, const_xmlChar* href, const_xmlChar* prefix) except NULL:
176
+ if doc is None:
177
+ raise TypeError
178
+ return doc._findOrBuildNodeNs(c_node, href, prefix, 0)
.venv/lib/python3.12/site-packages/lxml/pyclasslookup.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # dummy module for backwards compatibility
2
+
3
+ from lxml.etree import PythonElementClassLookup
.venv/lib/python3.12/site-packages/lxml/readonlytree.pxi ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # read-only tree implementation
2
+
3
+ @cython.internal
4
+ cdef class _ReadOnlyProxy:
5
+ "A read-only proxy class suitable for PIs/Comments (for internal use only!)."
6
+ cdef bint _free_after_use
7
+ cdef xmlNode* _c_node
8
+ cdef _ReadOnlyProxy _source_proxy
9
+ cdef list _dependent_proxies
10
+ def __cinit__(self):
11
+ self._c_node = NULL
12
+ self._free_after_use = 0
13
+
14
+ cdef int _assertNode(self) except -1:
15
+ """This is our way of saying: this proxy is invalid!
16
+ """
17
+ if not self._c_node:
18
+ raise ReferenceError("Proxy invalidated!")
19
+ return 0
20
+
21
+ cdef int _raise_unsupported_type(self) except -1:
22
+ raise TypeError(f"Unsupported node type: {self._c_node.type}")
23
+
24
+ cdef void free_after_use(self) noexcept:
25
+ """Should the xmlNode* be freed when releasing the proxy?
26
+ """
27
+ self._free_after_use = 1
28
+
29
+ @property
30
+ def tag(self):
31
+ """Element tag
32
+ """
33
+ self._assertNode()
34
+ if self._c_node.type == tree.XML_ELEMENT_NODE:
35
+ return _namespacedName(self._c_node)
36
+ elif self._c_node.type == tree.XML_PI_NODE:
37
+ return ProcessingInstruction
38
+ elif self._c_node.type == tree.XML_COMMENT_NODE:
39
+ return Comment
40
+ elif self._c_node.type == tree.XML_ENTITY_REF_NODE:
41
+ return Entity
42
+ else:
43
+ self._raise_unsupported_type()
44
+
45
+ @property
46
+ def text(self):
47
+ """Text before the first subelement. This is either a string or
48
+ the value None, if there was no text.
49
+ """
50
+ self._assertNode()
51
+ if self._c_node.type == tree.XML_ELEMENT_NODE:
52
+ return _collectText(self._c_node.children)
53
+ elif self._c_node.type in (tree.XML_PI_NODE,
54
+ tree.XML_COMMENT_NODE):
55
+ if self._c_node.content is NULL:
56
+ return ''
57
+ else:
58
+ return funicode(self._c_node.content)
59
+ elif self._c_node.type == tree.XML_ENTITY_REF_NODE:
60
+ return f'&{funicode(self._c_node.name)};'
61
+ else:
62
+ self._raise_unsupported_type()
63
+
64
+ @property
65
+ def tail(self):
66
+ """Text after this element's end tag, but before the next sibling
67
+ element's start tag. This is either a string or the value None, if
68
+ there was no text.
69
+ """
70
+ self._assertNode()
71
+ return _collectText(self._c_node.next)
72
+
73
+ @property
74
+ def sourceline(self):
75
+ """Original line number as found by the parser or None if unknown.
76
+ """
77
+ cdef long line
78
+ self._assertNode()
79
+ line = tree.xmlGetLineNo(self._c_node)
80
+ if line > 0:
81
+ return line
82
+ else:
83
+ return None
84
+
85
+ def __repr__(self):
86
+ self._assertNode()
87
+ if self._c_node.type == tree.XML_ELEMENT_NODE:
88
+ return "<Element %s at 0x%x>" % (self.tag, id(self))
89
+ elif self._c_node.type == tree.XML_COMMENT_NODE:
90
+ return "<!--%s-->" % self.text
91
+ elif self._c_node.type == tree.XML_ENTITY_NODE:
92
+ return "&%s;" % funicode(self._c_node.name)
93
+ elif self._c_node.type == tree.XML_PI_NODE:
94
+ text = self.text
95
+ if text:
96
+ return "<?%s %s?>" % (self.target, text)
97
+ else:
98
+ return "<?%s?>" % self.target
99
+ else:
100
+ self._raise_unsupported_type()
101
+
102
+ def __getitem__(self, x):
103
+ """Returns the subelement at the given position or the requested
104
+ slice.
105
+ """
106
+ cdef xmlNode* c_node = NULL
107
+ cdef Py_ssize_t step = 0, slicelength = 0
108
+ cdef Py_ssize_t c, i
109
+ cdef _node_to_node_function next_element
110
+ cdef list result
111
+ self._assertNode()
112
+ if isinstance(x, slice):
113
+ # slicing
114
+ if _isFullSlice(<slice>x):
115
+ return _collectChildren(self)
116
+ _findChildSlice(<slice>x, self._c_node, &c_node, &step, &slicelength)
117
+ if c_node is NULL:
118
+ return []
119
+ if step > 0:
120
+ next_element = _nextElement
121
+ else:
122
+ step = -step if step != python.PY_SSIZE_T_MIN else python.PY_SSIZE_T_MAX
123
+ next_element = _previousElement
124
+ result = []
125
+ c = 0
126
+ while c_node is not NULL and c < slicelength:
127
+ result.append(_newReadOnlyProxy(self._source_proxy, c_node))
128
+ result.append(_elementFactory(self._doc, c_node))
129
+ c = c + 1
130
+ for i from 0 <= i < step:
131
+ c_node = next_element(c_node)
132
+ return result
133
+ else:
134
+ # indexing
135
+ c_node = _findChild(self._c_node, x)
136
+ if c_node is NULL:
137
+ raise IndexError, "list index out of range"
138
+ return _newReadOnlyProxy(self._source_proxy, c_node)
139
+
140
+ def __len__(self):
141
+ """Returns the number of subelements.
142
+ """
143
+ cdef Py_ssize_t c
144
+ cdef xmlNode* c_node
145
+ self._assertNode()
146
+ c = 0
147
+ c_node = self._c_node.children
148
+ while c_node is not NULL:
149
+ if tree._isElement(c_node):
150
+ c = c + 1
151
+ c_node = c_node.next
152
+ return c
153
+
154
+ def __bool__(self):
155
+ cdef xmlNode* c_node
156
+ self._assertNode()
157
+ c_node = _findChildBackwards(self._c_node, 0)
158
+ return c_node != NULL
159
+
160
+ def __deepcopy__(self, memo):
161
+ "__deepcopy__(self, memo)"
162
+ return self.__copy__()
163
+
164
+ cpdef __copy__(self):
165
+ "__copy__(self)"
166
+ cdef xmlDoc* c_doc
167
+ cdef xmlNode* c_node
168
+ cdef _Document new_doc
169
+ if self._c_node is NULL:
170
+ return self
171
+ c_doc = _copyDocRoot(self._c_node.doc, self._c_node) # recursive
172
+ new_doc = _documentFactory(c_doc, None)
173
+ root = new_doc.getroot()
174
+ if root is not None:
175
+ return root
176
+ # Comment/PI
177
+ c_node = c_doc.children
178
+ while c_node is not NULL and c_node.type != self._c_node.type:
179
+ c_node = c_node.next
180
+ if c_node is NULL:
181
+ return None
182
+ return _elementFactory(new_doc, c_node)
183
+
184
+ def __iter__(self):
185
+ return iter(self.getchildren())
186
+
187
+ def iterchildren(self, tag=None, *, reversed=False):
188
+ """iterchildren(self, tag=None, reversed=False)
189
+
190
+ Iterate over the children of this element.
191
+ """
192
+ children = self.getchildren()
193
+ if tag is not None and tag != '*':
194
+ children = [ el for el in children if el.tag == tag ]
195
+ if reversed:
196
+ children = children[::-1]
197
+ return iter(children)
198
+
199
+ cpdef getchildren(self):
200
+ """Returns all subelements. The elements are returned in document
201
+ order.
202
+ """
203
+ cdef xmlNode* c_node
204
+ cdef list result
205
+ self._assertNode()
206
+ result = []
207
+ c_node = self._c_node.children
208
+ while c_node is not NULL:
209
+ if tree._isElement(c_node):
210
+ result.append(_newReadOnlyProxy(self._source_proxy, c_node))
211
+ c_node = c_node.next
212
+ return result
213
+
214
+ def getparent(self):
215
+ """Returns the parent of this element or None for the root element.
216
+ """
217
+ cdef xmlNode* c_parent
218
+ self._assertNode()
219
+ c_parent = self._c_node.parent
220
+ if c_parent is NULL or not tree._isElement(c_parent):
221
+ return None
222
+ else:
223
+ return _newReadOnlyProxy(self._source_proxy, c_parent)
224
+
225
+ def getnext(self):
226
+ """Returns the following sibling of this element or None.
227
+ """
228
+ cdef xmlNode* c_node
229
+ self._assertNode()
230
+ c_node = _nextElement(self._c_node)
231
+ if c_node is not NULL:
232
+ return _newReadOnlyProxy(self._source_proxy, c_node)
233
+ return None
234
+
235
+ def getprevious(self):
236
+ """Returns the preceding sibling of this element or None.
237
+ """
238
+ cdef xmlNode* c_node
239
+ self._assertNode()
240
+ c_node = _previousElement(self._c_node)
241
+ if c_node is not NULL:
242
+ return _newReadOnlyProxy(self._source_proxy, c_node)
243
+ return None
244
+
245
+
246
+ @cython.final
247
+ @cython.internal
248
+ cdef class _ReadOnlyPIProxy(_ReadOnlyProxy):
249
+ """A read-only proxy for processing instructions (for internal use only!)"""
250
+ @property
251
+ def target(self):
252
+ self._assertNode()
253
+ return funicode(self._c_node.name)
254
+
255
+ @cython.final
256
+ @cython.internal
257
+ cdef class _ReadOnlyEntityProxy(_ReadOnlyProxy):
258
+ """A read-only proxy for entity references (for internal use only!)"""
259
+ property name:
260
+ def __get__(self):
261
+ return funicode(self._c_node.name)
262
+
263
+ def __set__(self, value):
264
+ value_utf = _utf8(value)
265
+ if '&' in value or ';' in value:
266
+ raise ValueError(f"Invalid entity name '{value}'")
267
+ tree.xmlNodeSetName(self._c_node, _xcstr(value_utf))
268
+
269
+ @property
270
+ def text(self):
271
+ return f'&{funicode(self._c_node.name)};'
272
+
273
+
274
+ @cython.internal
275
+ cdef class _ReadOnlyElementProxy(_ReadOnlyProxy):
276
+ """The main read-only Element proxy class (for internal use only!)."""
277
+
278
+ @property
279
+ def attrib(self):
280
+ self._assertNode()
281
+ return dict(_collectAttributes(self._c_node, 3))
282
+
283
+ @property
284
+ def prefix(self):
285
+ """Namespace prefix or None.
286
+ """
287
+ self._assertNode()
288
+ if self._c_node.ns is not NULL:
289
+ if self._c_node.ns.prefix is not NULL:
290
+ return funicode(self._c_node.ns.prefix)
291
+ return None
292
+
293
+ @property
294
+ def nsmap(self):
295
+ """Namespace prefix->URI mapping known in the context of this
296
+ Element. This includes all namespace declarations of the
297
+ parents.
298
+
299
+ Note that changing the returned dict has no effect on the Element.
300
+ """
301
+ self._assertNode()
302
+ return _build_nsmap(self._c_node)
303
+
304
+ def get(self, key, default=None):
305
+ """Gets an element attribute.
306
+ """
307
+ self._assertNode()
308
+ return _getNodeAttributeValue(self._c_node, key, default)
309
+
310
+ def keys(self):
311
+ """Gets a list of attribute names. The names are returned in an
312
+ arbitrary order (just like for an ordinary Python dictionary).
313
+ """
314
+ self._assertNode()
315
+ return _collectAttributes(self._c_node, 1)
316
+
317
+ def values(self):
318
+ """Gets element attributes, as a sequence. The attributes are returned
319
+ in an arbitrary order.
320
+ """
321
+ self._assertNode()
322
+ return _collectAttributes(self._c_node, 2)
323
+
324
+ def items(self):
325
+ """Gets element attributes, as a sequence. The attributes are returned
326
+ in an arbitrary order.
327
+ """
328
+ self._assertNode()
329
+ return _collectAttributes(self._c_node, 3)
330
+
331
+ cdef _ReadOnlyProxy _newReadOnlyProxy(
332
+ _ReadOnlyProxy source_proxy, xmlNode* c_node):
333
+ cdef _ReadOnlyProxy el
334
+ if c_node.type == tree.XML_ELEMENT_NODE:
335
+ el = _ReadOnlyElementProxy.__new__(_ReadOnlyElementProxy)
336
+ elif c_node.type == tree.XML_PI_NODE:
337
+ el = _ReadOnlyPIProxy.__new__(_ReadOnlyPIProxy)
338
+ elif c_node.type in (tree.XML_COMMENT_NODE,
339
+ tree.XML_ENTITY_REF_NODE):
340
+ el = _ReadOnlyProxy.__new__(_ReadOnlyProxy)
341
+ else:
342
+ raise TypeError(f"Unsupported element type: {c_node.type}")
343
+ el._c_node = c_node
344
+ _initReadOnlyProxy(el, source_proxy)
345
+ return el
346
+
347
+ cdef inline _initReadOnlyProxy(_ReadOnlyProxy el,
348
+ _ReadOnlyProxy source_proxy):
349
+ if source_proxy is None:
350
+ el._source_proxy = el
351
+ el._dependent_proxies = [el]
352
+ else:
353
+ el._source_proxy = source_proxy
354
+ source_proxy._dependent_proxies.append(el)
355
+
356
+ cdef _freeReadOnlyProxies(_ReadOnlyProxy sourceProxy):
357
+ cdef xmlNode* c_node
358
+ cdef _ReadOnlyProxy el
359
+ if sourceProxy is None:
360
+ return
361
+ if sourceProxy._dependent_proxies is None:
362
+ return
363
+ for el in sourceProxy._dependent_proxies:
364
+ c_node = el._c_node
365
+ el._c_node = NULL
366
+ if el._free_after_use:
367
+ tree.xmlFreeNode(c_node)
368
+ del sourceProxy._dependent_proxies[:]
369
+
370
+ # opaque wrapper around non-element nodes, e.g. the document node
371
+ #
372
+ # This class does not imply any restrictions on modifiability or
373
+ # read-only status of the node, so use with caution.
374
+
375
+ @cython.internal
376
+ cdef class _OpaqueNodeWrapper:
377
+ cdef tree.xmlNode* _c_node
378
+ def __init__(self):
379
+ raise TypeError, "This type cannot be instantiated from Python"
380
+
381
+ @cython.final
382
+ @cython.internal
383
+ cdef class _OpaqueDocumentWrapper(_OpaqueNodeWrapper):
384
+ cdef int _assertNode(self) except -1:
385
+ """This is our way of saying: this proxy is invalid!
386
+ """
387
+ assert self._c_node is not NULL, "Proxy invalidated!"
388
+ return 0
389
+
390
+ cpdef append(self, other_element):
391
+ """Append a copy of an Element to the list of children.
392
+ """
393
+ cdef xmlNode* c_next
394
+ cdef xmlNode* c_node
395
+ self._assertNode()
396
+ c_node = _roNodeOf(other_element)
397
+ if c_node.type == tree.XML_ELEMENT_NODE:
398
+ if tree.xmlDocGetRootElement(<tree.xmlDoc*>self._c_node) is not NULL:
399
+ raise ValueError, "cannot append, document already has a root element"
400
+ elif c_node.type not in (tree.XML_PI_NODE, tree.XML_COMMENT_NODE):
401
+ raise TypeError, f"unsupported element type for top-level node: {c_node.type}"
402
+ c_node = _copyNodeToDoc(c_node, <tree.xmlDoc*>self._c_node)
403
+ c_next = c_node.next
404
+ tree.xmlAddChild(self._c_node, c_node)
405
+ _moveTail(c_next, c_node)
406
+
407
+ def extend(self, elements):
408
+ """Append a copy of all Elements from a sequence to the list of
409
+ children.
410
+ """
411
+ self._assertNode()
412
+ for element in elements:
413
+ self.append(element)
414
+
415
+ cdef _OpaqueNodeWrapper _newOpaqueAppendOnlyNodeWrapper(xmlNode* c_node):
416
+ cdef _OpaqueNodeWrapper node
417
+ if c_node.type in (tree.XML_DOCUMENT_NODE, tree.XML_HTML_DOCUMENT_NODE):
418
+ node = _OpaqueDocumentWrapper.__new__(_OpaqueDocumentWrapper)
419
+ else:
420
+ node = _OpaqueNodeWrapper.__new__(_OpaqueNodeWrapper)
421
+ node._c_node = c_node
422
+ return node
423
+
424
+ # element proxies that allow restricted modification
425
+
426
+ @cython.internal
427
+ cdef class _ModifyContentOnlyProxy(_ReadOnlyProxy):
428
+ """A read-only proxy that allows changing the text content.
429
+ """
430
+ property text:
431
+ def __get__(self):
432
+ self._assertNode()
433
+ if self._c_node.content is NULL:
434
+ return ''
435
+ else:
436
+ return funicode(self._c_node.content)
437
+
438
+ def __set__(self, value):
439
+ cdef tree.xmlDict* c_dict
440
+ self._assertNode()
441
+ if value is None:
442
+ c_text = <const_xmlChar*>NULL
443
+ else:
444
+ value = _utf8(value)
445
+ c_text = _xcstr(value)
446
+ tree.xmlNodeSetContent(self._c_node, c_text)
447
+
448
+ @cython.final
449
+ @cython.internal
450
+ cdef class _ModifyContentOnlyPIProxy(_ModifyContentOnlyProxy):
451
+ """A read-only proxy that allows changing the text/target content of a
452
+ processing instruction.
453
+ """
454
+ property target:
455
+ def __get__(self):
456
+ self._assertNode()
457
+ return funicode(self._c_node.name)
458
+
459
+ def __set__(self, value):
460
+ self._assertNode()
461
+ value = _utf8(value)
462
+ c_text = _xcstr(value)
463
+ tree.xmlNodeSetName(self._c_node, c_text)
464
+
465
+ @cython.final
466
+ @cython.internal
467
+ cdef class _ModifyContentOnlyEntityProxy(_ModifyContentOnlyProxy):
468
+ "A read-only proxy for entity references (for internal use only!)"
469
+ property name:
470
+ def __get__(self):
471
+ return funicode(self._c_node.name)
472
+
473
+ def __set__(self, value):
474
+ value = _utf8(value)
475
+ assert '&' not in value and ';' not in value, \
476
+ f"Invalid entity name '{value}'"
477
+ c_text = _xcstr(value)
478
+ tree.xmlNodeSetName(self._c_node, c_text)
479
+
480
+
481
+ @cython.final
482
+ @cython.internal
483
+ cdef class _AppendOnlyElementProxy(_ReadOnlyElementProxy):
484
+ """A read-only element that allows adding children and changing the
485
+ text content (i.e. everything that adds to the subtree).
486
+ """
487
+ cpdef append(self, other_element):
488
+ """Append a copy of an Element to the list of children.
489
+ """
490
+ cdef xmlNode* c_next
491
+ cdef xmlNode* c_node
492
+ self._assertNode()
493
+ c_node = _roNodeOf(other_element)
494
+ c_node = _copyNodeToDoc(c_node, self._c_node.doc)
495
+ c_next = c_node.next
496
+ tree.xmlAddChild(self._c_node, c_node)
497
+ _moveTail(c_next, c_node)
498
+
499
+ def extend(self, elements):
500
+ """Append a copy of all Elements from a sequence to the list of
501
+ children.
502
+ """
503
+ self._assertNode()
504
+ for element in elements:
505
+ self.append(element)
506
+
507
+ property text:
508
+ """Text before the first subelement. This is either a string or the
509
+ value None, if there was no text.
510
+ """
511
+ def __get__(self):
512
+ self._assertNode()
513
+ return _collectText(self._c_node.children)
514
+
515
+ def __set__(self, value):
516
+ self._assertNode()
517
+ if isinstance(value, QName):
518
+ value = _resolveQNameText(self, value).decode('utf8')
519
+ _setNodeText(self._c_node, value)
520
+
521
+
522
+ cdef _ReadOnlyProxy _newAppendOnlyProxy(
523
+ _ReadOnlyProxy source_proxy, xmlNode* c_node):
524
+ cdef _ReadOnlyProxy el
525
+ if c_node.type == tree.XML_ELEMENT_NODE:
526
+ el = _AppendOnlyElementProxy.__new__(_AppendOnlyElementProxy)
527
+ elif c_node.type == tree.XML_PI_NODE:
528
+ el = _ModifyContentOnlyPIProxy.__new__(_ModifyContentOnlyPIProxy)
529
+ elif c_node.type == tree.XML_COMMENT_NODE:
530
+ el = _ModifyContentOnlyProxy.__new__(_ModifyContentOnlyProxy)
531
+ else:
532
+ raise TypeError(f"Unsupported element type: {c_node.type}")
533
+ el._c_node = c_node
534
+ _initReadOnlyProxy(el, source_proxy)
535
+ return el
536
+
537
+ cdef xmlNode* _roNodeOf(element) except NULL:
538
+ cdef xmlNode* c_node
539
+ if isinstance(element, _Element):
540
+ c_node = (<_Element>element)._c_node
541
+ elif isinstance(element, _ReadOnlyProxy):
542
+ c_node = (<_ReadOnlyProxy>element)._c_node
543
+ elif isinstance(element, _OpaqueNodeWrapper):
544
+ c_node = (<_OpaqueNodeWrapper>element)._c_node
545
+ else:
546
+ raise TypeError, f"invalid argument type {type(element)}"
547
+
548
+ if c_node is NULL:
549
+ raise TypeError, "invalid element"
550
+ return c_node
551
+
552
+ cdef xmlNode* _nonRoNodeOf(element) except NULL:
553
+ cdef xmlNode* c_node
554
+ if isinstance(element, _Element):
555
+ c_node = (<_Element>element)._c_node
556
+ elif isinstance(element, _AppendOnlyElementProxy):
557
+ c_node = (<_AppendOnlyElementProxy>element)._c_node
558
+ elif isinstance(element, _OpaqueNodeWrapper):
559
+ c_node = (<_OpaqueNodeWrapper>element)._c_node
560
+ else:
561
+ raise TypeError, f"invalid argument type {type(element)}"
562
+
563
+ if c_node is NULL:
564
+ raise TypeError, "invalid element"
565
+ return c_node
.venv/lib/python3.12/site-packages/lxml/relaxng.pxi ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # support for RelaxNG validation
2
+ from lxml.includes cimport relaxng
3
+
4
+ cdef object _rnc2rng
5
+ try:
6
+ import rnc2rng as _rnc2rng
7
+ except ImportError:
8
+ _rnc2rng = None
9
+
10
+
11
+ cdef int _require_rnc2rng() except -1:
12
+ if _rnc2rng is None:
13
+ raise RelaxNGParseError(
14
+ 'compact syntax not supported (please install rnc2rng)')
15
+ return 0
16
+
17
+
18
+ cdef class RelaxNGError(LxmlError):
19
+ """Base class for RelaxNG errors.
20
+ """
21
+
22
+ cdef class RelaxNGParseError(RelaxNGError):
23
+ """Error while parsing an XML document as RelaxNG.
24
+ """
25
+
26
+ cdef class RelaxNGValidateError(RelaxNGError):
27
+ """Error while validating an XML document with a RelaxNG schema.
28
+ """
29
+
30
+
31
+ ################################################################################
32
+ # RelaxNG
33
+
34
+ cdef class RelaxNG(_Validator):
35
+ """RelaxNG(self, etree=None, file=None)
36
+ Turn a document into a Relax NG validator.
37
+
38
+ Either pass a schema as Element or ElementTree, or pass a file or
39
+ filename through the ``file`` keyword argument.
40
+ """
41
+ cdef relaxng.xmlRelaxNG* _c_schema
42
+ def __cinit__(self):
43
+ self._c_schema = NULL
44
+
45
+ def __init__(self, etree=None, *, file=None):
46
+ cdef _Document doc
47
+ cdef _Element root_node
48
+ cdef xmlDoc* fake_c_doc = NULL
49
+ cdef relaxng.xmlRelaxNGParserCtxt* parser_ctxt = NULL
50
+ _Validator.__init__(self)
51
+ if etree is not None:
52
+ doc = _documentOrRaise(etree)
53
+ root_node = _rootNodeOrRaise(etree)
54
+ fake_c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
55
+ parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(fake_c_doc)
56
+ elif file is not None:
57
+ if _isString(file):
58
+ if file[-4:].lower() == '.rnc':
59
+ _require_rnc2rng()
60
+ rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file)))
61
+ doc = _parseMemoryDocument(rng_data_utf8, parser=None, url=file)
62
+ parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
63
+ else:
64
+ doc = None
65
+ filename = _encodeFilename(file)
66
+ with self._error_log:
67
+ orig_loader = _register_document_loader()
68
+ parser_ctxt = relaxng.xmlRelaxNGNewParserCtxt(_cstr(filename))
69
+ _reset_document_loader(orig_loader)
70
+ elif (_getFilenameForFile(file) or '')[-4:].lower() == '.rnc':
71
+ _require_rnc2rng()
72
+ rng_data_utf8 = _utf8(_rnc2rng.dumps(_rnc2rng.load(file)))
73
+ doc = _parseMemoryDocument(
74
+ rng_data_utf8, parser=None, url=_getFilenameForFile(file))
75
+ parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
76
+ else:
77
+ doc = _parseDocument(file, parser=None, base_url=None)
78
+ parser_ctxt = relaxng.xmlRelaxNGNewDocParserCtxt(doc._c_doc)
79
+ else:
80
+ raise RelaxNGParseError, "No tree or file given"
81
+
82
+ if parser_ctxt is NULL:
83
+ if fake_c_doc is not NULL:
84
+ _destroyFakeDoc(doc._c_doc, fake_c_doc)
85
+ raise RelaxNGParseError(
86
+ self._error_log._buildExceptionMessage(
87
+ "Document is not parsable as Relax NG"),
88
+ self._error_log)
89
+
90
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
91
+ relaxng.xmlRelaxNGSetParserStructuredErrors(
92
+ parser_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
93
+ _connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGP)
94
+ self._c_schema = relaxng.xmlRelaxNGParse(parser_ctxt)
95
+ _connectGenericErrorLog(None)
96
+
97
+ relaxng.xmlRelaxNGFreeParserCtxt(parser_ctxt)
98
+ if self._c_schema is NULL:
99
+ if fake_c_doc is not NULL:
100
+ _destroyFakeDoc(doc._c_doc, fake_c_doc)
101
+ raise RelaxNGParseError(
102
+ self._error_log._buildExceptionMessage(
103
+ "Document is not valid Relax NG"),
104
+ self._error_log)
105
+ if fake_c_doc is not NULL:
106
+ _destroyFakeDoc(doc._c_doc, fake_c_doc)
107
+
108
+ def __dealloc__(self):
109
+ relaxng.xmlRelaxNGFree(self._c_schema)
110
+
111
+ def __call__(self, etree):
112
+ """__call__(self, etree)
113
+
114
+ Validate doc using Relax NG.
115
+
116
+ Returns true if document is valid, false if not."""
117
+ cdef _Document doc
118
+ cdef _Element root_node
119
+ cdef xmlDoc* c_doc
120
+ cdef relaxng.xmlRelaxNGValidCtxt* valid_ctxt
121
+ cdef int ret
122
+
123
+ assert self._c_schema is not NULL, "RelaxNG instance not initialised"
124
+ doc = _documentOrRaise(etree)
125
+ root_node = _rootNodeOrRaise(etree)
126
+
127
+ valid_ctxt = relaxng.xmlRelaxNGNewValidCtxt(self._c_schema)
128
+ if valid_ctxt is NULL:
129
+ raise MemoryError()
130
+
131
+ try:
132
+ self._error_log.clear()
133
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
134
+ relaxng.xmlRelaxNGSetValidStructuredErrors(
135
+ valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
136
+ _connectGenericErrorLog(self._error_log, xmlerror.XML_FROM_RELAXNGV)
137
+ c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
138
+ with nogil:
139
+ ret = relaxng.xmlRelaxNGValidateDoc(valid_ctxt, c_doc)
140
+ _destroyFakeDoc(doc._c_doc, c_doc)
141
+ finally:
142
+ _connectGenericErrorLog(None)
143
+ relaxng.xmlRelaxNGFreeValidCtxt(valid_ctxt)
144
+
145
+ if ret == -1:
146
+ raise RelaxNGValidateError(
147
+ "Internal error in Relax NG validation",
148
+ self._error_log)
149
+ if ret == 0:
150
+ return True
151
+ else:
152
+ return False
153
+
154
+ @classmethod
155
+ def from_rnc_string(cls, src, base_url=None):
156
+ """Parse a RelaxNG schema in compact syntax from a text string
157
+
158
+ Requires the rnc2rng package to be installed.
159
+
160
+ Passing the source URL or file path of the source as 'base_url'
161
+ will enable resolving resource references relative to the source.
162
+ """
163
+ _require_rnc2rng()
164
+ rng_str = utf8(_rnc2rng.dumps(_rnc2rng.loads(src)))
165
+ return cls(_parseMemoryDocument(rng_str, parser=None, url=base_url))
.venv/lib/python3.12/site-packages/lxml/sax.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8140b87f112d80cc7c60f13d45e74f80fc955e1a0ec40045226fc6fb67d91523
3
+ size 186296
.venv/lib/python3.12/site-packages/lxml/sax.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SAX-based adapter to copy trees from/to the Python standard library.
3
+
4
+ Use the `ElementTreeContentHandler` class to build an ElementTree from
5
+ SAX events.
6
+
7
+ Use the `ElementTreeProducer` class or the `saxify()` function to fire
8
+ the SAX events of an ElementTree against a SAX ContentHandler.
9
+
10
+ See https://lxml.de/sax.html
11
+ """
12
+
13
+
14
+ from xml.sax.handler import ContentHandler
15
+ from lxml import etree
16
+ from lxml.etree import ElementTree, SubElement
17
+ from lxml.etree import Comment, ProcessingInstruction
18
+
19
+ try:
20
+ from types import GenericAlias as _GenericAlias
21
+ except ImportError:
22
+ # Python 3.8 - we only need this as return value from "__class_getitem__"
23
+ def _GenericAlias(cls, item):
24
+ return f"{cls.__name__}[{item.__name__}]"
25
+
26
+
27
+ class SaxError(etree.LxmlError):
28
+ """General SAX error.
29
+ """
30
+
31
+
32
+ def _getNsTag(tag):
33
+ if tag[0] == '{' and '}' in tag:
34
+ return tuple(tag[1:].split('}', 1))
35
+ else:
36
+ return None, tag
37
+
38
+
39
+ class ElementTreeContentHandler(ContentHandler):
40
+ """Build an lxml ElementTree from SAX events.
41
+ """
42
+ def __init__(self, makeelement=None):
43
+ ContentHandler.__init__(self)
44
+ self._root = None
45
+ self._root_siblings = []
46
+ self._element_stack = []
47
+ self._default_ns = None
48
+ self._ns_mapping = { None : [None] }
49
+ self._new_mappings = {}
50
+ if makeelement is None:
51
+ makeelement = etree.Element
52
+ self._makeelement = makeelement
53
+
54
+ def _get_etree(self):
55
+ "Contains the generated ElementTree after parsing is finished."
56
+ return ElementTree(self._root)
57
+
58
+ etree = property(_get_etree, doc=_get_etree.__doc__)
59
+
60
+ def setDocumentLocator(self, locator):
61
+ pass
62
+
63
+ def startDocument(self):
64
+ pass
65
+
66
+ def endDocument(self):
67
+ pass
68
+
69
+ def startPrefixMapping(self, prefix, uri):
70
+ self._new_mappings[prefix] = uri
71
+ try:
72
+ self._ns_mapping[prefix].append(uri)
73
+ except KeyError:
74
+ self._ns_mapping[prefix] = [uri]
75
+ if prefix is None:
76
+ self._default_ns = uri
77
+
78
+ def endPrefixMapping(self, prefix):
79
+ ns_uri_list = self._ns_mapping[prefix]
80
+ ns_uri_list.pop()
81
+ if prefix is None:
82
+ self._default_ns = ns_uri_list[-1]
83
+
84
+ def _buildTag(self, ns_name_tuple):
85
+ ns_uri, local_name = ns_name_tuple
86
+ if ns_uri:
87
+ el_tag = "{%s}%s" % ns_name_tuple
88
+ elif self._default_ns:
89
+ el_tag = "{%s}%s" % (self._default_ns, local_name)
90
+ else:
91
+ el_tag = local_name
92
+ return el_tag
93
+
94
+ def startElementNS(self, ns_name, qname, attributes=None):
95
+ el_name = self._buildTag(ns_name)
96
+ if attributes:
97
+ attrs = {}
98
+ try:
99
+ iter_attributes = attributes.iteritems()
100
+ except AttributeError:
101
+ iter_attributes = attributes.items()
102
+
103
+ for name_tuple, value in iter_attributes:
104
+ if name_tuple[0]:
105
+ attr_name = "{%s}%s" % name_tuple
106
+ else:
107
+ attr_name = name_tuple[1]
108
+ attrs[attr_name] = value
109
+ else:
110
+ attrs = None
111
+
112
+ element_stack = self._element_stack
113
+ if self._root is None:
114
+ element = self._root = \
115
+ self._makeelement(el_name, attrs, self._new_mappings)
116
+ if self._root_siblings and hasattr(element, 'addprevious'):
117
+ for sibling in self._root_siblings:
118
+ element.addprevious(sibling)
119
+ del self._root_siblings[:]
120
+ else:
121
+ element = SubElement(element_stack[-1], el_name,
122
+ attrs, self._new_mappings)
123
+ element_stack.append(element)
124
+
125
+ self._new_mappings.clear()
126
+
127
+ def processingInstruction(self, target, data):
128
+ pi = ProcessingInstruction(target, data)
129
+ if self._root is None:
130
+ self._root_siblings.append(pi)
131
+ else:
132
+ self._element_stack[-1].append(pi)
133
+
134
+ def endElementNS(self, ns_name, qname):
135
+ element = self._element_stack.pop()
136
+ el_tag = self._buildTag(ns_name)
137
+ if el_tag != element.tag:
138
+ raise SaxError("Unexpected element closed: " + el_tag)
139
+
140
+ def startElement(self, name, attributes=None):
141
+ if attributes:
142
+ attributes = {(None, k): v for k, v in attributes.items()}
143
+ self.startElementNS((None, name), name, attributes)
144
+
145
+ def endElement(self, name):
146
+ self.endElementNS((None, name), name)
147
+
148
+ def characters(self, data):
149
+ last_element = self._element_stack[-1]
150
+ try:
151
+ # if there already is a child element, we must append to its tail
152
+ last_element = last_element[-1]
153
+ except IndexError:
154
+ # otherwise: append to the text
155
+ last_element.text = (last_element.text or '') + data
156
+ else:
157
+ last_element.tail = (last_element.tail or '') + data
158
+
159
+ ignorableWhitespace = characters
160
+
161
+ # Allow subscripting sax.ElementTreeContentHandler in type annotations (PEP 560)
162
+ def __class_getitem__(cls, item):
163
+ return _GenericAlias(cls, item)
164
+
165
+
166
+ class ElementTreeProducer:
167
+ """Produces SAX events for an element and children.
168
+ """
169
+ def __init__(self, element_or_tree, content_handler):
170
+ try:
171
+ element = element_or_tree.getroot()
172
+ except AttributeError:
173
+ element = element_or_tree
174
+ self._element = element
175
+ self._content_handler = content_handler
176
+ from xml.sax.xmlreader import AttributesNSImpl as attr_class
177
+ self._attr_class = attr_class
178
+ self._empty_attributes = attr_class({}, {})
179
+
180
+ def saxify(self):
181
+ self._content_handler.startDocument()
182
+
183
+ element = self._element
184
+ if hasattr(element, 'getprevious'):
185
+ siblings = []
186
+ sibling = element.getprevious()
187
+ while getattr(sibling, 'tag', None) is ProcessingInstruction:
188
+ siblings.append(sibling)
189
+ sibling = sibling.getprevious()
190
+ for sibling in siblings[::-1]:
191
+ self._recursive_saxify(sibling, {})
192
+
193
+ self._recursive_saxify(element, {})
194
+
195
+ if hasattr(element, 'getnext'):
196
+ sibling = element.getnext()
197
+ while getattr(sibling, 'tag', None) is ProcessingInstruction:
198
+ self._recursive_saxify(sibling, {})
199
+ sibling = sibling.getnext()
200
+
201
+ self._content_handler.endDocument()
202
+
203
+ def _recursive_saxify(self, element, parent_nsmap):
204
+ content_handler = self._content_handler
205
+ tag = element.tag
206
+ if tag is Comment or tag is ProcessingInstruction:
207
+ if tag is ProcessingInstruction:
208
+ content_handler.processingInstruction(
209
+ element.target, element.text)
210
+ tail = element.tail
211
+ if tail:
212
+ content_handler.characters(tail)
213
+ return
214
+
215
+ element_nsmap = element.nsmap
216
+ new_prefixes = []
217
+ if element_nsmap != parent_nsmap:
218
+ # There have been updates to the namespace
219
+ for prefix, ns_uri in element_nsmap.items():
220
+ if parent_nsmap.get(prefix) != ns_uri:
221
+ new_prefixes.append( (prefix, ns_uri) )
222
+
223
+ attribs = element.items()
224
+ if attribs:
225
+ attr_values = {}
226
+ attr_qnames = {}
227
+ for attr_ns_name, value in attribs:
228
+ attr_ns_tuple = _getNsTag(attr_ns_name)
229
+ attr_values[attr_ns_tuple] = value
230
+ attr_qnames[attr_ns_tuple] = self._build_qname(
231
+ attr_ns_tuple[0], attr_ns_tuple[1], element_nsmap,
232
+ preferred_prefix=None, is_attribute=True)
233
+ sax_attributes = self._attr_class(attr_values, attr_qnames)
234
+ else:
235
+ sax_attributes = self._empty_attributes
236
+
237
+ ns_uri, local_name = _getNsTag(tag)
238
+ qname = self._build_qname(
239
+ ns_uri, local_name, element_nsmap, element.prefix, is_attribute=False)
240
+
241
+ for prefix, uri in new_prefixes:
242
+ content_handler.startPrefixMapping(prefix, uri)
243
+ content_handler.startElementNS(
244
+ (ns_uri, local_name), qname, sax_attributes)
245
+ text = element.text
246
+ if text:
247
+ content_handler.characters(text)
248
+ for child in element:
249
+ self._recursive_saxify(child, element_nsmap)
250
+ content_handler.endElementNS((ns_uri, local_name), qname)
251
+ for prefix, uri in new_prefixes:
252
+ content_handler.endPrefixMapping(prefix)
253
+ tail = element.tail
254
+ if tail:
255
+ content_handler.characters(tail)
256
+
257
+ def _build_qname(self, ns_uri, local_name, nsmap, preferred_prefix, is_attribute):
258
+ if ns_uri is None:
259
+ return local_name
260
+
261
+ if not is_attribute and nsmap.get(preferred_prefix) == ns_uri:
262
+ prefix = preferred_prefix
263
+ else:
264
+ # Pick the first matching prefix, in alphabetical order.
265
+ candidates = [
266
+ pfx for (pfx, uri) in nsmap.items()
267
+ if pfx is not None and uri == ns_uri
268
+ ]
269
+ prefix = (
270
+ candidates[0] if len(candidates) == 1
271
+ else min(candidates) if candidates
272
+ else None
273
+ )
274
+
275
+ if prefix is None:
276
+ # Default namespace
277
+ return local_name
278
+ return prefix + ':' + local_name
279
+
280
+
281
+ def saxify(element_or_tree, content_handler):
282
+ """One-shot helper to generate SAX events from an XML tree and fire
283
+ them against a SAX ContentHandler.
284
+ """
285
+ return ElementTreeProducer(element_or_tree, content_handler).saxify()
.venv/lib/python3.12/site-packages/lxml/saxparser.pxi ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SAX-like interfaces
2
+
3
+ class XMLSyntaxAssertionError(XMLSyntaxError, AssertionError):
4
+ """
5
+ An XMLSyntaxError that additionally inherits from AssertionError for
6
+ ElementTree / backwards compatibility reasons.
7
+
8
+ This class may get replaced by a plain XMLSyntaxError in a future version.
9
+ """
10
+ def __init__(self, message):
11
+ XMLSyntaxError.__init__(self, message, None, 0, 1)
12
+
13
+
14
+ ctypedef enum _SaxParserEvents:
15
+ SAX_EVENT_START = 1 << 0
16
+ SAX_EVENT_END = 1 << 1
17
+ SAX_EVENT_DATA = 1 << 2
18
+ SAX_EVENT_DOCTYPE = 1 << 3
19
+ SAX_EVENT_PI = 1 << 4
20
+ SAX_EVENT_COMMENT = 1 << 5
21
+ SAX_EVENT_START_NS = 1 << 6
22
+ SAX_EVENT_END_NS = 1 << 7
23
+
24
+ ctypedef enum _ParseEventFilter:
25
+ PARSE_EVENT_FILTER_START = 1 << 0
26
+ PARSE_EVENT_FILTER_END = 1 << 1
27
+ PARSE_EVENT_FILTER_START_NS = 1 << 2
28
+ PARSE_EVENT_FILTER_END_NS = 1 << 3
29
+ PARSE_EVENT_FILTER_COMMENT = 1 << 4
30
+ PARSE_EVENT_FILTER_PI = 1 << 5
31
+
32
+
33
+ cdef int _buildParseEventFilter(events) except -1:
34
+ cdef int event_filter = 0
35
+ for event in events:
36
+ if event == 'start':
37
+ event_filter |= PARSE_EVENT_FILTER_START
38
+ elif event == 'end':
39
+ event_filter |= PARSE_EVENT_FILTER_END
40
+ elif event == 'start-ns':
41
+ event_filter |= PARSE_EVENT_FILTER_START_NS
42
+ elif event == 'end-ns':
43
+ event_filter |= PARSE_EVENT_FILTER_END_NS
44
+ elif event == 'comment':
45
+ event_filter |= PARSE_EVENT_FILTER_COMMENT
46
+ elif event == 'pi':
47
+ event_filter |= PARSE_EVENT_FILTER_PI
48
+ else:
49
+ raise ValueError, f"invalid event name '{event}'"
50
+ return event_filter
51
+
52
+
53
+ cdef class _SaxParserTarget:
54
+ cdef int _sax_event_filter
55
+
56
+ cdef _handleSaxStart(self, tag, attrib, nsmap):
57
+ return None
58
+ cdef _handleSaxEnd(self, tag):
59
+ return None
60
+ cdef int _handleSaxData(self, data) except -1:
61
+ return 0
62
+ cdef int _handleSaxDoctype(self, root_tag, public_id, system_id) except -1:
63
+ return 0
64
+ cdef _handleSaxPi(self, target, data):
65
+ return None
66
+ cdef _handleSaxComment(self, comment):
67
+ return None
68
+ cdef _handleSaxStartNs(self, prefix, uri):
69
+ return None
70
+ cdef _handleSaxEndNs(self, prefix):
71
+ return None
72
+
73
+
74
+ #@cython.final
75
+ @cython.internal
76
+ @cython.no_gc_clear # Required because parent class uses it - Cython bug.
77
+ cdef class _SaxParserContext(_ParserContext):
78
+ """This class maps SAX2 events to parser target events.
79
+ """
80
+ cdef _SaxParserTarget _target
81
+ cdef _BaseParser _parser
82
+ cdef xmlparser.startElementNsSAX2Func _origSaxStart
83
+ cdef xmlparser.endElementNsSAX2Func _origSaxEnd
84
+ cdef xmlparser.startElementSAXFunc _origSaxStartNoNs
85
+ cdef xmlparser.endElementSAXFunc _origSaxEndNoNs
86
+ cdef xmlparser.charactersSAXFunc _origSaxData
87
+ cdef xmlparser.cdataBlockSAXFunc _origSaxCData
88
+ cdef xmlparser.internalSubsetSAXFunc _origSaxDoctype
89
+ cdef xmlparser.commentSAXFunc _origSaxComment
90
+ cdef xmlparser.processingInstructionSAXFunc _origSaxPI
91
+ cdef xmlparser.startDocumentSAXFunc _origSaxStartDocument
92
+
93
+ # for event collecting
94
+ cdef int _event_filter
95
+ cdef list _ns_stack
96
+ cdef list _node_stack
97
+ cdef _ParseEventsIterator events_iterator
98
+
99
+ # for iterparse
100
+ cdef _Element _root
101
+ cdef _MultiTagMatcher _matcher
102
+
103
+ def __cinit__(self, _BaseParser parser):
104
+ self._ns_stack = []
105
+ self._node_stack = []
106
+ self._parser = parser
107
+ self.events_iterator = _ParseEventsIterator()
108
+
109
+ cdef void _setSaxParserTarget(self, _SaxParserTarget target) noexcept:
110
+ self._target = target
111
+
112
+ cdef void _initParserContext(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
113
+ _ParserContext._initParserContext(self, c_ctxt)
114
+ if self._target is not None:
115
+ self._connectTarget(c_ctxt)
116
+ elif self._event_filter:
117
+ self._connectEvents(c_ctxt)
118
+
119
+ cdef void _connectTarget(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
120
+ """Wrap original SAX2 callbacks to call into parser target.
121
+ """
122
+ sax = c_ctxt.sax
123
+ self._origSaxStart = sax.startElementNs = NULL
124
+ self._origSaxStartNoNs = sax.startElement = NULL
125
+ if self._target._sax_event_filter & (SAX_EVENT_START |
126
+ SAX_EVENT_START_NS |
127
+ SAX_EVENT_END_NS):
128
+ # intercept => overwrite orig callback
129
+ # FIXME: also intercept on when collecting END events
130
+ if sax.initialized == xmlparser.XML_SAX2_MAGIC:
131
+ sax.startElementNs = _handleSaxTargetStart
132
+ if self._target._sax_event_filter & SAX_EVENT_START:
133
+ sax.startElement = _handleSaxTargetStartNoNs
134
+
135
+ self._origSaxEnd = sax.endElementNs = NULL
136
+ self._origSaxEndNoNs = sax.endElement = NULL
137
+ if self._target._sax_event_filter & (SAX_EVENT_END |
138
+ SAX_EVENT_END_NS):
139
+ if sax.initialized == xmlparser.XML_SAX2_MAGIC:
140
+ sax.endElementNs = _handleSaxEnd
141
+ if self._target._sax_event_filter & SAX_EVENT_END:
142
+ sax.endElement = _handleSaxEndNoNs
143
+
144
+ self._origSaxData = sax.characters = sax.cdataBlock = NULL
145
+ if self._target._sax_event_filter & SAX_EVENT_DATA:
146
+ sax.characters = sax.cdataBlock = _handleSaxData
147
+
148
+ # doctype propagation is always required for entity replacement
149
+ self._origSaxDoctype = sax.internalSubset
150
+ if self._target._sax_event_filter & SAX_EVENT_DOCTYPE:
151
+ sax.internalSubset = _handleSaxTargetDoctype
152
+
153
+ self._origSaxPI = sax.processingInstruction = NULL
154
+ if self._target._sax_event_filter & SAX_EVENT_PI:
155
+ sax.processingInstruction = _handleSaxTargetPI
156
+
157
+ self._origSaxComment = sax.comment = NULL
158
+ if self._target._sax_event_filter & SAX_EVENT_COMMENT:
159
+ sax.comment = _handleSaxTargetComment
160
+
161
+ # enforce entity replacement
162
+ sax.reference = NULL
163
+ c_ctxt.replaceEntities = 1
164
+
165
+ cdef void _connectEvents(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
166
+ """Wrap original SAX2 callbacks to collect parse events without parser target.
167
+ """
168
+ sax = c_ctxt.sax
169
+ self._origSaxStartDocument = sax.startDocument
170
+ sax.startDocument = _handleSaxStartDocument
171
+
172
+ # only override "start" event handler if needed
173
+ self._origSaxStart = sax.startElementNs
174
+ if self._event_filter == 0 or c_ctxt.html or \
175
+ self._event_filter & (PARSE_EVENT_FILTER_START |
176
+ PARSE_EVENT_FILTER_END |
177
+ PARSE_EVENT_FILTER_START_NS |
178
+ PARSE_EVENT_FILTER_END_NS):
179
+ sax.startElementNs = <xmlparser.startElementNsSAX2Func>_handleSaxStart
180
+
181
+ self._origSaxStartNoNs = sax.startElement
182
+ if self._event_filter == 0 or c_ctxt.html or \
183
+ self._event_filter & (PARSE_EVENT_FILTER_START |
184
+ PARSE_EVENT_FILTER_END):
185
+ sax.startElement = <xmlparser.startElementSAXFunc>_handleSaxStartNoNs
186
+
187
+ # only override "end" event handler if needed
188
+ self._origSaxEnd = sax.endElementNs
189
+ if self._event_filter == 0 or \
190
+ self._event_filter & (PARSE_EVENT_FILTER_END |
191
+ PARSE_EVENT_FILTER_END_NS):
192
+ sax.endElementNs = <xmlparser.endElementNsSAX2Func>_handleSaxEnd
193
+
194
+ self._origSaxEndNoNs = sax.endElement
195
+ if self._event_filter == 0 or \
196
+ self._event_filter & PARSE_EVENT_FILTER_END:
197
+ sax.endElement = <xmlparser.endElementSAXFunc>_handleSaxEndNoNs
198
+
199
+ self._origSaxComment = sax.comment
200
+ if self._event_filter & PARSE_EVENT_FILTER_COMMENT:
201
+ sax.comment = <xmlparser.commentSAXFunc>_handleSaxComment
202
+
203
+ self._origSaxPI = sax.processingInstruction
204
+ if self._event_filter & PARSE_EVENT_FILTER_PI:
205
+ sax.processingInstruction = <xmlparser.processingInstructionSAXFunc>_handleSaxPIEvent
206
+
207
+ cdef _setEventFilter(self, events, tag):
208
+ self._event_filter = _buildParseEventFilter(events)
209
+ if not self._event_filter or tag is None or tag == '*':
210
+ self._matcher = None
211
+ else:
212
+ self._matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag)
213
+
214
+ cdef int startDocument(self, xmlDoc* c_doc) except -1:
215
+ try:
216
+ self._doc = _documentFactory(c_doc, self._parser)
217
+ finally:
218
+ self._parser = None # clear circular reference ASAP
219
+ if self._matcher is not None:
220
+ self._matcher.cacheTags(self._doc, force_into_dict=True)
221
+ return 0
222
+
223
+ cdef int pushEvent(self, event, xmlNode* c_node) except -1:
224
+ cdef _Element root
225
+ if self._root is None:
226
+ root = self._doc.getroot()
227
+ if root is not None and root._c_node.type == tree.XML_ELEMENT_NODE:
228
+ self._root = root
229
+ node = _elementFactory(self._doc, c_node)
230
+ self.events_iterator._events.append( (event, node) )
231
+ return 0
232
+
233
+ cdef int flushEvents(self) except -1:
234
+ events = self.events_iterator._events
235
+ while self._node_stack:
236
+ events.append( ('end', self._node_stack.pop()) )
237
+ _pushSaxNsEndEvents(self)
238
+ while self._ns_stack:
239
+ _pushSaxNsEndEvents(self)
240
+
241
+ cdef void _handleSaxException(self, xmlparser.xmlParserCtxt* c_ctxt) noexcept:
242
+ if c_ctxt.errNo == xmlerror.XML_ERR_OK:
243
+ c_ctxt.errNo = xmlerror.XML_ERR_INTERNAL_ERROR
244
+ # stop parsing immediately
245
+ c_ctxt.wellFormed = 0
246
+ c_ctxt.disableSAX = 1
247
+ c_ctxt.instate = xmlparser.XML_PARSER_EOF
248
+ self._store_raised()
249
+
250
+
251
+ @cython.final
252
+ @cython.internal
253
+ cdef class _ParseEventsIterator:
254
+ """A reusable parse events iterator"""
255
+ cdef list _events
256
+ cdef int _event_index
257
+
258
+ def __cinit__(self):
259
+ self._events = []
260
+ self._event_index = 0
261
+
262
+ def __iter__(self):
263
+ return self
264
+
265
+ def __next__(self):
266
+ cdef int event_index = self._event_index
267
+ events = self._events
268
+ if event_index >= 2**10 or event_index * 2 >= len(events):
269
+ if event_index:
270
+ # clean up from time to time
271
+ del events[:event_index]
272
+ self._event_index = event_index = 0
273
+ if event_index >= len(events):
274
+ raise StopIteration
275
+ item = events[event_index]
276
+ self._event_index = event_index + 1
277
+ return item
278
+
279
+
280
+ cdef list _build_prefix_uri_list(_SaxParserContext context, int c_nb_namespaces,
281
+ const_xmlChar** c_namespaces):
282
+ "Build [(prefix, uri)] list of declared namespaces."
283
+ cdef int i
284
+ namespaces = []
285
+ for i in xrange(c_nb_namespaces):
286
+ namespaces.append((funicodeOrEmpty(c_namespaces[0]), funicode(c_namespaces[1])))
287
+ c_namespaces += 2
288
+ return namespaces
289
+
290
+
291
+ cdef void _handleSaxStart(
292
+ void* ctxt, const_xmlChar* c_localname, const_xmlChar* c_prefix,
293
+ const_xmlChar* c_namespace, int c_nb_namespaces,
294
+ const_xmlChar** c_namespaces,
295
+ int c_nb_attributes, int c_nb_defaulted,
296
+ const_xmlChar** c_attributes) noexcept with gil:
297
+ cdef int i
298
+ cdef size_t c_len
299
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
300
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
301
+ return
302
+ context = <_SaxParserContext>c_ctxt._private
303
+ cdef int event_filter = context._event_filter
304
+ try:
305
+ if (c_nb_namespaces and
306
+ event_filter & (PARSE_EVENT_FILTER_START_NS |
307
+ PARSE_EVENT_FILTER_END_NS)):
308
+ declared_namespaces = _build_prefix_uri_list(
309
+ context, c_nb_namespaces, c_namespaces)
310
+ if event_filter & PARSE_EVENT_FILTER_START_NS:
311
+ for prefix_uri_tuple in declared_namespaces:
312
+ context.events_iterator._events.append(("start-ns", prefix_uri_tuple))
313
+ else:
314
+ declared_namespaces = None
315
+
316
+ context._origSaxStart(c_ctxt, c_localname, c_prefix, c_namespace,
317
+ c_nb_namespaces, c_namespaces, c_nb_attributes,
318
+ c_nb_defaulted, c_attributes)
319
+ if c_ctxt.html:
320
+ _fixHtmlDictNodeNames(c_ctxt.dict, c_ctxt.node)
321
+ # The HTML parser in libxml2 reports the missing opening tags when it finds
322
+ # misplaced ones, but with tag names from C string constants that ignore the
323
+ # parser dict. Thus, we need to intern the name ourselves.
324
+ c_localname = tree.xmlDictLookup(c_ctxt.dict, c_localname, -1)
325
+ if c_localname is NULL:
326
+ raise MemoryError()
327
+
328
+ if event_filter & PARSE_EVENT_FILTER_END_NS:
329
+ context._ns_stack.append(declared_namespaces)
330
+ if event_filter & (PARSE_EVENT_FILTER_END |
331
+ PARSE_EVENT_FILTER_START):
332
+ _pushSaxStartEvent(context, c_ctxt, c_namespace, c_localname, None)
333
+ except:
334
+ context._handleSaxException(c_ctxt)
335
+ finally:
336
+ return # swallow any further exceptions
337
+
338
+
339
+ cdef void _handleSaxTargetStart(
340
+ void* ctxt, const_xmlChar* c_localname, const_xmlChar* c_prefix,
341
+ const_xmlChar* c_namespace, int c_nb_namespaces,
342
+ const_xmlChar** c_namespaces,
343
+ int c_nb_attributes, int c_nb_defaulted,
344
+ const_xmlChar** c_attributes) noexcept with gil:
345
+ cdef int i
346
+ cdef size_t c_len
347
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
348
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
349
+ return
350
+ context = <_SaxParserContext>c_ctxt._private
351
+
352
+ cdef int event_filter = context._event_filter
353
+ cdef int sax_event_filter = context._target._sax_event_filter
354
+ try:
355
+ if c_nb_namespaces:
356
+ declared_namespaces = _build_prefix_uri_list(
357
+ context, c_nb_namespaces, c_namespaces)
358
+
359
+ if event_filter & PARSE_EVENT_FILTER_START_NS:
360
+ for prefix_uri_tuple in declared_namespaces:
361
+ context.events_iterator._events.append(("start-ns", prefix_uri_tuple))
362
+
363
+ if sax_event_filter & SAX_EVENT_START_NS:
364
+ for prefix, uri in declared_namespaces:
365
+ context._target._handleSaxStartNs(prefix, uri)
366
+ else:
367
+ declared_namespaces = None
368
+
369
+ if sax_event_filter & SAX_EVENT_START:
370
+ if c_nb_defaulted > 0:
371
+ # only add default attributes if we asked for them
372
+ if c_ctxt.loadsubset & xmlparser.XML_COMPLETE_ATTRS == 0:
373
+ c_nb_attributes -= c_nb_defaulted
374
+ if c_nb_attributes == 0:
375
+ attrib = IMMUTABLE_EMPTY_MAPPING
376
+ else:
377
+ attrib = {}
378
+ for i in xrange(c_nb_attributes):
379
+ name = _namespacedNameFromNsName(
380
+ c_attributes[2], c_attributes[0])
381
+ if c_attributes[3] is NULL:
382
+ value = ''
383
+ else:
384
+ c_len = c_attributes[4] - c_attributes[3]
385
+ value = c_attributes[3][:c_len].decode('utf8')
386
+ attrib[name] = value
387
+ c_attributes += 5
388
+
389
+ nsmap = dict(declared_namespaces) if c_nb_namespaces else IMMUTABLE_EMPTY_MAPPING
390
+
391
+ element = _callTargetSaxStart(
392
+ context, c_ctxt,
393
+ _namespacedNameFromNsName(c_namespace, c_localname),
394
+ attrib, nsmap)
395
+ else:
396
+ element = None
397
+
398
+ if (event_filter & PARSE_EVENT_FILTER_END_NS or
399
+ sax_event_filter & SAX_EVENT_END_NS):
400
+ context._ns_stack.append(declared_namespaces)
401
+ if event_filter & (PARSE_EVENT_FILTER_END |
402
+ PARSE_EVENT_FILTER_START):
403
+ _pushSaxStartEvent(context, c_ctxt, c_namespace,
404
+ c_localname, element)
405
+ except:
406
+ context._handleSaxException(c_ctxt)
407
+ finally:
408
+ return # swallow any further exceptions
409
+
410
+
411
+ cdef void _handleSaxStartNoNs(void* ctxt, const_xmlChar* c_name,
412
+ const_xmlChar** c_attributes) noexcept with gil:
413
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
414
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
415
+ return
416
+ context = <_SaxParserContext>c_ctxt._private
417
+ try:
418
+ context._origSaxStartNoNs(c_ctxt, c_name, c_attributes)
419
+ if c_ctxt.html:
420
+ _fixHtmlDictNodeNames(c_ctxt.dict, c_ctxt.node)
421
+ # The HTML parser in libxml2 reports the missing opening tags when it finds
422
+ # misplaced ones, but with tag names from C string constants that ignore the
423
+ # parser dict. Thus, we need to intern the name ourselves.
424
+ c_name = tree.xmlDictLookup(c_ctxt.dict, c_name, -1)
425
+ if c_name is NULL:
426
+ raise MemoryError()
427
+ if context._event_filter & (PARSE_EVENT_FILTER_END |
428
+ PARSE_EVENT_FILTER_START):
429
+ _pushSaxStartEvent(context, c_ctxt, NULL, c_name, None)
430
+ except:
431
+ context._handleSaxException(c_ctxt)
432
+ finally:
433
+ return # swallow any further exceptions
434
+
435
+
436
+ cdef void _handleSaxTargetStartNoNs(void* ctxt, const_xmlChar* c_name,
437
+ const_xmlChar** c_attributes) noexcept with gil:
438
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
439
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
440
+ return
441
+ context = <_SaxParserContext>c_ctxt._private
442
+ try:
443
+ if c_attributes is NULL:
444
+ attrib = IMMUTABLE_EMPTY_MAPPING
445
+ else:
446
+ attrib = {}
447
+ while c_attributes[0] is not NULL:
448
+ name = funicode(c_attributes[0])
449
+ attrib[name] = funicodeOrEmpty(c_attributes[1])
450
+ c_attributes += 2
451
+ element = _callTargetSaxStart(
452
+ context, c_ctxt, funicode(c_name),
453
+ attrib, IMMUTABLE_EMPTY_MAPPING)
454
+ if context._event_filter & (PARSE_EVENT_FILTER_END |
455
+ PARSE_EVENT_FILTER_START):
456
+ _pushSaxStartEvent(context, c_ctxt, NULL, c_name, element)
457
+ except:
458
+ context._handleSaxException(c_ctxt)
459
+ finally:
460
+ return # swallow any further exceptions
461
+
462
+
463
+ cdef _callTargetSaxStart(_SaxParserContext context,
464
+ xmlparser.xmlParserCtxt* c_ctxt,
465
+ tag, attrib, nsmap):
466
+ element = context._target._handleSaxStart(tag, attrib, nsmap)
467
+ if element is not None and c_ctxt.input is not NULL:
468
+ if isinstance(element, _Element):
469
+ (<_Element>element)._c_node.line = (
470
+ <unsigned short>c_ctxt.input.line
471
+ if c_ctxt.input.line < 65535 else 65535)
472
+ return element
473
+
474
+
475
+ cdef int _pushSaxStartEvent(_SaxParserContext context,
476
+ xmlparser.xmlParserCtxt* c_ctxt,
477
+ const_xmlChar* c_href,
478
+ const_xmlChar* c_name, node) except -1:
479
+ if (context._matcher is None or
480
+ context._matcher.matchesNsTag(c_href, c_name)):
481
+ if node is None and context._target is None:
482
+ assert context._doc is not None
483
+ node = _elementFactory(context._doc, c_ctxt.node)
484
+ if context._event_filter & PARSE_EVENT_FILTER_START:
485
+ context.events_iterator._events.append(('start', node))
486
+ if (context._target is None and
487
+ context._event_filter & PARSE_EVENT_FILTER_END):
488
+ context._node_stack.append(node)
489
+ return 0
490
+
491
+
492
+ cdef void _handleSaxEnd(void* ctxt, const_xmlChar* c_localname,
493
+ const_xmlChar* c_prefix,
494
+ const_xmlChar* c_namespace) noexcept with gil:
495
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
496
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
497
+ return
498
+ context = <_SaxParserContext>c_ctxt._private
499
+ try:
500
+ if context._target is not None:
501
+ if context._target._sax_event_filter & SAX_EVENT_END:
502
+ node = context._target._handleSaxEnd(
503
+ _namespacedNameFromNsName(c_namespace, c_localname))
504
+ else:
505
+ node = None
506
+ else:
507
+ context._origSaxEnd(c_ctxt, c_localname, c_prefix, c_namespace)
508
+ node = None
509
+ _pushSaxEndEvent(context, c_namespace, c_localname, node)
510
+ _pushSaxNsEndEvents(context)
511
+ except:
512
+ context._handleSaxException(c_ctxt)
513
+ finally:
514
+ return # swallow any further exceptions
515
+
516
+
517
+ cdef void _handleSaxEndNoNs(void* ctxt, const_xmlChar* c_name) noexcept with gil:
518
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
519
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
520
+ return
521
+ context = <_SaxParserContext>c_ctxt._private
522
+ try:
523
+ if context._target is not None:
524
+ node = context._target._handleSaxEnd(funicode(c_name))
525
+ else:
526
+ context._origSaxEndNoNs(c_ctxt, c_name)
527
+ node = None
528
+ _pushSaxEndEvent(context, NULL, c_name, node)
529
+ except:
530
+ context._handleSaxException(c_ctxt)
531
+ finally:
532
+ return # swallow any further exceptions
533
+
534
+
535
+ cdef int _pushSaxNsEndEvents(_SaxParserContext context) except -1:
536
+ cdef bint build_events = context._event_filter & PARSE_EVENT_FILTER_END_NS
537
+ cdef bint call_target = (
538
+ context._target is not None
539
+ and context._target._sax_event_filter & SAX_EVENT_END_NS)
540
+ if not build_events and not call_target:
541
+ return 0
542
+
543
+ cdef list declared_namespaces = context._ns_stack.pop()
544
+ if declared_namespaces is None:
545
+ return 0
546
+
547
+ cdef tuple prefix_uri
548
+ for prefix_uri in reversed(declared_namespaces):
549
+ if call_target:
550
+ context._target._handleSaxEndNs(prefix_uri[0])
551
+ if build_events:
552
+ context.events_iterator._events.append(('end-ns', None))
553
+
554
+ return 0
555
+
556
+
557
+ cdef int _pushSaxEndEvent(_SaxParserContext context,
558
+ const_xmlChar* c_href,
559
+ const_xmlChar* c_name, node) except -1:
560
+ if context._event_filter & PARSE_EVENT_FILTER_END:
561
+ if (context._matcher is None or
562
+ context._matcher.matchesNsTag(c_href, c_name)):
563
+ if context._target is None:
564
+ node = context._node_stack.pop()
565
+ context.events_iterator._events.append(('end', node))
566
+ return 0
567
+
568
+
569
+ cdef void _handleSaxData(void* ctxt, const_xmlChar* c_data, int data_len) noexcept with gil:
570
+ # can only be called if parsing with a target
571
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
572
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
573
+ return
574
+ context = <_SaxParserContext>c_ctxt._private
575
+ try:
576
+ context._target._handleSaxData(
577
+ c_data[:data_len].decode('utf8'))
578
+ except:
579
+ context._handleSaxException(c_ctxt)
580
+ finally:
581
+ return # swallow any further exceptions
582
+
583
+
584
+ cdef void _handleSaxTargetDoctype(void* ctxt, const_xmlChar* c_name,
585
+ const_xmlChar* c_public,
586
+ const_xmlChar* c_system) noexcept with gil:
587
+ # can only be called if parsing with a target
588
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
589
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
590
+ return
591
+ context = <_SaxParserContext>c_ctxt._private
592
+ try:
593
+ context._target._handleSaxDoctype(
594
+ funicodeOrNone(c_name),
595
+ funicodeOrNone(c_public),
596
+ funicodeOrNone(c_system))
597
+ except:
598
+ context._handleSaxException(c_ctxt)
599
+ finally:
600
+ return # swallow any further exceptions
601
+
602
+
603
+ cdef void _handleSaxStartDocument(void* ctxt) noexcept with gil:
604
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
605
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
606
+ return
607
+ context = <_SaxParserContext>c_ctxt._private
608
+ context._origSaxStartDocument(ctxt)
609
+ c_doc = c_ctxt.myDoc
610
+ try:
611
+ context.startDocument(c_doc)
612
+ except:
613
+ context._handleSaxException(c_ctxt)
614
+ finally:
615
+ return # swallow any further exceptions
616
+
617
+
618
+ cdef void _handleSaxTargetPI(void* ctxt, const_xmlChar* c_target,
619
+ const_xmlChar* c_data) noexcept with gil:
620
+ # can only be called if parsing with a target
621
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
622
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
623
+ return
624
+ context = <_SaxParserContext>c_ctxt._private
625
+ try:
626
+ pi = context._target._handleSaxPi(
627
+ funicodeOrNone(c_target),
628
+ funicodeOrEmpty(c_data))
629
+ if context._event_filter & PARSE_EVENT_FILTER_PI:
630
+ context.events_iterator._events.append(('pi', pi))
631
+ except:
632
+ context._handleSaxException(c_ctxt)
633
+ finally:
634
+ return # swallow any further exceptions
635
+
636
+
637
+ cdef void _handleSaxPIEvent(void* ctxt, const_xmlChar* target,
638
+ const_xmlChar* data) noexcept with gil:
639
+ # can only be called when collecting pi events
640
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
641
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
642
+ return
643
+ context = <_SaxParserContext>c_ctxt._private
644
+ context._origSaxPI(ctxt, target, data)
645
+ c_node = _findLastEventNode(c_ctxt)
646
+ if c_node is NULL:
647
+ return
648
+ try:
649
+ context.pushEvent('pi', c_node)
650
+ except:
651
+ context._handleSaxException(c_ctxt)
652
+ finally:
653
+ return # swallow any further exceptions
654
+
655
+
656
+ cdef void _handleSaxTargetComment(void* ctxt, const_xmlChar* c_data) noexcept with gil:
657
+ # can only be called if parsing with a target
658
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
659
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
660
+ return
661
+ context = <_SaxParserContext>c_ctxt._private
662
+ try:
663
+ comment = context._target._handleSaxComment(funicodeOrEmpty(c_data))
664
+ if context._event_filter & PARSE_EVENT_FILTER_COMMENT:
665
+ context.events_iterator._events.append(('comment', comment))
666
+ except:
667
+ context._handleSaxException(c_ctxt)
668
+ finally:
669
+ return # swallow any further exceptions
670
+
671
+
672
+ cdef void _handleSaxComment(void* ctxt, const_xmlChar* text) noexcept with gil:
673
+ # can only be called when collecting comment events
674
+ c_ctxt = <xmlparser.xmlParserCtxt*>ctxt
675
+ if c_ctxt._private is NULL or xmlparser.xmlCtxtIsStopped(c_ctxt):
676
+ return
677
+ context = <_SaxParserContext>c_ctxt._private
678
+ context._origSaxComment(ctxt, text)
679
+ c_node = _findLastEventNode(c_ctxt)
680
+ if c_node is NULL:
681
+ return
682
+ try:
683
+ context.pushEvent('comment', c_node)
684
+ except:
685
+ context._handleSaxException(c_ctxt)
686
+ finally:
687
+ return # swallow any further exceptions
688
+
689
+
690
+ cdef inline xmlNode* _findLastEventNode(xmlparser.xmlParserCtxt* c_ctxt) noexcept:
691
+ # this mimics what libxml2 creates for comments/PIs
692
+ if c_ctxt.inSubset == 1:
693
+ return c_ctxt.myDoc.intSubset.last
694
+ elif c_ctxt.inSubset == 2:
695
+ return c_ctxt.myDoc.extSubset.last
696
+ elif c_ctxt.node is NULL:
697
+ return c_ctxt.myDoc.last
698
+ elif c_ctxt.node.type == tree.XML_ELEMENT_NODE:
699
+ return c_ctxt.node.last
700
+ else:
701
+ return c_ctxt.node.next
702
+
703
+
704
+ ############################################################
705
+ ## ET compatible XML tree builder
706
+ ############################################################
707
+
708
+ cdef class TreeBuilder(_SaxParserTarget):
709
+ """TreeBuilder(self, element_factory=None, parser=None,
710
+ comment_factory=None, pi_factory=None,
711
+ insert_comments=True, insert_pis=True)
712
+
713
+ Parser target that builds a tree from parse event callbacks.
714
+
715
+ The factory arguments can be used to influence the creation of
716
+ elements, comments and processing instructions.
717
+
718
+ By default, comments and processing instructions are inserted into
719
+ the tree, but they can be ignored by passing the respective flags.
720
+
721
+ The final tree is returned by the ``close()`` method.
722
+ """
723
+ cdef _BaseParser _parser
724
+ cdef object _factory
725
+ cdef object _comment_factory
726
+ cdef object _pi_factory
727
+ cdef list _data
728
+ cdef list _element_stack
729
+ cdef object _element_stack_pop
730
+ cdef _Element _last # may be None
731
+ cdef bint _in_tail
732
+ cdef bint _insert_comments
733
+ cdef bint _insert_pis
734
+
735
+ def __init__(self, *, element_factory=None, parser=None,
736
+ comment_factory=None, pi_factory=None,
737
+ bint insert_comments=True, bint insert_pis=True):
738
+ self._sax_event_filter = \
739
+ SAX_EVENT_START | SAX_EVENT_END | SAX_EVENT_DATA | \
740
+ SAX_EVENT_PI | SAX_EVENT_COMMENT
741
+ self._data = [] # data collector
742
+ self._element_stack = [] # element stack
743
+ self._element_stack_pop = self._element_stack.pop
744
+ self._last = None # last element
745
+ self._in_tail = 0 # true if we're after an end tag
746
+ self._factory = element_factory
747
+ self._comment_factory = comment_factory if comment_factory is not None else Comment
748
+ self._pi_factory = pi_factory if pi_factory is not None else ProcessingInstruction
749
+ self._insert_comments = insert_comments
750
+ self._insert_pis = insert_pis
751
+ self._parser = parser
752
+
753
+ @cython.final
754
+ cdef int _flush(self) except -1:
755
+ if self._data:
756
+ if self._last is not None:
757
+ text = "".join(self._data)
758
+ if self._in_tail:
759
+ assert self._last.tail is None, "internal error (tail)"
760
+ self._last.tail = text
761
+ else:
762
+ assert self._last.text is None, "internal error (text)"
763
+ self._last.text = text
764
+ del self._data[:]
765
+ return 0
766
+
767
+ # internal SAX event handlers
768
+
769
+ @cython.final
770
+ cdef _handleSaxStart(self, tag, attrib, nsmap):
771
+ self._flush()
772
+ if self._factory is not None:
773
+ self._last = self._factory(tag, attrib)
774
+ if self._element_stack:
775
+ _appendChild(self._element_stack[-1], self._last)
776
+ elif self._element_stack:
777
+ self._last = _makeSubElement(
778
+ self._element_stack[-1], tag, None, None, attrib, nsmap, None)
779
+ else:
780
+ self._last = _makeElement(
781
+ tag, NULL, None, self._parser, None, None, attrib, nsmap, None)
782
+ self._element_stack.append(self._last)
783
+ self._in_tail = 0
784
+ return self._last
785
+
786
+ @cython.final
787
+ cdef _handleSaxEnd(self, tag):
788
+ self._flush()
789
+ self._last = self._element_stack_pop()
790
+ self._in_tail = 1
791
+ return self._last
792
+
793
+ @cython.final
794
+ cdef int _handleSaxData(self, data) except -1:
795
+ self._data.append(data)
796
+
797
+ @cython.final
798
+ cdef _handleSaxPi(self, target, data):
799
+ elem = self._pi_factory(target, data)
800
+ if self._insert_pis:
801
+ self._flush()
802
+ self._last = elem
803
+ if self._element_stack:
804
+ _appendChild(self._element_stack[-1], self._last)
805
+ self._in_tail = 1
806
+ return self._last
807
+
808
+ @cython.final
809
+ cdef _handleSaxComment(self, comment):
810
+ elem = self._comment_factory(comment)
811
+ if self._insert_comments:
812
+ self._flush()
813
+ self._last = elem
814
+ if self._element_stack:
815
+ _appendChild(self._element_stack[-1], self._last)
816
+ self._in_tail = 1
817
+ return elem
818
+
819
+ # Python level event handlers
820
+
821
+ def close(self):
822
+ """close(self)
823
+
824
+ Flushes the builder buffers, and returns the toplevel document
825
+ element. Raises XMLSyntaxError on inconsistencies.
826
+ """
827
+ if self._element_stack:
828
+ raise XMLSyntaxAssertionError("missing end tags")
829
+ # TODO: this does not necessarily seem like an error case. Why not just return None?
830
+ if self._last is None:
831
+ raise XMLSyntaxAssertionError("missing toplevel element")
832
+ return self._last
833
+
834
+ def data(self, data):
835
+ """data(self, data)
836
+
837
+ Adds text to the current element. The value should be either an
838
+ 8-bit string containing ASCII text, or a Unicode string.
839
+ """
840
+ self._handleSaxData(data)
841
+
842
+ def start(self, tag, attrs, nsmap=None):
843
+ """start(self, tag, attrs, nsmap=None)
844
+
845
+ Opens a new element.
846
+ """
847
+ if nsmap is None:
848
+ nsmap = IMMUTABLE_EMPTY_MAPPING
849
+ return self._handleSaxStart(tag, attrs, nsmap)
850
+
851
+ def end(self, tag):
852
+ """end(self, tag)
853
+
854
+ Closes the current element.
855
+ """
856
+ element = self._handleSaxEnd(tag)
857
+ assert self._last.tag == tag,\
858
+ f"end tag mismatch (expected {self._last.tag}, got {tag})"
859
+ return element
860
+
861
+ def pi(self, target, data=None):
862
+ """pi(self, target, data=None)
863
+
864
+ Creates a processing instruction using the factory, appends it
865
+ (unless disabled) and returns it.
866
+ """
867
+ return self._handleSaxPi(target, data)
868
+
869
+ def comment(self, comment):
870
+ """comment(self, comment)
871
+
872
+ Creates a comment using the factory, appends it (unless disabled)
873
+ and returns it.
874
+ """
875
+ return self._handleSaxComment(comment)
.venv/lib/python3.12/site-packages/lxml/schematron.pxi ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # support for Schematron validation
2
+ from lxml.includes cimport schematron
3
+
4
+
5
+ cdef class SchematronError(LxmlError):
6
+ """Base class of all Schematron errors.
7
+ """
8
+
9
+ cdef class SchematronParseError(SchematronError):
10
+ """Error while parsing an XML document as Schematron schema.
11
+ """
12
+
13
+ cdef class SchematronValidateError(SchematronError):
14
+ """Error while validating an XML document with a Schematron schema.
15
+ """
16
+
17
+
18
+ ################################################################################
19
+ # Schematron
20
+
21
+ cdef class Schematron(_Validator):
22
+ """Schematron(self, etree=None, file=None)
23
+ A Schematron validator.
24
+
25
+ Pass a root Element or an ElementTree to turn it into a validator.
26
+ Alternatively, pass a filename as keyword argument 'file' to parse from
27
+ the file system.
28
+
29
+ Schematron is a less well known, but very powerful schema language. The main
30
+ idea is to use the capabilities of XPath to put restrictions on the structure
31
+ and the content of XML documents. Here is a simple example::
32
+
33
+ >>> schematron = Schematron(XML('''
34
+ ... <schema xmlns="http://www.ascc.net/xml/schematron" >
35
+ ... <pattern name="id is the only permitted attribute name">
36
+ ... <rule context="*">
37
+ ... <report test="@*[not(name()='id')]">Attribute
38
+ ... <name path="@*[not(name()='id')]"/> is forbidden<name/>
39
+ ... </report>
40
+ ... </rule>
41
+ ... </pattern>
42
+ ... </schema>
43
+ ... '''))
44
+
45
+ >>> xml = XML('''
46
+ ... <AAA name="aaa">
47
+ ... <BBB id="bbb"/>
48
+ ... <CCC color="ccc"/>
49
+ ... </AAA>
50
+ ... ''')
51
+
52
+ >>> schematron.validate(xml)
53
+ 0
54
+
55
+ >>> xml = XML('''
56
+ ... <AAA id="aaa">
57
+ ... <BBB id="bbb"/>
58
+ ... <CCC/>
59
+ ... </AAA>
60
+ ... ''')
61
+
62
+ >>> schematron.validate(xml)
63
+ 1
64
+
65
+ Schematron was added to libxml2 in version 2.6.21. Before version 2.6.32,
66
+ however, Schematron lacked support for error reporting other than to stderr.
67
+ This version is therefore required to retrieve validation warnings and
68
+ errors in lxml.
69
+ """
70
+ cdef schematron.xmlSchematron* _c_schema
71
+ cdef xmlDoc* _c_schema_doc
72
+
73
+ def __init__(self, etree=None, *, file=None):
74
+ cdef _Document doc
75
+ cdef _Element root_node
76
+ cdef xmlNode* c_node
77
+ cdef char* c_href
78
+ cdef schematron.xmlSchematronParserCtxt* parser_ctxt = NULL
79
+ _Validator.__init__(self)
80
+ if not config.ENABLE_SCHEMATRON:
81
+ raise SchematronError, \
82
+ "lxml.etree was compiled without Schematron support."
83
+
84
+ import warnings
85
+ warnings.warn(
86
+ "The (non-ISO) Schematron feature is deprecated and will be removed from libxml2 and lxml. "
87
+ "Use 'lxml.isoschematron' instead.",
88
+ DeprecationWarning,
89
+ )
90
+
91
+ if etree is not None:
92
+ doc = _documentOrRaise(etree)
93
+ root_node = _rootNodeOrRaise(etree)
94
+ self._c_schema_doc = _copyDocRoot(doc._c_doc, root_node._c_node)
95
+ parser_ctxt = schematron.xmlSchematronNewDocParserCtxt(self._c_schema_doc)
96
+ elif file is not None:
97
+ filename = _getFilenameForFile(file)
98
+ if filename is None:
99
+ # XXX assume a string object
100
+ filename = file
101
+ filename = _encodeFilename(filename)
102
+ with self._error_log:
103
+ orig_loader = _register_document_loader()
104
+ parser_ctxt = schematron.xmlSchematronNewParserCtxt(_cstr(filename))
105
+ _reset_document_loader(orig_loader)
106
+ else:
107
+ raise SchematronParseError, "No tree or file given"
108
+
109
+ if parser_ctxt is NULL:
110
+ if self._c_schema_doc is not NULL:
111
+ tree.xmlFreeDoc(self._c_schema_doc)
112
+ self._c_schema_doc = NULL
113
+ raise MemoryError()
114
+
115
+ try:
116
+ with self._error_log:
117
+ orig_loader = _register_document_loader()
118
+ self._c_schema = schematron.xmlSchematronParse(parser_ctxt)
119
+ _reset_document_loader(orig_loader)
120
+ finally:
121
+ schematron.xmlSchematronFreeParserCtxt(parser_ctxt)
122
+
123
+ if self._c_schema is NULL:
124
+ raise SchematronParseError(
125
+ "Document is not a valid Schematron schema",
126
+ self._error_log)
127
+
128
+ def __dealloc__(self):
129
+ schematron.xmlSchematronFree(self._c_schema)
130
+ if self._c_schema_doc is not NULL:
131
+ tree.xmlFreeDoc(self._c_schema_doc)
132
+
133
+ def __call__(self, etree):
134
+ """__call__(self, etree)
135
+
136
+ Validate doc using Schematron.
137
+
138
+ Returns true if document is valid, false if not."""
139
+ cdef _Document doc
140
+ cdef _Element root_node
141
+ cdef xmlDoc* c_doc
142
+ cdef schematron.xmlSchematronValidCtxt* valid_ctxt
143
+ cdef int ret
144
+
145
+ assert self._c_schema is not NULL, "Schematron instance not initialised"
146
+ doc = _documentOrRaise(etree)
147
+ root_node = _rootNodeOrRaise(etree)
148
+
149
+ valid_ctxt = schematron.xmlSchematronNewValidCtxt(
150
+ self._c_schema, schematron.XML_SCHEMATRON_OUT_ERROR)
151
+ if valid_ctxt is NULL:
152
+ raise MemoryError()
153
+
154
+ try:
155
+ self._error_log.clear()
156
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
157
+ schematron.xmlSchematronSetValidStructuredErrors(
158
+ valid_ctxt, <xmlerror.xmlStructuredErrorFunc> _receiveError, <void*>self._error_log)
159
+ c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
160
+ with nogil:
161
+ ret = schematron.xmlSchematronValidateDoc(valid_ctxt, c_doc)
162
+ _destroyFakeDoc(doc._c_doc, c_doc)
163
+ finally:
164
+ schematron.xmlSchematronFreeValidCtxt(valid_ctxt)
165
+
166
+ if ret == -1:
167
+ raise SchematronValidateError(
168
+ "Internal error in Schematron validation",
169
+ self._error_log)
170
+ if ret == 0:
171
+ return True
172
+ else:
173
+ return False
.venv/lib/python3.12/site-packages/lxml/serializer.pxi ADDED
@@ -0,0 +1,1849 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # XML serialization and output functions
2
+
3
+ cdef object GzipFile
4
+ from gzip import GzipFile
5
+
6
+
7
+ cdef class SerialisationError(LxmlError):
8
+ """A libxml2 error that occurred during serialisation.
9
+ """
10
+
11
+
12
+ cdef enum _OutputMethods:
13
+ OUTPUT_METHOD_XML
14
+ OUTPUT_METHOD_HTML
15
+ OUTPUT_METHOD_TEXT
16
+
17
+
18
+ cdef int _findOutputMethod(method) except -1:
19
+ if method is None:
20
+ return OUTPUT_METHOD_XML
21
+ method = method.lower()
22
+ if method == "xml":
23
+ return OUTPUT_METHOD_XML
24
+ if method == "html":
25
+ return OUTPUT_METHOD_HTML
26
+ if method == "text":
27
+ return OUTPUT_METHOD_TEXT
28
+ raise ValueError(f"unknown output method {method!r}")
29
+
30
+
31
+ cdef _textToString(xmlNode* c_node, encoding, bint with_tail):
32
+ cdef bint needs_conversion
33
+ cdef const_xmlChar* c_text
34
+ cdef xmlNode* c_text_node
35
+ cdef tree.xmlBuffer* c_buffer
36
+ cdef int error_result
37
+
38
+ c_buffer = tree.xmlBufferCreate()
39
+ if c_buffer is NULL:
40
+ raise MemoryError()
41
+
42
+ with nogil:
43
+ error_result = tree.xmlNodeBufGetContent(c_buffer, c_node)
44
+ if with_tail:
45
+ c_text_node = _textNodeOrSkip(c_node.next)
46
+ while c_text_node is not NULL:
47
+ tree.xmlBufferWriteChar(c_buffer, <const_char*>c_text_node.content)
48
+ c_text_node = _textNodeOrSkip(c_text_node.next)
49
+ c_text = tree.xmlBufferContent(c_buffer)
50
+
51
+ if error_result < 0 or c_text is NULL:
52
+ tree.xmlBufferFree(c_buffer)
53
+ raise SerialisationError, "Error during serialisation (out of memory?)"
54
+
55
+ try:
56
+ needs_conversion = 0
57
+ if encoding is unicode:
58
+ needs_conversion = 1
59
+ elif encoding is not None:
60
+ # Python prefers lower case encoding names
61
+ encoding = encoding.lower()
62
+ if encoding not in ('utf8', 'utf-8'):
63
+ if encoding == 'ascii':
64
+ if isutf8l(c_text, tree.xmlBufferLength(c_buffer)):
65
+ # will raise a decode error below
66
+ needs_conversion = 1
67
+ else:
68
+ needs_conversion = 1
69
+
70
+ if needs_conversion:
71
+ text = (<const_char*>c_text)[:tree.xmlBufferLength(c_buffer)].decode('utf8')
72
+ if encoding is not unicode:
73
+ encoding = _utf8(encoding)
74
+ text = python.PyUnicode_AsEncodedString(
75
+ text, encoding, 'strict')
76
+ else:
77
+ text = (<unsigned char*>c_text)[:tree.xmlBufferLength(c_buffer)]
78
+ finally:
79
+ tree.xmlBufferFree(c_buffer)
80
+ return text
81
+
82
+
83
+ cdef _tostring(_Element element, encoding, doctype, method,
84
+ bint write_xml_declaration, bint write_complete_document,
85
+ bint pretty_print, bint with_tail, int standalone):
86
+ """Serialize an element to an encoded string representation of its XML
87
+ tree.
88
+ """
89
+ cdef tree.xmlOutputBuffer* c_buffer
90
+ cdef tree.xmlBuf* c_result_buffer
91
+ cdef tree.xmlCharEncodingHandler* enchandler
92
+ cdef const_char* c_enc
93
+ cdef const_xmlChar* c_version
94
+ cdef const_xmlChar* c_doctype
95
+ cdef int c_method
96
+ cdef int error_result
97
+ if element is None:
98
+ return None
99
+ _assertValidNode(element)
100
+ c_method = _findOutputMethod(method)
101
+ if c_method == OUTPUT_METHOD_TEXT:
102
+ return _textToString(element._c_node, encoding, with_tail)
103
+ if encoding is None or encoding is unicode:
104
+ c_enc = NULL
105
+ else:
106
+ encoding = _utf8(encoding)
107
+ c_enc = _cstr(encoding)
108
+ if doctype is None:
109
+ c_doctype = NULL
110
+ else:
111
+ doctype = _utf8(doctype)
112
+ c_doctype = _xcstr(doctype)
113
+ # it is necessary to *and* find the encoding handler *and* use
114
+ # encoding during output
115
+ enchandler = tree.xmlFindCharEncodingHandler(c_enc)
116
+ if enchandler is NULL and c_enc is not NULL:
117
+ if encoding is not None:
118
+ encoding = encoding.decode('UTF-8')
119
+ raise LookupError, f"unknown encoding: '{encoding}'"
120
+ c_buffer = tree.xmlAllocOutputBuffer(enchandler)
121
+ if c_buffer is NULL:
122
+ tree.xmlCharEncCloseFunc(enchandler)
123
+ raise MemoryError()
124
+
125
+ with nogil:
126
+ _writeNodeToBuffer(c_buffer, element._c_node, c_enc, c_doctype, c_method,
127
+ write_xml_declaration, write_complete_document,
128
+ pretty_print, with_tail, standalone)
129
+ tree.xmlOutputBufferFlush(c_buffer)
130
+ if c_buffer.conv is not NULL:
131
+ c_result_buffer = c_buffer.conv
132
+ else:
133
+ c_result_buffer = c_buffer.buffer
134
+
135
+ error_result = c_buffer.error
136
+ if error_result != xmlerror.XML_ERR_OK:
137
+ tree.xmlOutputBufferClose(c_buffer)
138
+ _raiseSerialisationError(error_result)
139
+
140
+ try:
141
+ if encoding is unicode:
142
+ result = (<unsigned char*>tree.xmlBufContent(
143
+ c_result_buffer))[:tree.xmlBufUse(c_result_buffer)].decode('UTF-8')
144
+ else:
145
+ result = <bytes>(<unsigned char*>tree.xmlBufContent(
146
+ c_result_buffer))[:tree.xmlBufUse(c_result_buffer)]
147
+ finally:
148
+ error_result = tree.xmlOutputBufferClose(c_buffer)
149
+ if error_result == -1:
150
+ _raiseSerialisationError(error_result)
151
+ return result
152
+
153
+ cdef bytes _tostringC14N(element_or_tree, bint exclusive, bint with_comments, inclusive_ns_prefixes):
154
+ cdef xmlDoc* c_doc
155
+ cdef xmlChar* c_buffer = NULL
156
+ cdef int byte_count = -1
157
+ cdef bytes result
158
+ cdef _Document doc
159
+ cdef _Element element
160
+ cdef xmlChar **c_inclusive_ns_prefixes
161
+
162
+ if isinstance(element_or_tree, _Element):
163
+ _assertValidNode(<_Element>element_or_tree)
164
+ doc = (<_Element>element_or_tree)._doc
165
+ c_doc = _plainFakeRootDoc(doc._c_doc, (<_Element>element_or_tree)._c_node, 0)
166
+ else:
167
+ doc = _documentOrRaise(element_or_tree)
168
+ _assertValidDoc(doc)
169
+ c_doc = doc._c_doc
170
+
171
+ c_inclusive_ns_prefixes = _convert_ns_prefixes(c_doc.dict, inclusive_ns_prefixes) if inclusive_ns_prefixes else NULL
172
+ try:
173
+ with nogil:
174
+ byte_count = c14n.xmlC14NDocDumpMemory(
175
+ c_doc, NULL, exclusive, c_inclusive_ns_prefixes, with_comments, &c_buffer)
176
+
177
+ finally:
178
+ _destroyFakeDoc(doc._c_doc, c_doc)
179
+ if c_inclusive_ns_prefixes is not NULL:
180
+ python.lxml_free(c_inclusive_ns_prefixes)
181
+
182
+ if byte_count < 0 or c_buffer is NULL:
183
+ if c_buffer is not NULL:
184
+ tree.xmlFree(c_buffer)
185
+ raise C14NError, "C14N failed"
186
+ try:
187
+ result = c_buffer[:byte_count]
188
+ finally:
189
+ tree.xmlFree(c_buffer)
190
+ return result
191
+
192
+ cdef _raiseSerialisationError(int error_result):
193
+ if error_result == xmlerror.XML_ERR_NO_MEMORY:
194
+ raise MemoryError()
195
+ message = ErrorTypes._getName(error_result)
196
+ if message is None:
197
+ message = f"unknown error {error_result}"
198
+ raise SerialisationError, message
199
+
200
+ ############################################################
201
+ # low-level serialisation functions
202
+
203
+ cdef void _writeDoctype(tree.xmlOutputBuffer* c_buffer,
204
+ const_xmlChar* c_doctype) noexcept nogil:
205
+ tree.xmlOutputBufferWrite(c_buffer, tree.xmlStrlen(c_doctype),
206
+ <const_char*>c_doctype)
207
+ tree.xmlOutputBufferWriteString(c_buffer, "\n")
208
+
209
+ cdef void _writeNodeToBuffer(tree.xmlOutputBuffer* c_buffer,
210
+ xmlNode* c_node, const_char* encoding, const_xmlChar* c_doctype,
211
+ int c_method, bint write_xml_declaration,
212
+ bint write_complete_document,
213
+ bint pretty_print, bint with_tail,
214
+ int standalone) noexcept nogil:
215
+ cdef xmlNode* c_nsdecl_node
216
+ cdef xmlDoc* c_doc = c_node.doc
217
+ if write_xml_declaration and c_method == OUTPUT_METHOD_XML:
218
+ _writeDeclarationToBuffer(c_buffer, c_doc.version, encoding, standalone)
219
+
220
+ # comments/processing instructions before doctype declaration
221
+ if write_complete_document and not c_buffer.error and c_doc.intSubset:
222
+ _writePrevSiblings(c_buffer, <xmlNode*>c_doc.intSubset, encoding, pretty_print)
223
+
224
+ if c_doctype:
225
+ _writeDoctype(c_buffer, c_doctype)
226
+ # write internal DTD subset, preceding PIs/comments, etc.
227
+ if write_complete_document and not c_buffer.error:
228
+ if c_doctype is NULL:
229
+ _writeDtdToBuffer(c_buffer, c_doc, c_node.name, c_method, encoding)
230
+ _writePrevSiblings(c_buffer, c_node, encoding, pretty_print)
231
+
232
+ c_nsdecl_node = c_node
233
+ if not c_node.parent or c_node.parent.type != tree.XML_DOCUMENT_NODE:
234
+ # copy the node and add namespaces from parents
235
+ # this is required to make libxml write them
236
+ c_nsdecl_node = tree.xmlCopyNode(c_node, 2)
237
+ if not c_nsdecl_node:
238
+ c_buffer.error = xmlerror.XML_ERR_NO_MEMORY
239
+ return
240
+ _copyParentNamespaces(c_node, c_nsdecl_node)
241
+
242
+ c_nsdecl_node.parent = c_node.parent
243
+ c_nsdecl_node.children = c_node.children
244
+ c_nsdecl_node.last = c_node.last
245
+
246
+ # write node
247
+ if c_method == OUTPUT_METHOD_HTML:
248
+ tree.htmlNodeDumpFormatOutput(
249
+ c_buffer, c_doc, c_nsdecl_node, encoding, pretty_print)
250
+ else:
251
+ tree.xmlNodeDumpOutput(
252
+ c_buffer, c_doc, c_nsdecl_node, 0, pretty_print, encoding)
253
+
254
+ if c_nsdecl_node is not c_node:
255
+ # clean up
256
+ c_nsdecl_node.children = c_nsdecl_node.last = NULL
257
+ tree.xmlFreeNode(c_nsdecl_node)
258
+
259
+ if c_buffer.error:
260
+ return
261
+
262
+ # write tail, trailing comments, etc.
263
+ if with_tail:
264
+ _writeTail(c_buffer, c_node, encoding, c_method, pretty_print)
265
+ if write_complete_document:
266
+ _writeNextSiblings(c_buffer, c_node, encoding, pretty_print)
267
+ if pretty_print:
268
+ tree.xmlOutputBufferWrite(c_buffer, 1, "\n")
269
+
270
+ cdef void _writeDeclarationToBuffer(tree.xmlOutputBuffer* c_buffer,
271
+ const_xmlChar* version, const_char* encoding,
272
+ int standalone) noexcept nogil:
273
+ if version is NULL:
274
+ version = <unsigned char*>"1.0"
275
+ tree.xmlOutputBufferWrite(c_buffer, 15, "<?xml version='")
276
+ tree.xmlOutputBufferWriteString(c_buffer, <const_char*>version)
277
+ tree.xmlOutputBufferWrite(c_buffer, 12, "' encoding='")
278
+ tree.xmlOutputBufferWriteString(c_buffer, encoding)
279
+ if standalone == 0:
280
+ tree.xmlOutputBufferWrite(c_buffer, 20, "' standalone='no'?>\n")
281
+ elif standalone == 1:
282
+ tree.xmlOutputBufferWrite(c_buffer, 21, "' standalone='yes'?>\n")
283
+ else:
284
+ tree.xmlOutputBufferWrite(c_buffer, 4, "'?>\n")
285
+
286
+ cdef void _writeDtdToBuffer(tree.xmlOutputBuffer* c_buffer,
287
+ xmlDoc* c_doc, const_xmlChar* c_root_name,
288
+ int c_method, const_char* encoding) noexcept nogil:
289
+ cdef tree.xmlDtd* c_dtd
290
+ cdef xmlNode* c_node
291
+ cdef char* quotechar
292
+ c_dtd = c_doc.intSubset
293
+ if not c_dtd or not c_dtd.name:
294
+ return
295
+
296
+ # Name in document type declaration must match the root element tag.
297
+ # For XML, case sensitive match, for HTML insensitive.
298
+ if c_method == OUTPUT_METHOD_HTML:
299
+ if tree.xmlStrcasecmp(c_root_name, c_dtd.name) != 0:
300
+ return
301
+ else:
302
+ if tree.xmlStrcmp(c_root_name, c_dtd.name) != 0:
303
+ return
304
+
305
+ tree.xmlOutputBufferWrite(c_buffer, 10, "<!DOCTYPE ")
306
+ tree.xmlOutputBufferWriteString(c_buffer, <const_char*>c_dtd.name)
307
+
308
+ cdef const_xmlChar* public_id = c_dtd.ExternalID
309
+ cdef const_xmlChar* sys_url = c_dtd.SystemID
310
+ if public_id and public_id[0] == b'\0':
311
+ public_id = NULL
312
+ if sys_url and sys_url[0] == b'\0':
313
+ sys_url = NULL
314
+
315
+ if public_id:
316
+ tree.xmlOutputBufferWrite(c_buffer, 9, ' PUBLIC "')
317
+ tree.xmlOutputBufferWriteString(c_buffer, <const_char*>public_id)
318
+ if sys_url:
319
+ tree.xmlOutputBufferWrite(c_buffer, 2, '" ')
320
+ else:
321
+ tree.xmlOutputBufferWrite(c_buffer, 1, '"')
322
+ elif sys_url:
323
+ tree.xmlOutputBufferWrite(c_buffer, 8, ' SYSTEM ')
324
+
325
+ if sys_url:
326
+ if tree.xmlStrchr(sys_url, b'"'):
327
+ quotechar = '\''
328
+ else:
329
+ quotechar = '"'
330
+ tree.xmlOutputBufferWrite(c_buffer, 1, quotechar)
331
+ tree.xmlOutputBufferWriteString(c_buffer, <const_char*>sys_url)
332
+ tree.xmlOutputBufferWrite(c_buffer, 1, quotechar)
333
+
334
+ if (not c_dtd.entities and not c_dtd.elements and
335
+ not c_dtd.attributes and not c_dtd.notations and
336
+ not c_dtd.pentities):
337
+ tree.xmlOutputBufferWrite(c_buffer, 2, '>\n')
338
+ return
339
+
340
+ tree.xmlOutputBufferWrite(c_buffer, 3, ' [\n')
341
+ if c_dtd.notations and not c_buffer.error:
342
+ c_buf = tree.xmlBufferCreate()
343
+ if not c_buf:
344
+ c_buffer.error = xmlerror.XML_ERR_NO_MEMORY
345
+ return
346
+ tree.xmlDumpNotationTable(c_buf, <tree.xmlNotationTable*>c_dtd.notations)
347
+ tree.xmlOutputBufferWrite(
348
+ c_buffer, tree.xmlBufferLength(c_buf),
349
+ <const_char*>tree.xmlBufferContent(c_buf))
350
+ tree.xmlBufferFree(c_buf)
351
+ c_node = c_dtd.children
352
+ while c_node and not c_buffer.error:
353
+ tree.xmlNodeDumpOutput(c_buffer, c_node.doc, c_node, 0, 0, encoding)
354
+ c_node = c_node.next
355
+ tree.xmlOutputBufferWrite(c_buffer, 3, "]>\n")
356
+
357
+ cdef void _writeTail(tree.xmlOutputBuffer* c_buffer, xmlNode* c_node,
358
+ const_char* encoding, int c_method, bint pretty_print) noexcept nogil:
359
+ "Write the element tail."
360
+ c_node = c_node.next
361
+ while c_node and not c_buffer.error and c_node.type in (
362
+ tree.XML_TEXT_NODE, tree.XML_CDATA_SECTION_NODE):
363
+ if c_method == OUTPUT_METHOD_HTML:
364
+ tree.htmlNodeDumpFormatOutput(
365
+ c_buffer, c_node.doc, c_node, encoding, pretty_print)
366
+ else:
367
+ tree.xmlNodeDumpOutput(
368
+ c_buffer, c_node.doc, c_node, 0, pretty_print, encoding)
369
+ c_node = c_node.next
370
+
371
+ cdef void _writePrevSiblings(tree.xmlOutputBuffer* c_buffer, xmlNode* c_node,
372
+ const_char* encoding, bint pretty_print) noexcept nogil:
373
+ cdef xmlNode* c_sibling
374
+ if c_node.parent and _isElement(c_node.parent):
375
+ return
376
+ # we are at a root node, so add PI and comment siblings
377
+ c_sibling = c_node
378
+ while c_sibling.prev and \
379
+ (c_sibling.prev.type == tree.XML_PI_NODE or
380
+ c_sibling.prev.type == tree.XML_COMMENT_NODE):
381
+ c_sibling = c_sibling.prev
382
+ while c_sibling is not c_node and not c_buffer.error:
383
+ tree.xmlNodeDumpOutput(c_buffer, c_node.doc, c_sibling, 0,
384
+ pretty_print, encoding)
385
+ if pretty_print:
386
+ tree.xmlOutputBufferWriteString(c_buffer, "\n")
387
+ c_sibling = c_sibling.next
388
+
389
+ cdef void _writeNextSiblings(tree.xmlOutputBuffer* c_buffer, xmlNode* c_node,
390
+ const_char* encoding, bint pretty_print) noexcept nogil:
391
+ cdef xmlNode* c_sibling
392
+ if c_node.parent and _isElement(c_node.parent):
393
+ return
394
+ # we are at a root node, so add PI and comment siblings
395
+ c_sibling = c_node.next
396
+ while not c_buffer.error and c_sibling and \
397
+ (c_sibling.type == tree.XML_PI_NODE or
398
+ c_sibling.type == tree.XML_COMMENT_NODE):
399
+ if pretty_print:
400
+ tree.xmlOutputBufferWriteString(c_buffer, "\n")
401
+ tree.xmlNodeDumpOutput(c_buffer, c_node.doc, c_sibling, 0,
402
+ pretty_print, encoding)
403
+ c_sibling = c_sibling.next
404
+
405
+
406
+ # copied and adapted from libxml2 (xmlBufAttrSerializeTxtContent())
407
+ cdef _write_attr_string(tree.xmlOutputBuffer* buf, const char *string):
408
+ cdef const char *base
409
+ cdef const char *cur
410
+
411
+ if string == NULL:
412
+ return
413
+
414
+ base = cur = <const char*>string
415
+ while cur[0] != 0:
416
+ if cur[0] == b'\n':
417
+ if base != cur:
418
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
419
+
420
+ tree.xmlOutputBufferWrite(buf, 5, "&#10;")
421
+ cur += 1
422
+ base = cur
423
+
424
+ elif cur[0] == b'\r':
425
+ if base != cur:
426
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
427
+
428
+ tree.xmlOutputBufferWrite(buf, 5, "&#13;")
429
+ cur += 1
430
+ base = cur
431
+
432
+ elif cur[0] == b'\t':
433
+ if base != cur:
434
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
435
+
436
+ tree.xmlOutputBufferWrite(buf, 4, "&#9;")
437
+ cur += 1
438
+ base = cur
439
+
440
+ elif cur[0] == b'"':
441
+ if base != cur:
442
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
443
+
444
+ tree.xmlOutputBufferWrite(buf, 6, "&quot;")
445
+ cur += 1
446
+ base = cur
447
+
448
+ elif cur[0] == b'<':
449
+ if base != cur:
450
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
451
+
452
+ tree.xmlOutputBufferWrite(buf, 4, "&lt;")
453
+ cur += 1
454
+ base = cur
455
+
456
+ elif cur[0] == b'>':
457
+ if base != cur:
458
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
459
+
460
+ tree.xmlOutputBufferWrite(buf, 4, "&gt;")
461
+ cur += 1
462
+ base = cur
463
+ elif cur[0] == b'&':
464
+ if base != cur:
465
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
466
+
467
+ tree.xmlOutputBufferWrite(buf, 5, "&amp;")
468
+ cur += 1
469
+ base = cur
470
+
471
+ else:
472
+ # Leave further encoding and escaping to the buffer encoder.
473
+ cur += 1
474
+
475
+ if base != cur:
476
+ tree.xmlOutputBufferWrite(buf, cur - base, base)
477
+
478
+
479
+ cdef void _write_cdata_section(tree.xmlOutputBuffer* buf, const char* c_data, const char* c_end):
480
+ tree.xmlOutputBufferWrite(buf, 9, "<![CDATA[")
481
+ while c_end - c_data > limits.INT_MAX:
482
+ tree.xmlOutputBufferWrite(buf, limits.INT_MAX, c_data)
483
+ c_data += limits.INT_MAX
484
+ tree.xmlOutputBufferWrite(buf, c_end - c_data, c_data)
485
+ tree.xmlOutputBufferWrite(buf, 3, "]]>")
486
+
487
+
488
+ cdef _write_cdata_string(tree.xmlOutputBuffer* buf, bytes bstring):
489
+ cdef const char* c_data = bstring
490
+ cdef const char* c_end = c_data + len(bstring)
491
+ cdef const char* c_pos = c_data
492
+ cdef bint nothing_written = True
493
+
494
+ while True:
495
+ c_pos = <const char*> cstring_h.memchr(c_pos, b']', c_end - c_pos)
496
+ if not c_pos:
497
+ break
498
+ c_pos += 1
499
+ next_char = c_pos[0]
500
+ c_pos += 1
501
+ if next_char != b']':
502
+ continue
503
+ # Found ']]', c_pos points to next character.
504
+ while c_pos[0] == b']':
505
+ c_pos += 1
506
+ if c_pos[0] != b'>':
507
+ if c_pos == c_end:
508
+ break
509
+ # c_pos[0] is neither ']' nor '>', continue with next character.
510
+ c_pos += 1
511
+ continue
512
+
513
+ # Write section up to ']]' and start next block at trailing '>'.
514
+ _write_cdata_section(buf, c_data, c_pos)
515
+ nothing_written = False
516
+ c_data = c_pos
517
+ c_pos += 1
518
+
519
+ if nothing_written or c_data < c_end:
520
+ _write_cdata_section(buf, c_data, c_end)
521
+
522
+
523
+ ############################################################
524
+ # output to file-like objects
525
+
526
+ cdef object io_open
527
+ from io import open as io_open
528
+
529
+ cdef object gzip
530
+ import gzip
531
+
532
+ cdef object getwriter
533
+ from codecs import getwriter
534
+ cdef object utf8_writer = getwriter('utf8')
535
+
536
+ cdef object contextmanager
537
+ from contextlib import contextmanager
538
+
539
+ cdef object _open_utf8_file
540
+
541
+ @contextmanager
542
+ def _open_utf8_file(file, compression=0):
543
+ file = _getFSPathOrObject(file)
544
+ if _isString(file):
545
+ if compression:
546
+ with gzip.GzipFile(file, mode='wb', compresslevel=compression) as zf:
547
+ yield utf8_writer(zf)
548
+ else:
549
+ with io_open(file, 'w', encoding='utf8') as f:
550
+ yield f
551
+ else:
552
+ if compression:
553
+ with gzip.GzipFile(fileobj=file, mode='wb', compresslevel=compression) as zf:
554
+ yield utf8_writer(zf)
555
+ else:
556
+ yield utf8_writer(file)
557
+
558
+
559
+ @cython.final
560
+ @cython.internal
561
+ cdef class _FilelikeWriter:
562
+ cdef object _filelike
563
+ cdef object _close_filelike
564
+ cdef _ExceptionContext _exc_context
565
+ cdef _ErrorLog error_log
566
+
567
+ def __cinit__(self, filelike, exc_context=None, compression=None, close=False):
568
+ if compression is not None and compression > 0:
569
+ filelike = GzipFile(
570
+ fileobj=filelike, mode='wb', compresslevel=compression)
571
+ self._close_filelike = filelike.close
572
+ elif close:
573
+ self._close_filelike = filelike.close
574
+ self._filelike = filelike
575
+ if exc_context is None:
576
+ self._exc_context = _ExceptionContext()
577
+ else:
578
+ self._exc_context = exc_context
579
+ self.error_log = _ErrorLog()
580
+
581
+ cdef tree.xmlOutputBuffer* _createOutputBuffer(
582
+ self, tree.xmlCharEncodingHandler* enchandler) except NULL:
583
+ cdef tree.xmlOutputBuffer* c_buffer
584
+ c_buffer = tree.xmlOutputBufferCreateIO(
585
+ <tree.xmlOutputWriteCallback>_writeFilelikeWriter, _closeFilelikeWriter,
586
+ <python.PyObject*>self, enchandler)
587
+ if c_buffer is NULL:
588
+ raise IOError, "Could not create I/O writer context."
589
+ return c_buffer
590
+
591
+ cdef int write(self, char* c_buffer, int size) noexcept:
592
+ try:
593
+ if self._filelike is None:
594
+ raise IOError, "File is already closed"
595
+ py_buffer = <bytes>c_buffer[:size]
596
+ self._filelike.write(py_buffer)
597
+ except:
598
+ size = -1
599
+ self._exc_context._store_raised()
600
+ finally:
601
+ return size # and swallow any further exceptions
602
+
603
+ cdef int close(self) noexcept:
604
+ retval = 0
605
+ try:
606
+ if self._close_filelike is not None:
607
+ self._close_filelike()
608
+ # we should not close the file here as we didn't open it
609
+ self._filelike = None
610
+ except:
611
+ retval = -1
612
+ self._exc_context._store_raised()
613
+ finally:
614
+ return retval # and swallow any further exceptions
615
+
616
+ cdef int _writeFilelikeWriter(void* ctxt, char* c_buffer, int length) noexcept:
617
+ return (<_FilelikeWriter>ctxt).write(c_buffer, length)
618
+
619
+ cdef int _closeFilelikeWriter(void* ctxt) noexcept:
620
+ return (<_FilelikeWriter>ctxt).close()
621
+
622
+ cdef _tofilelike(f, _Element element, encoding, doctype, method,
623
+ bint write_xml_declaration, bint write_doctype,
624
+ bint pretty_print, bint with_tail, int standalone,
625
+ int compression):
626
+ cdef _FilelikeWriter writer = None
627
+ cdef tree.xmlOutputBuffer* c_buffer
628
+ cdef tree.xmlCharEncodingHandler* enchandler
629
+ cdef const_char* c_enc
630
+ cdef const_xmlChar* c_doctype
631
+ cdef int error_result
632
+
633
+ c_method = _findOutputMethod(method)
634
+ if c_method == OUTPUT_METHOD_TEXT:
635
+ data = _textToString(element._c_node, encoding, with_tail)
636
+ if compression:
637
+ bytes_out = BytesIO()
638
+ with GzipFile(fileobj=bytes_out, mode='wb', compresslevel=compression) as gzip_file:
639
+ gzip_file.write(data)
640
+ data = bytes_out.getvalue()
641
+ f = _getFSPathOrObject(f)
642
+ if _isString(f):
643
+ filename8 = _encodeFilename(f)
644
+ with open(filename8, 'wb') as f:
645
+ f.write(data)
646
+ else:
647
+ f.write(data)
648
+ return
649
+
650
+ if encoding is None:
651
+ c_enc = NULL
652
+ else:
653
+ encoding = _utf8(encoding)
654
+ c_enc = _cstr(encoding)
655
+ if doctype is None:
656
+ c_doctype = NULL
657
+ else:
658
+ doctype = _utf8(doctype)
659
+ c_doctype = _xcstr(doctype)
660
+
661
+ writer = _create_output_buffer(f, c_enc, compression, &c_buffer, close=False)
662
+ if writer is None:
663
+ with nogil:
664
+ error_result = _serialise_node(
665
+ c_buffer, c_doctype, c_enc, element._c_node, c_method,
666
+ write_xml_declaration, write_doctype, pretty_print, with_tail, standalone)
667
+ else:
668
+ error_result = _serialise_node(
669
+ c_buffer, c_doctype, c_enc, element._c_node, c_method,
670
+ write_xml_declaration, write_doctype, pretty_print, with_tail, standalone)
671
+
672
+ if writer is not None:
673
+ writer._exc_context._raise_if_stored()
674
+ if error_result != xmlerror.XML_ERR_OK:
675
+ _raiseSerialisationError(error_result)
676
+
677
+
678
+ cdef int _serialise_node(tree.xmlOutputBuffer* c_buffer, const_xmlChar* c_doctype,
679
+ const_char* c_enc, xmlNode* c_node, int c_method,
680
+ bint write_xml_declaration, bint write_doctype, bint pretty_print,
681
+ bint with_tail, int standalone) noexcept nogil:
682
+ _writeNodeToBuffer(
683
+ c_buffer, c_node, c_enc, c_doctype, c_method,
684
+ write_xml_declaration, write_doctype, pretty_print, with_tail, standalone)
685
+ error_result = c_buffer.error
686
+ if error_result == xmlerror.XML_ERR_OK:
687
+ error_result = tree.xmlOutputBufferClose(c_buffer)
688
+ if error_result != -1:
689
+ error_result = xmlerror.XML_ERR_OK
690
+ else:
691
+ tree.xmlOutputBufferClose(c_buffer)
692
+ return error_result
693
+
694
+
695
+ cdef _FilelikeWriter _create_output_buffer(
696
+ f, const_char* c_enc, int c_compression,
697
+ tree.xmlOutputBuffer** c_buffer_ret, bint close):
698
+ cdef tree.xmlOutputBuffer* c_buffer
699
+ cdef _FilelikeWriter writer
700
+ cdef bytes filename8
701
+ enchandler = tree.xmlFindCharEncodingHandler(c_enc)
702
+ if enchandler is NULL:
703
+ raise LookupError(
704
+ f"unknown encoding: '{c_enc.decode('UTF-8') if c_enc is not NULL else u''}'")
705
+ try:
706
+ f = _getFSPathOrObject(f)
707
+
708
+ if c_compression and not HAS_ZLIB_COMPRESSION and _isString(f):
709
+ # Let "_FilelikeWriter" fall back to Python's GzipFile.
710
+ f = open(f, mode="wb")
711
+ close = True
712
+
713
+ if _isString(f):
714
+ filename8 = _encodeFilename(f)
715
+ if b'%' in filename8 and (
716
+ # Exclude absolute Windows paths and file:// URLs.
717
+ _isFilePath(<const xmlChar*>filename8) not in (NO_FILE_PATH, ABS_WIN_FILE_PATH)
718
+ or filename8[:7].lower() == b'file://'):
719
+ # A file path (not a URL) containing the '%' URL escape character.
720
+ # libxml2 uses URL-unescaping on these, so escape the path before passing it in.
721
+ filename8 = filename8.replace(b'%', b'%25')
722
+ c_buffer = tree.xmlOutputBufferCreateFilename(
723
+ _cstr(filename8), enchandler, c_compression)
724
+ if c_buffer is NULL:
725
+ python.PyErr_SetFromErrno(IOError) # raises IOError
726
+ writer = None
727
+ elif hasattr(f, 'write'):
728
+ writer = _FilelikeWriter(f, compression=c_compression, close=close)
729
+ c_buffer = writer._createOutputBuffer(enchandler)
730
+ else:
731
+ raise TypeError(
732
+ f"File or filename expected, got '{python._fqtypename(f).decode('UTF-8')}'")
733
+ except:
734
+ tree.xmlCharEncCloseFunc(enchandler)
735
+ raise
736
+ c_buffer_ret[0] = c_buffer
737
+ return writer
738
+
739
+ cdef xmlChar **_convert_ns_prefixes(tree.xmlDict* c_dict, ns_prefixes) except NULL:
740
+ cdef size_t i, num_ns_prefixes = len(ns_prefixes)
741
+ # Need to allocate one extra memory block to handle last NULL entry
742
+ c_ns_prefixes = <xmlChar **>python.lxml_malloc(num_ns_prefixes + 1, sizeof(xmlChar*))
743
+ if not c_ns_prefixes:
744
+ raise MemoryError()
745
+ i = 0
746
+ try:
747
+ for prefix in ns_prefixes:
748
+ prefix_utf = _utf8(prefix)
749
+ c_prefix_len = len(prefix_utf)
750
+ if c_prefix_len > limits.INT_MAX:
751
+ raise ValueError("Prefix too long")
752
+ c_prefix = tree.xmlDictExists(c_dict, _xcstr(prefix_utf), <int> c_prefix_len)
753
+ if c_prefix:
754
+ # unknown prefixes do not need to get serialised
755
+ c_ns_prefixes[i] = <xmlChar*>c_prefix
756
+ i += 1
757
+ except:
758
+ python.lxml_free(c_ns_prefixes)
759
+ raise
760
+
761
+ c_ns_prefixes[i] = NULL # append end marker
762
+ return c_ns_prefixes
763
+
764
+ cdef _tofilelikeC14N(f, _Element element, bint exclusive, bint with_comments,
765
+ int compression, inclusive_ns_prefixes):
766
+ cdef _FilelikeWriter writer = None
767
+ cdef tree.xmlOutputBuffer* c_buffer
768
+ cdef xmlChar **c_inclusive_ns_prefixes = NULL
769
+ cdef char* c_filename
770
+ cdef xmlDoc* c_base_doc
771
+ cdef xmlDoc* c_doc
772
+ cdef int bytes_count, error = 0
773
+
774
+ c_base_doc = element._c_node.doc
775
+ c_doc = _fakeRootDoc(c_base_doc, element._c_node)
776
+ try:
777
+ c_inclusive_ns_prefixes = (
778
+ _convert_ns_prefixes(c_doc.dict, inclusive_ns_prefixes)
779
+ if inclusive_ns_prefixes else NULL)
780
+
781
+ f = _getFSPathOrObject(f)
782
+
783
+ close = False
784
+ if compression and not HAS_ZLIB_COMPRESSION and _isString(f):
785
+ # Let "_FilelikeWriter" fall back to Python's GzipFile.
786
+ f = open(f, mode="wb")
787
+ close = True
788
+
789
+ if _isString(f):
790
+ filename8 = _encodeFilename(f)
791
+ c_filename = _cstr(filename8)
792
+ with nogil:
793
+ error = c14n.xmlC14NDocSave(
794
+ c_doc, NULL, exclusive, c_inclusive_ns_prefixes,
795
+ with_comments, c_filename, compression)
796
+ elif hasattr(f, 'write'):
797
+ writer = _FilelikeWriter(f, compression=compression, close=close)
798
+ c_buffer = writer._createOutputBuffer(NULL)
799
+ try:
800
+ with writer.error_log:
801
+ bytes_count = c14n.xmlC14NDocSaveTo(
802
+ c_doc, NULL, exclusive, c_inclusive_ns_prefixes,
803
+ with_comments, c_buffer)
804
+ finally:
805
+ error = tree.xmlOutputBufferClose(c_buffer)
806
+ if bytes_count < 0:
807
+ error = bytes_count
808
+ elif error != -1:
809
+ error = xmlerror.XML_ERR_OK
810
+ else:
811
+ raise TypeError(f"File or filename expected, got '{python._fqtypename(f).decode('UTF-8')}'")
812
+ finally:
813
+ _destroyFakeDoc(c_base_doc, c_doc)
814
+ if c_inclusive_ns_prefixes is not NULL:
815
+ python.lxml_free(c_inclusive_ns_prefixes)
816
+
817
+ if writer is not None:
818
+ writer._exc_context._raise_if_stored()
819
+
820
+ if error < 0:
821
+ message = "C14N failed"
822
+ if writer is not None:
823
+ errors = writer.error_log
824
+ if len(errors):
825
+ message = errors[0].message
826
+ raise C14NError(message)
827
+
828
+
829
+ # C14N 2.0
830
+
831
+ def canonicalize(xml_data=None, *, out=None, from_file=None, **options):
832
+ """Convert XML to its C14N 2.0 serialised form.
833
+
834
+ If *out* is provided, it must be a file or file-like object that receives
835
+ the serialised canonical XML output (text, not bytes) through its ``.write()``
836
+ method. To write to a file, open it in text mode with encoding "utf-8".
837
+ If *out* is not provided, this function returns the output as text string.
838
+
839
+ Either *xml_data* (an XML string, tree or Element) or *file*
840
+ (a file path or file-like object) must be provided as input.
841
+
842
+ The configuration options are the same as for the ``C14NWriterTarget``.
843
+ """
844
+ if xml_data is None and from_file is None:
845
+ raise ValueError("Either 'xml_data' or 'from_file' must be provided as input")
846
+
847
+ sio = None
848
+ if out is None:
849
+ sio = out = StringIO()
850
+
851
+ target = C14NWriterTarget(out.write, **options)
852
+
853
+ if xml_data is not None and not isinstance(xml_data, basestring):
854
+ _tree_to_target(xml_data, target)
855
+ return sio.getvalue() if sio is not None else None
856
+
857
+ cdef _FeedParser parser = XMLParser(
858
+ target=target,
859
+ attribute_defaults=True,
860
+ collect_ids=False,
861
+ )
862
+
863
+ if xml_data is not None:
864
+ parser.feed(xml_data)
865
+ parser.close()
866
+ elif from_file is not None:
867
+ try:
868
+ _parseDocument(from_file, parser, base_url=None)
869
+ except _TargetParserResult:
870
+ pass
871
+
872
+ return sio.getvalue() if sio is not None else None
873
+
874
+
875
+ cdef _tree_to_target(element, target):
876
+ for event, elem in iterwalk(element, events=('start', 'end', 'start-ns', 'comment', 'pi')):
877
+ text = None
878
+ if event == 'start':
879
+ target.start(elem.tag, elem.attrib)
880
+ text = elem.text
881
+ elif event == 'end':
882
+ target.end(elem.tag)
883
+ text = elem.tail
884
+ elif event == 'start-ns':
885
+ target.start_ns(*elem)
886
+ continue
887
+ elif event == 'comment':
888
+ target.comment(elem.text)
889
+ text = elem.tail
890
+ elif event == 'pi':
891
+ target.pi(elem.target, elem.text)
892
+ text = elem.tail
893
+ if text:
894
+ target.data(text)
895
+ return target.close()
896
+
897
+
898
+ cdef object _looks_like_prefix_name = re.compile(r'^\w+:\w+$', re.UNICODE).match
899
+
900
+
901
+ cdef class C14NWriterTarget:
902
+ """
903
+ Canonicalization writer target for the XMLParser.
904
+
905
+ Serialises parse events to XML C14N 2.0.
906
+
907
+ Configuration options:
908
+
909
+ - *with_comments*: set to true to include comments
910
+ - *strip_text*: set to true to strip whitespace before and after text content
911
+ - *rewrite_prefixes*: set to true to replace namespace prefixes by "n{number}"
912
+ - *qname_aware_tags*: a set of qname aware tag names in which prefixes
913
+ should be replaced in text content
914
+ - *qname_aware_attrs*: a set of qname aware attribute names in which prefixes
915
+ should be replaced in text content
916
+ - *exclude_attrs*: a set of attribute names that should not be serialised
917
+ - *exclude_tags*: a set of tag names that should not be serialised
918
+ """
919
+ cdef object _write
920
+ cdef list _data
921
+ cdef set _qname_aware_tags
922
+ cdef object _find_qname_aware_attrs
923
+ cdef list _declared_ns_stack
924
+ cdef list _ns_stack
925
+ cdef dict _prefix_map
926
+ cdef list _preserve_space
927
+ cdef tuple _pending_start
928
+ cdef set _exclude_tags
929
+ cdef set _exclude_attrs
930
+ cdef Py_ssize_t _ignored_depth
931
+ cdef bint _with_comments
932
+ cdef bint _strip_text
933
+ cdef bint _rewrite_prefixes
934
+ cdef bint _root_seen
935
+ cdef bint _root_done
936
+
937
+ def __init__(self, write, *,
938
+ with_comments=False, strip_text=False, rewrite_prefixes=False,
939
+ qname_aware_tags=None, qname_aware_attrs=None,
940
+ exclude_attrs=None, exclude_tags=None):
941
+ self._write = write
942
+ self._data = []
943
+ self._with_comments = with_comments
944
+ self._strip_text = strip_text
945
+ self._exclude_attrs = set(exclude_attrs) if exclude_attrs else None
946
+ self._exclude_tags = set(exclude_tags) if exclude_tags else None
947
+
948
+ self._rewrite_prefixes = rewrite_prefixes
949
+ if qname_aware_tags:
950
+ self._qname_aware_tags = set(qname_aware_tags)
951
+ else:
952
+ self._qname_aware_tags = None
953
+ if qname_aware_attrs:
954
+ self._find_qname_aware_attrs = set(qname_aware_attrs).intersection
955
+ else:
956
+ self._find_qname_aware_attrs = None
957
+
958
+ # Stack with globally and newly declared namespaces as (uri, prefix) pairs.
959
+ self._declared_ns_stack = [[
960
+ ("http://www.w3.org/XML/1998/namespace", "xml"),
961
+ ]]
962
+ # Stack with user declared namespace prefixes as (uri, prefix) pairs.
963
+ self._ns_stack = []
964
+ if not rewrite_prefixes:
965
+ self._ns_stack.append(_DEFAULT_NAMESPACE_PREFIXES_ITEMS)
966
+ self._ns_stack.append([])
967
+ self._prefix_map = {}
968
+ self._preserve_space = [False]
969
+ self._pending_start = None
970
+ self._ignored_depth = 0
971
+ self._root_seen = False
972
+ self._root_done = False
973
+
974
+ def _iter_namespaces(self, ns_stack):
975
+ for namespaces in reversed(ns_stack):
976
+ if namespaces: # almost no element declares new namespaces
977
+ yield from namespaces
978
+
979
+ cdef _resolve_prefix_name(self, prefixed_name):
980
+ prefix, name = prefixed_name.split(':', 1)
981
+ for uri, p in self._iter_namespaces(self._ns_stack):
982
+ if p == prefix:
983
+ return f'{{{uri}}}{name}'
984
+ raise ValueError(f'Prefix {prefix} of QName "{prefixed_name}" is not declared in scope')
985
+
986
+ cdef _qname(self, qname, uri=None):
987
+ if uri is None:
988
+ uri, tag = qname[1:].rsplit('}', 1) if qname[:1] == '{' else ('', qname)
989
+ else:
990
+ tag = qname
991
+
992
+ prefixes_seen = set()
993
+ for u, prefix in self._iter_namespaces(self._declared_ns_stack):
994
+ if u == uri and prefix not in prefixes_seen:
995
+ return f'{prefix}:{tag}' if prefix else tag, tag, uri
996
+ prefixes_seen.add(prefix)
997
+
998
+ # Not declared yet => add new declaration.
999
+ if self._rewrite_prefixes:
1000
+ if uri in self._prefix_map:
1001
+ prefix = self._prefix_map[uri]
1002
+ else:
1003
+ prefix = self._prefix_map[uri] = f'n{len(self._prefix_map)}'
1004
+ self._declared_ns_stack[-1].append((uri, prefix))
1005
+ return f'{prefix}:{tag}', tag, uri
1006
+
1007
+ if not uri and '' not in prefixes_seen:
1008
+ # No default namespace declared => no prefix needed.
1009
+ return tag, tag, uri
1010
+
1011
+ for u, prefix in self._iter_namespaces(self._ns_stack):
1012
+ if u == uri:
1013
+ self._declared_ns_stack[-1].append((uri, prefix))
1014
+ return f'{prefix}:{tag}' if prefix else tag, tag, uri
1015
+
1016
+ if not uri:
1017
+ # As soon as a default namespace is defined,
1018
+ # anything that has no namespace (and thus, no prefix) goes there.
1019
+ return tag, tag, uri
1020
+
1021
+ raise ValueError(f'Namespace "{uri}" of name "{tag}" is not declared in scope')
1022
+
1023
+ def data(self, data):
1024
+ if not self._ignored_depth:
1025
+ self._data.append(data)
1026
+
1027
+ cdef _flush(self):
1028
+ cdef unicode data = ''.join(self._data)
1029
+ del self._data[:]
1030
+ if self._strip_text and not self._preserve_space[-1]:
1031
+ data = data.strip()
1032
+ if self._pending_start is not None:
1033
+ (tag, attrs, new_namespaces), self._pending_start = self._pending_start, None
1034
+ qname_text = data if ':' in data and _looks_like_prefix_name(data) else None
1035
+ self._start(tag, attrs, new_namespaces, qname_text)
1036
+ if qname_text is not None:
1037
+ return
1038
+ if data and self._root_seen:
1039
+ self._write(_escape_cdata_c14n(data))
1040
+
1041
+ def start_ns(self, prefix, uri):
1042
+ if self._ignored_depth:
1043
+ return
1044
+ # we may have to resolve qnames in text content
1045
+ if self._data:
1046
+ self._flush()
1047
+ self._ns_stack[-1].append((uri, prefix))
1048
+
1049
+ def start(self, tag, attrs):
1050
+ if self._exclude_tags is not None and (
1051
+ self._ignored_depth or tag in self._exclude_tags):
1052
+ self._ignored_depth += 1
1053
+ return
1054
+ if self._data:
1055
+ self._flush()
1056
+
1057
+ new_namespaces = []
1058
+ self._declared_ns_stack.append(new_namespaces)
1059
+
1060
+ if self._qname_aware_tags is not None and tag in self._qname_aware_tags:
1061
+ # Need to parse text first to see if it requires a prefix declaration.
1062
+ self._pending_start = (tag, attrs, new_namespaces)
1063
+ return
1064
+ self._start(tag, attrs, new_namespaces)
1065
+
1066
+ cdef _start(self, tag, attrs, new_namespaces, qname_text=None):
1067
+ if self._exclude_attrs is not None and attrs:
1068
+ attrs = {k: v for k, v in attrs.items() if k not in self._exclude_attrs}
1069
+
1070
+ qnames = {tag, *attrs}
1071
+ resolved_names = {}
1072
+
1073
+ # Resolve prefixes in attribute and tag text.
1074
+ if qname_text is not None:
1075
+ qname = resolved_names[qname_text] = self._resolve_prefix_name(qname_text)
1076
+ qnames.add(qname)
1077
+ if self._find_qname_aware_attrs is not None and attrs:
1078
+ qattrs = self._find_qname_aware_attrs(attrs)
1079
+ if qattrs:
1080
+ for attr_name in qattrs:
1081
+ value = attrs[attr_name]
1082
+ if _looks_like_prefix_name(value):
1083
+ qname = resolved_names[value] = self._resolve_prefix_name(value)
1084
+ qnames.add(qname)
1085
+ else:
1086
+ qattrs = None
1087
+ else:
1088
+ qattrs = None
1089
+
1090
+ # Assign prefixes in lexicographical order of used URIs.
1091
+ parsed_qnames = {n: self._qname(n) for n in sorted(
1092
+ qnames, key=lambda n: n.split('}', 1))}
1093
+
1094
+ # Write namespace declarations in prefix order ...
1095
+ if new_namespaces:
1096
+ attr_list = [
1097
+ ('xmlns:' + prefix if prefix else 'xmlns', uri)
1098
+ for uri, prefix in new_namespaces
1099
+ ]
1100
+ attr_list.sort()
1101
+ else:
1102
+ # almost always empty
1103
+ attr_list = []
1104
+
1105
+ # ... followed by attributes in URI+name order
1106
+ if attrs:
1107
+ for k, v in sorted(attrs.items()):
1108
+ if qattrs is not None and k in qattrs and v in resolved_names:
1109
+ v = parsed_qnames[resolved_names[v]][0]
1110
+ attr_qname, attr_name, uri = parsed_qnames[k]
1111
+ # No prefix for attributes in default ('') namespace.
1112
+ attr_list.append((attr_qname if uri else attr_name, v))
1113
+
1114
+ # Honour xml:space attributes.
1115
+ space_behaviour = attrs.get('{http://www.w3.org/XML/1998/namespace}space')
1116
+ self._preserve_space.append(
1117
+ space_behaviour == 'preserve' if space_behaviour
1118
+ else self._preserve_space[-1])
1119
+
1120
+ # Write the tag.
1121
+ write = self._write
1122
+ write('<' + parsed_qnames[tag][0])
1123
+ if attr_list:
1124
+ write(''.join([f' {k}="{_escape_attrib_c14n(v)}"' for k, v in attr_list]))
1125
+ write('>')
1126
+
1127
+ # Write the resolved qname text content.
1128
+ if qname_text is not None:
1129
+ write(_escape_cdata_c14n(parsed_qnames[resolved_names[qname_text]][0]))
1130
+
1131
+ self._root_seen = True
1132
+ self._ns_stack.append([])
1133
+
1134
+ def end(self, tag):
1135
+ if self._ignored_depth:
1136
+ self._ignored_depth -= 1
1137
+ return
1138
+ if self._data:
1139
+ self._flush()
1140
+ self._write(f'</{self._qname(tag)[0]}>')
1141
+ self._preserve_space.pop()
1142
+ self._root_done = len(self._preserve_space) == 1
1143
+ self._declared_ns_stack.pop()
1144
+ self._ns_stack.pop()
1145
+
1146
+ def comment(self, text):
1147
+ if not self._with_comments:
1148
+ return
1149
+ if self._ignored_depth:
1150
+ return
1151
+ if self._root_done:
1152
+ self._write('\n')
1153
+ elif self._root_seen and self._data:
1154
+ self._flush()
1155
+ self._write(f'<!--{_escape_cdata_c14n(text)}-->')
1156
+ if not self._root_seen:
1157
+ self._write('\n')
1158
+
1159
+ def pi(self, target, data):
1160
+ if self._ignored_depth:
1161
+ return
1162
+ if self._root_done:
1163
+ self._write('\n')
1164
+ elif self._root_seen and self._data:
1165
+ self._flush()
1166
+ self._write(
1167
+ f'<?{target} {_escape_cdata_c14n(data)}?>' if data else f'<?{target}?>')
1168
+ if not self._root_seen:
1169
+ self._write('\n')
1170
+
1171
+ def close(self):
1172
+ return None
1173
+
1174
+
1175
+ cdef _raise_serialization_error(text):
1176
+ raise TypeError("cannot serialize %r (type %s)" % (text, type(text).__name__))
1177
+
1178
+
1179
+ cdef unicode _escape_cdata_c14n(stext):
1180
+ # escape character data
1181
+ cdef unicode text
1182
+ cdef Py_UCS4 ch
1183
+ cdef Py_ssize_t start = 0, pos = 0
1184
+ cdef list substrings = None
1185
+ try:
1186
+ text = unicode(stext)
1187
+ except (TypeError, AttributeError):
1188
+ return _raise_serialization_error(stext)
1189
+
1190
+ for pos, ch in enumerate(text):
1191
+ if ch == '&':
1192
+ escape = '&amp;'
1193
+ elif ch == '<':
1194
+ escape = '&lt;'
1195
+ elif ch == '>':
1196
+ escape = '&gt;'
1197
+ elif ch == '\r':
1198
+ escape = '&#xD;'
1199
+ else:
1200
+ continue
1201
+
1202
+ if substrings is None:
1203
+ substrings = []
1204
+ if pos > start:
1205
+ substrings.append(text[start:pos])
1206
+ substrings.append(escape)
1207
+ start = pos + 1
1208
+
1209
+ if substrings is None:
1210
+ return text
1211
+ if pos >= start:
1212
+ substrings.append(text[start:pos+1])
1213
+ return ''.join(substrings)
1214
+
1215
+
1216
+ cdef unicode _escape_attrib_c14n(stext):
1217
+ # escape attribute value
1218
+ cdef unicode text
1219
+ cdef Py_UCS4 ch
1220
+ cdef Py_ssize_t start = 0, pos = 0
1221
+ cdef list substrings = None
1222
+ try:
1223
+ text = unicode(stext)
1224
+ except (TypeError, AttributeError):
1225
+ return _raise_serialization_error(stext)
1226
+
1227
+ for pos, ch in enumerate(text):
1228
+ if ch == '&':
1229
+ escape = '&amp;'
1230
+ elif ch == '<':
1231
+ escape = '&lt;'
1232
+ elif ch == '"':
1233
+ escape = '&quot;'
1234
+ elif ch == '\t':
1235
+ escape = '&#x9;'
1236
+ elif ch == '\n':
1237
+ escape = '&#xA;'
1238
+ elif ch == '\r':
1239
+ escape = '&#xD;'
1240
+ else:
1241
+ continue
1242
+
1243
+ if substrings is None:
1244
+ substrings = []
1245
+ if pos > start:
1246
+ substrings.append(text[start:pos])
1247
+ substrings.append(escape)
1248
+ start = pos + 1
1249
+
1250
+ if substrings is None:
1251
+ return text
1252
+ if pos >= start:
1253
+ substrings.append(text[start:pos+1])
1254
+ return ''.join(substrings)
1255
+
1256
+
1257
+ # incremental serialisation
1258
+
1259
+ cdef class xmlfile:
1260
+ """xmlfile(self, output_file, encoding=None, compression=None, close=False, buffered=True)
1261
+
1262
+ A simple mechanism for incremental XML serialisation.
1263
+
1264
+ Usage example::
1265
+
1266
+ with xmlfile("somefile.xml", encoding='utf-8') as xf:
1267
+ xf.write_declaration(standalone=True)
1268
+ xf.write_doctype('<!DOCTYPE root SYSTEM "some.dtd">')
1269
+
1270
+ # generate an element (the root element)
1271
+ with xf.element('root'):
1272
+ # write a complete Element into the open root element
1273
+ xf.write(etree.Element('test'))
1274
+
1275
+ # generate and write more Elements, e.g. through iterparse
1276
+ for element in generate_some_elements():
1277
+ # serialise generated elements into the XML file
1278
+ xf.write(element)
1279
+
1280
+ # or write multiple Elements or strings at once
1281
+ xf.write(etree.Element('start'), "text", etree.Element('end'))
1282
+
1283
+ If 'output_file' is a file(-like) object, passing ``close=True`` will
1284
+ close it when exiting the context manager. By default, it is left
1285
+ to the owner to do that. When a file path is used, lxml will take care
1286
+ of opening and closing the file itself. Also, when a compression level
1287
+ is set, lxml will deliberately close the file to make sure all data gets
1288
+ compressed and written.
1289
+
1290
+ Setting ``buffered=False`` will flush the output after each operation,
1291
+ such as opening or closing an ``xf.element()`` block or calling
1292
+ ``xf.write()``. Alternatively, calling ``xf.flush()`` can be used to
1293
+ explicitly flush any pending output when buffering is enabled.
1294
+ """
1295
+ cdef object output_file
1296
+ cdef bytes encoding
1297
+ cdef _IncrementalFileWriter writer
1298
+ cdef _AsyncIncrementalFileWriter async_writer
1299
+ cdef int compresslevel
1300
+ cdef bint close
1301
+ cdef bint buffered
1302
+ cdef int method
1303
+
1304
+ def __init__(self, output_file not None, encoding=None, compression=None,
1305
+ close=False, buffered=True):
1306
+ self.output_file = output_file
1307
+ self.encoding = _utf8orNone(encoding)
1308
+ self.compresslevel = compression or 0
1309
+ self.close = close
1310
+ self.buffered = buffered
1311
+ self.method = OUTPUT_METHOD_XML
1312
+
1313
+ def __enter__(self):
1314
+ assert self.output_file is not None
1315
+ self.writer = _IncrementalFileWriter(
1316
+ self.output_file, self.encoding, self.compresslevel,
1317
+ self.close, self.buffered, self.method)
1318
+ return self.writer
1319
+
1320
+ def __exit__(self, exc_type, exc_val, exc_tb):
1321
+ if self.writer is not None:
1322
+ old_writer, self.writer = self.writer, None
1323
+ raise_on_error = exc_type is None
1324
+ old_writer._close(raise_on_error)
1325
+ if self.close:
1326
+ self.output_file = None
1327
+
1328
+ async def __aenter__(self):
1329
+ assert self.output_file is not None
1330
+ if isinstance(self.output_file, basestring):
1331
+ raise TypeError("Cannot asynchronously write to a plain file")
1332
+ if not hasattr(self.output_file, 'write'):
1333
+ raise TypeError("Output file needs an async .write() method")
1334
+ self.async_writer = _AsyncIncrementalFileWriter(
1335
+ self.output_file, self.encoding, self.compresslevel,
1336
+ self.close, self.buffered, self.method)
1337
+ return self.async_writer
1338
+
1339
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
1340
+ if self.async_writer is not None:
1341
+ old_writer, self.async_writer = self.async_writer, None
1342
+ raise_on_error = exc_type is None
1343
+ await old_writer._close(raise_on_error)
1344
+ if self.close:
1345
+ self.output_file = None
1346
+
1347
+
1348
+ cdef class htmlfile(xmlfile):
1349
+ """htmlfile(self, output_file, encoding=None, compression=None, close=False, buffered=True)
1350
+
1351
+ A simple mechanism for incremental HTML serialisation. Works the same as
1352
+ xmlfile.
1353
+ """
1354
+ def __init__(self, *args, **kwargs):
1355
+ super().__init__(*args, **kwargs)
1356
+ self.method = OUTPUT_METHOD_HTML
1357
+
1358
+
1359
+ cdef enum _IncrementalFileWriterStatus:
1360
+ WRITER_STARTING = 0
1361
+ WRITER_DECL_WRITTEN = 1
1362
+ WRITER_DTD_WRITTEN = 2
1363
+ WRITER_IN_ELEMENT = 3
1364
+ WRITER_FINISHED = 4
1365
+
1366
+
1367
+ @cython.final
1368
+ @cython.internal
1369
+ cdef class _IncrementalFileWriter:
1370
+ cdef tree.xmlOutputBuffer* _c_out
1371
+ cdef bytes _encoding
1372
+ cdef const_char* _c_encoding
1373
+ cdef _FilelikeWriter _target
1374
+ cdef list _element_stack
1375
+ cdef int _status
1376
+ cdef int _method
1377
+ cdef bint _buffered
1378
+
1379
+ def __cinit__(self, outfile, bytes encoding, int compresslevel, bint close,
1380
+ bint buffered, int method):
1381
+ self._status = WRITER_STARTING
1382
+ self._element_stack = []
1383
+ if encoding is None:
1384
+ # We always need a document encoding to make the attribute serialisation
1385
+ # of libxml2 identical to ours.
1386
+ encoding = b'ASCII'
1387
+ self._encoding = encoding
1388
+ self._c_encoding = _cstr(encoding)
1389
+ self._buffered = buffered
1390
+ self._target = _create_output_buffer(
1391
+ outfile, self._c_encoding, compresslevel, &self._c_out, close)
1392
+ self._method = method
1393
+
1394
+ def __dealloc__(self):
1395
+ if self._c_out is not NULL:
1396
+ tree.xmlOutputBufferClose(self._c_out)
1397
+
1398
+ def write_declaration(self, version=None, standalone=None, doctype=None):
1399
+ """write_declaration(self, version=None, standalone=None, doctype=None)
1400
+
1401
+ Write an XML declaration and (optionally) a doctype into the file.
1402
+ """
1403
+ assert self._c_out is not NULL
1404
+ cdef const_xmlChar* c_version
1405
+ cdef int c_standalone
1406
+ if self._method != OUTPUT_METHOD_XML:
1407
+ raise LxmlSyntaxError("only XML documents have declarations")
1408
+ if self._status >= WRITER_DECL_WRITTEN:
1409
+ raise LxmlSyntaxError("XML declaration already written")
1410
+ version = _utf8orNone(version)
1411
+ c_version = _xcstr(version) if version is not None else NULL
1412
+ doctype = _utf8orNone(doctype)
1413
+ if standalone is None:
1414
+ c_standalone = -1
1415
+ else:
1416
+ c_standalone = 1 if standalone else 0
1417
+ _writeDeclarationToBuffer(self._c_out, c_version, self._c_encoding, c_standalone)
1418
+ if doctype is not None:
1419
+ _writeDoctype(self._c_out, _xcstr(doctype))
1420
+ self._status = WRITER_DTD_WRITTEN
1421
+ else:
1422
+ self._status = WRITER_DECL_WRITTEN
1423
+ if not self._buffered:
1424
+ tree.xmlOutputBufferFlush(self._c_out)
1425
+ self._handle_error(self._c_out.error)
1426
+
1427
+ def write_doctype(self, doctype):
1428
+ """write_doctype(self, doctype)
1429
+
1430
+ Writes the given doctype declaration verbatimly into the file.
1431
+ """
1432
+ assert self._c_out is not NULL
1433
+ if doctype is None:
1434
+ return
1435
+ if self._status >= WRITER_DTD_WRITTEN:
1436
+ raise LxmlSyntaxError("DOCTYPE already written or cannot write it here")
1437
+ doctype = _utf8(doctype)
1438
+ _writeDoctype(self._c_out, _xcstr(doctype))
1439
+ self._status = WRITER_DTD_WRITTEN
1440
+ if not self._buffered:
1441
+ tree.xmlOutputBufferFlush(self._c_out)
1442
+ self._handle_error(self._c_out.error)
1443
+
1444
+ def method(self, method):
1445
+ """method(self, method)
1446
+
1447
+ Returns a context manager that overrides and restores the output method.
1448
+ method is one of (None, 'xml', 'html') where None means 'xml'.
1449
+ """
1450
+ assert self._c_out is not NULL
1451
+ c_method = self._method if method is None else _findOutputMethod(method)
1452
+ return _MethodChanger(self, c_method)
1453
+
1454
+ def element(self, tag, attrib=None, nsmap=None, method=None, **_extra):
1455
+ """element(self, tag, attrib=None, nsmap=None, method, **_extra)
1456
+
1457
+ Returns a context manager that writes an opening and closing tag.
1458
+ method is one of (None, 'xml', 'html') where None means 'xml'.
1459
+ """
1460
+ assert self._c_out is not NULL
1461
+ attributes = []
1462
+ if attrib is not None:
1463
+ for name, value in _iter_attrib(attrib):
1464
+ if name not in _extra:
1465
+ ns, name = _getNsTag(name)
1466
+ attributes.append((ns, name, _utf8(value)))
1467
+ if _extra:
1468
+ for name, value in _extra.iteritems():
1469
+ ns, name = _getNsTag(name)
1470
+ attributes.append((ns, name, _utf8(value)))
1471
+ reversed_nsmap = {}
1472
+ if nsmap:
1473
+ for prefix, ns in nsmap.items():
1474
+ if prefix is not None:
1475
+ prefix = _utf8(prefix)
1476
+ _prefixValidOrRaise(prefix)
1477
+ reversed_nsmap[_utf8(ns)] = prefix
1478
+ ns, name = _getNsTag(tag)
1479
+
1480
+ c_method = self._method if method is None else _findOutputMethod(method)
1481
+
1482
+ return _FileWriterElement(self, (ns, name, attributes, reversed_nsmap), c_method)
1483
+
1484
+ cdef _write_qname(self, bytes name, bytes prefix):
1485
+ if prefix: # empty bytes for no prefix (not None to allow sorting)
1486
+ tree.xmlOutputBufferWrite(self._c_out, len(prefix), _cstr(prefix))
1487
+ tree.xmlOutputBufferWrite(self._c_out, 1, ':')
1488
+ tree.xmlOutputBufferWrite(self._c_out, len(name), _cstr(name))
1489
+
1490
+ cdef _write_start_element(self, element_config):
1491
+ if self._status > WRITER_IN_ELEMENT:
1492
+ raise LxmlSyntaxError("cannot append trailing element to complete XML document")
1493
+ ns, name, attributes, nsmap = element_config
1494
+ flat_namespace_map, new_namespaces = self._collect_namespaces(nsmap)
1495
+ prefix = self._find_prefix(ns, flat_namespace_map, new_namespaces)
1496
+ tree.xmlOutputBufferWrite(self._c_out, 1, '<')
1497
+ self._write_qname(name, prefix)
1498
+
1499
+ self._write_attributes_and_namespaces(
1500
+ attributes, flat_namespace_map, new_namespaces)
1501
+
1502
+ tree.xmlOutputBufferWrite(self._c_out, 1, '>')
1503
+ if not self._buffered:
1504
+ tree.xmlOutputBufferFlush(self._c_out)
1505
+ self._handle_error(self._c_out.error)
1506
+
1507
+ self._element_stack.append((ns, name, prefix, flat_namespace_map))
1508
+ self._status = WRITER_IN_ELEMENT
1509
+
1510
+ cdef _write_attributes_and_namespaces(self, list attributes,
1511
+ dict flat_namespace_map,
1512
+ list new_namespaces):
1513
+ if attributes:
1514
+ # _find_prefix() may append to new_namespaces => build them first
1515
+ attributes = [
1516
+ (self._find_prefix(ns, flat_namespace_map, new_namespaces), name, value)
1517
+ for ns, name, value in attributes ]
1518
+ if new_namespaces:
1519
+ new_namespaces.sort()
1520
+ self._write_attributes_list(new_namespaces)
1521
+ if attributes:
1522
+ self._write_attributes_list(attributes)
1523
+
1524
+ cdef _write_attributes_list(self, list attributes):
1525
+ for prefix, name, value in attributes:
1526
+ tree.xmlOutputBufferWrite(self._c_out, 1, ' ')
1527
+ self._write_qname(name, prefix)
1528
+ tree.xmlOutputBufferWrite(self._c_out, 2, '="')
1529
+ _write_attr_string(self._c_out, _cstr(value))
1530
+
1531
+ tree.xmlOutputBufferWrite(self._c_out, 1, '"')
1532
+
1533
+ cdef _write_end_element(self, element_config):
1534
+ if self._status != WRITER_IN_ELEMENT:
1535
+ raise LxmlSyntaxError("not in an element")
1536
+ if not self._element_stack or self._element_stack[-1][:2] != element_config[:2]:
1537
+ raise LxmlSyntaxError("inconsistent exit action in context manager")
1538
+
1539
+ # If previous write operations failed, the context manager exit might still call us.
1540
+ # That is ok, but we stop writing closing tags and handling errors in that case.
1541
+ # For all non-I/O errors, we continue writing closing tags if we can.
1542
+ ok_to_write = self._c_out.error == xmlerror.XML_ERR_OK
1543
+
1544
+ name, prefix = self._element_stack.pop()[1:3]
1545
+ if ok_to_write:
1546
+ tree.xmlOutputBufferWrite(self._c_out, 2, '</')
1547
+ self._write_qname(name, prefix)
1548
+ tree.xmlOutputBufferWrite(self._c_out, 1, '>')
1549
+
1550
+ if not self._element_stack:
1551
+ self._status = WRITER_FINISHED
1552
+ if ok_to_write:
1553
+ if not self._buffered:
1554
+ tree.xmlOutputBufferFlush(self._c_out)
1555
+ self._handle_error(self._c_out.error)
1556
+
1557
+ cdef _find_prefix(self, bytes href, dict flat_namespaces_map, list new_namespaces):
1558
+ if href is None:
1559
+ return None
1560
+ if href in flat_namespaces_map:
1561
+ return flat_namespaces_map[href]
1562
+ # need to create a new prefix
1563
+ prefixes = flat_namespaces_map.values()
1564
+ i = 0
1565
+ while True:
1566
+ prefix = _utf8('ns%d' % i)
1567
+ if prefix not in prefixes:
1568
+ new_namespaces.append((b'xmlns', prefix, href))
1569
+ flat_namespaces_map[href] = prefix
1570
+ return prefix
1571
+ i += 1
1572
+
1573
+ cdef _collect_namespaces(self, dict nsmap):
1574
+ new_namespaces = []
1575
+ flat_namespaces_map = {}
1576
+ for ns, prefix in nsmap.iteritems():
1577
+ flat_namespaces_map[ns] = prefix
1578
+ if prefix is None:
1579
+ # use empty bytes rather than None to allow sorting
1580
+ new_namespaces.append((b'', b'xmlns', ns))
1581
+ else:
1582
+ new_namespaces.append((b'xmlns', prefix, ns))
1583
+ # merge in flat namespace map of parent
1584
+ if self._element_stack:
1585
+ for ns, prefix in (<dict>self._element_stack[-1][-1]).iteritems():
1586
+ if flat_namespaces_map.get(ns) is None:
1587
+ # unknown or empty prefix => prefer a 'real' prefix
1588
+ flat_namespaces_map[ns] = prefix
1589
+ return flat_namespaces_map, new_namespaces
1590
+
1591
+ def write(self, *args, bint with_tail=True, bint pretty_print=False, method=None):
1592
+ """write(self, *args, with_tail=True, pretty_print=False, method=None)
1593
+
1594
+ Write subtrees or strings into the file.
1595
+
1596
+ If method is not None, it should be one of ('html', 'xml', 'text')
1597
+ to temporarily override the output method.
1598
+ """
1599
+ assert self._c_out is not NULL
1600
+ c_method = self._method if method is None else _findOutputMethod(method)
1601
+
1602
+ for content in args:
1603
+ if _isString(content):
1604
+ if self._status != WRITER_IN_ELEMENT:
1605
+ if self._status > WRITER_IN_ELEMENT or content.strip():
1606
+ raise LxmlSyntaxError("not in an element")
1607
+ bstring = _utf8(content)
1608
+ if not bstring:
1609
+ continue
1610
+
1611
+ ns, name, _, _ = self._element_stack[-1]
1612
+ if (c_method == OUTPUT_METHOD_HTML and
1613
+ ns in (None, b'http://www.w3.org/1999/xhtml') and
1614
+ name in (b'script', b'style')):
1615
+ tree.xmlOutputBufferWrite(self._c_out, len(bstring), _cstr(bstring))
1616
+
1617
+ else:
1618
+ tree.xmlOutputBufferWriteEscape(self._c_out, _xcstr(bstring), NULL)
1619
+
1620
+ elif isinstance(content, CDATA):
1621
+ if self._status > WRITER_IN_ELEMENT:
1622
+ raise LxmlSyntaxError("not in an element")
1623
+ _write_cdata_string(self._c_out, (<CDATA>content)._utf8_data)
1624
+
1625
+ elif iselement(content):
1626
+ if self._status > WRITER_IN_ELEMENT:
1627
+ raise LxmlSyntaxError("cannot append trailing element to complete XML document")
1628
+ _writeNodeToBuffer(self._c_out, (<_Element>content)._c_node,
1629
+ self._c_encoding, NULL, c_method,
1630
+ False, False, pretty_print, with_tail, False)
1631
+ if (<_Element>content)._c_node.type == tree.XML_ELEMENT_NODE:
1632
+ if not self._element_stack:
1633
+ self._status = WRITER_FINISHED
1634
+
1635
+ elif content is not None:
1636
+ raise TypeError(
1637
+ f"got invalid input value of type {type(content)}, expected string, CDATA or Element")
1638
+
1639
+ self._handle_error(self._c_out.error)
1640
+
1641
+ if not self._buffered:
1642
+ tree.xmlOutputBufferFlush(self._c_out)
1643
+ self._handle_error(self._c_out.error)
1644
+
1645
+ def flush(self):
1646
+ """flush(self)
1647
+
1648
+ Write any pending content of the current output buffer to the stream.
1649
+ """
1650
+ assert self._c_out is not NULL
1651
+ tree.xmlOutputBufferFlush(self._c_out)
1652
+ self._handle_error(self._c_out.error)
1653
+
1654
+ cdef _close(self, bint raise_on_error):
1655
+ if raise_on_error:
1656
+ if self._status < WRITER_IN_ELEMENT:
1657
+ raise LxmlSyntaxError("no content written")
1658
+ if self._element_stack:
1659
+ raise LxmlSyntaxError("pending open tags on close")
1660
+ error_result = self._c_out.error
1661
+ if error_result == xmlerror.XML_ERR_OK:
1662
+ error_result = tree.xmlOutputBufferClose(self._c_out)
1663
+ if error_result != -1:
1664
+ error_result = xmlerror.XML_ERR_OK
1665
+ else:
1666
+ tree.xmlOutputBufferClose(self._c_out)
1667
+ self._status = WRITER_FINISHED
1668
+ self._c_out = NULL
1669
+ del self._element_stack[:]
1670
+ if raise_on_error:
1671
+ self._handle_error(error_result)
1672
+
1673
+ cdef _handle_error(self, int error_result):
1674
+ if error_result != xmlerror.XML_ERR_OK:
1675
+ if self._target is not None:
1676
+ self._target._exc_context._raise_if_stored()
1677
+ _raiseSerialisationError(error_result)
1678
+
1679
+
1680
+ @cython.final
1681
+ @cython.internal
1682
+ cdef class _AsyncDataWriter:
1683
+ cdef list _data
1684
+ def __cinit__(self):
1685
+ self._data = []
1686
+
1687
+ cdef bytes collect(self):
1688
+ data = b''.join(self._data)
1689
+ del self._data[:]
1690
+ return data
1691
+
1692
+ def write(self, data):
1693
+ self._data.append(data)
1694
+
1695
+ def close(self):
1696
+ pass
1697
+
1698
+
1699
+ @cython.final
1700
+ @cython.internal
1701
+ cdef class _AsyncIncrementalFileWriter:
1702
+ cdef _IncrementalFileWriter _writer
1703
+ cdef _AsyncDataWriter _buffer
1704
+ cdef object _async_outfile
1705
+ cdef int _flush_after_writes
1706
+ cdef bint _should_close
1707
+ cdef bint _buffered
1708
+
1709
+ def __cinit__(self, async_outfile, bytes encoding, int compresslevel, bint close,
1710
+ bint buffered, int method):
1711
+ self._flush_after_writes = 20
1712
+ self._async_outfile = async_outfile
1713
+ self._should_close = close
1714
+ self._buffered = buffered
1715
+ self._buffer = _AsyncDataWriter()
1716
+ self._writer = _IncrementalFileWriter(
1717
+ self._buffer, encoding, compresslevel, close=True, buffered=False, method=method)
1718
+
1719
+ cdef bytes _flush(self):
1720
+ if not self._buffered or len(self._buffer._data) > self._flush_after_writes:
1721
+ return self._buffer.collect()
1722
+ return None
1723
+
1724
+ async def flush(self):
1725
+ self._writer.flush()
1726
+ data = self._buffer.collect()
1727
+ if data:
1728
+ await self._async_outfile.write(data)
1729
+
1730
+ async def write_declaration(self, version=None, standalone=None, doctype=None):
1731
+ self._writer.write_declaration(version, standalone, doctype)
1732
+ data = self._flush()
1733
+ if data:
1734
+ await self._async_outfile.write(data)
1735
+
1736
+ async def write_doctype(self, doctype):
1737
+ self._writer.write_doctype(doctype)
1738
+ data = self._flush()
1739
+ if data:
1740
+ await self._async_outfile.write(data)
1741
+
1742
+ async def write(self, *args, with_tail=True, pretty_print=False, method=None):
1743
+ self._writer.write(*args, with_tail=with_tail, pretty_print=pretty_print, method=method)
1744
+ data = self._flush()
1745
+ if data:
1746
+ await self._async_outfile.write(data)
1747
+
1748
+ def method(self, method):
1749
+ return self._writer.method(method)
1750
+
1751
+ def element(self, tag, attrib=None, nsmap=None, method=None, **_extra):
1752
+ element_writer = self._writer.element(tag, attrib, nsmap, method, **_extra)
1753
+ return _AsyncFileWriterElement(element_writer, self)
1754
+
1755
+ async def _close(self, bint raise_on_error):
1756
+ self._writer._close(raise_on_error)
1757
+ data = self._buffer.collect()
1758
+ if data:
1759
+ await self._async_outfile.write(data)
1760
+ if self._should_close:
1761
+ await self._async_outfile.close()
1762
+
1763
+
1764
+ @cython.final
1765
+ @cython.internal
1766
+ cdef class _AsyncFileWriterElement:
1767
+ cdef _FileWriterElement _element_writer
1768
+ cdef _AsyncIncrementalFileWriter _writer
1769
+
1770
+ def __cinit__(self, _FileWriterElement element_writer not None,
1771
+ _AsyncIncrementalFileWriter writer not None):
1772
+ self._element_writer = element_writer
1773
+ self._writer = writer
1774
+
1775
+ async def __aenter__(self):
1776
+ self._element_writer.__enter__()
1777
+ data = self._writer._flush()
1778
+ if data:
1779
+ await self._writer._async_outfile.write(data)
1780
+
1781
+ async def __aexit__(self, *args):
1782
+ self._element_writer.__exit__(*args)
1783
+ data = self._writer._flush()
1784
+ if data:
1785
+ await self._writer._async_outfile.write(data)
1786
+
1787
+
1788
+ @cython.final
1789
+ @cython.internal
1790
+ @cython.freelist(8)
1791
+ cdef class _FileWriterElement:
1792
+ cdef _IncrementalFileWriter _writer
1793
+ cdef object _element
1794
+ cdef int _new_method
1795
+ cdef int _old_method
1796
+
1797
+ def __cinit__(self, _IncrementalFileWriter writer not None, element_config, int method):
1798
+ self._writer = writer
1799
+ self._element = element_config
1800
+ self._new_method = method
1801
+ self._old_method = writer._method
1802
+
1803
+ def __enter__(self):
1804
+ self._writer._method = self._new_method
1805
+ self._writer._write_start_element(self._element)
1806
+
1807
+ def __exit__(self, exc_type, exc_val, exc_tb):
1808
+ self._writer._write_end_element(self._element)
1809
+ self._writer._method = self._old_method
1810
+
1811
+
1812
+ @cython.final
1813
+ @cython.internal
1814
+ @cython.freelist(8)
1815
+ cdef class _MethodChanger:
1816
+ cdef _IncrementalFileWriter _writer
1817
+ cdef int _new_method
1818
+ cdef int _old_method
1819
+ cdef bint _entered
1820
+ cdef bint _exited
1821
+
1822
+ def __cinit__(self, _IncrementalFileWriter writer not None, int method):
1823
+ self._writer = writer
1824
+ self._new_method = method
1825
+ self._old_method = writer._method
1826
+ self._entered = False
1827
+ self._exited = False
1828
+
1829
+ def __enter__(self):
1830
+ if self._entered:
1831
+ raise LxmlSyntaxError("Inconsistent enter action in context manager")
1832
+ self._writer._method = self._new_method
1833
+ self._entered = True
1834
+
1835
+ def __exit__(self, exc_type, exc_val, exc_tb):
1836
+ if self._exited:
1837
+ raise LxmlSyntaxError("Inconsistent exit action in context manager")
1838
+ if self._writer._method != self._new_method:
1839
+ raise LxmlSyntaxError("Method changed outside of context manager")
1840
+ self._writer._method = self._old_method
1841
+ self._exited = True
1842
+
1843
+ async def __aenter__(self):
1844
+ # for your async convenience
1845
+ return self.__enter__()
1846
+
1847
+ async def __aexit__(self, *args):
1848
+ # for your async convenience
1849
+ return self.__exit__(*args)