applied-ai-018 commited on
Commit
fb271d1
·
verified ·
1 Parent(s): aa5079b

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/17.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step80/zero/17.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step80/zero/17.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  4. venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/__init__.cpython-310.pyc +0 -0
  5. venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/__main__.cpython-310.pyc +0 -0
  6. venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/md.cpython-310.pyc +0 -0
  7. venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/models.cpython-310.pyc +0 -0
  8. venv/lib/python3.10/site-packages/charset_normalizer/api.py +626 -0
  9. venv/lib/python3.10/site-packages/charset_normalizer/cli/__init__.py +6 -0
  10. venv/lib/python3.10/site-packages/charset_normalizer/cli/__main__.py +296 -0
  11. venv/lib/python3.10/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/charset_normalizer/md.py +615 -0
  14. venv/lib/python3.10/site-packages/lxml/ElementInclude.py +244 -0
  15. venv/lib/python3.10/site-packages/lxml/__init__.py +22 -0
  16. venv/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc +0 -0
  22. venv/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/lxml/_elementpath.cpython-310-x86_64-linux-gnu.so +0 -0
  26. venv/lib/python3.10/site-packages/lxml/_elementpath.py +341 -0
  27. venv/lib/python3.10/site-packages/lxml/apihelpers.pxi +1793 -0
  28. venv/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so +0 -0
  29. venv/lib/python3.10/site-packages/lxml/builder.py +232 -0
  30. venv/lib/python3.10/site-packages/lxml/classlookup.pxi +580 -0
  31. venv/lib/python3.10/site-packages/lxml/cleanup.pxi +215 -0
  32. venv/lib/python3.10/site-packages/lxml/cssselect.py +101 -0
  33. venv/lib/python3.10/site-packages/lxml/debug.pxi +90 -0
  34. venv/lib/python3.10/site-packages/lxml/docloader.pxi +178 -0
  35. venv/lib/python3.10/site-packages/lxml/doctestcompare.py +488 -0
  36. venv/lib/python3.10/site-packages/lxml/dtd.pxi +478 -0
  37. venv/lib/python3.10/site-packages/lxml/etree.h +248 -0
  38. venv/lib/python3.10/site-packages/lxml/etree.pyx +0 -0
  39. venv/lib/python3.10/site-packages/lxml/etree_api.h +195 -0
  40. venv/lib/python3.10/site-packages/lxml/extensions.pxi +833 -0
  41. venv/lib/python3.10/site-packages/lxml/includes/htmlparser.pxd +56 -0
  42. venv/lib/python3.10/site-packages/lxml/isoschematron/__init__.py +348 -0
  43. venv/lib/python3.10/site-packages/lxml/isoschematron/__pycache__/__init__.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/lxml/isoschematron/resources/rng/iso-schematron.rng +709 -0
  45. venv/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl +75 -0
  46. venv/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl +77 -0
  47. venv/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl +313 -0
  48. venv/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl +1160 -0
  49. venv/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl +55 -0
  50. venv/lib/python3.10/site-packages/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl +1796 -0
ckpts/universal/global_step80/zero/17.mlp.dense_4h_to_h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c14966b0f04921ae94219d62004ec1c62f2d523c898d261b7dfd320c04b7a3a
3
+ size 33555612
ckpts/universal/global_step80/zero/17.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea24a8ff97ad7b5ffa04fe7f9936715d6ffe0f86852910e638ea7081cf6f58dc
3
+ size 33555627
ckpts/universal/global_step80/zero/17.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77ff49d590025dabe163e59f659355c91bdd03a973214b4554577f2fcbbd4df6
3
+ size 33555533
venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (268 Bytes). View file
 
venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/md.cpython-310.pyc ADDED
Binary file (15.8 kB). View file
 
venv/lib/python3.10/site-packages/charset_normalizer/__pycache__/models.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
venv/lib/python3.10/site-packages/charset_normalizer/api.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from os import PathLike
3
+ from typing import BinaryIO, List, Optional, Set, Union
4
+
5
+ from .cd import (
6
+ coherence_ratio,
7
+ encoding_languages,
8
+ mb_encoding_languages,
9
+ merge_coherence_ratios,
10
+ )
11
+ from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE
12
+ from .md import mess_ratio
13
+ from .models import CharsetMatch, CharsetMatches
14
+ from .utils import (
15
+ any_specified_encoding,
16
+ cut_sequence_chunks,
17
+ iana_name,
18
+ identify_sig_or_bom,
19
+ is_cp_similar,
20
+ is_multi_byte_encoding,
21
+ should_strip_sig_or_bom,
22
+ )
23
+
24
+ # Will most likely be controversial
25
+ # logging.addLevelName(TRACE, "TRACE")
26
+ logger = logging.getLogger("charset_normalizer")
27
+ explain_handler = logging.StreamHandler()
28
+ explain_handler.setFormatter(
29
+ logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
30
+ )
31
+
32
+
33
+ def from_bytes(
34
+ sequences: Union[bytes, bytearray],
35
+ steps: int = 5,
36
+ chunk_size: int = 512,
37
+ threshold: float = 0.2,
38
+ cp_isolation: Optional[List[str]] = None,
39
+ cp_exclusion: Optional[List[str]] = None,
40
+ preemptive_behaviour: bool = True,
41
+ explain: bool = False,
42
+ language_threshold: float = 0.1,
43
+ enable_fallback: bool = True,
44
+ ) -> CharsetMatches:
45
+ """
46
+ Given a raw bytes sequence, return the best possibles charset usable to render str objects.
47
+ If there is no results, it is a strong indicator that the source is binary/not text.
48
+ By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence.
49
+ And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.
50
+
51
+ The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page
52
+ but never take it for granted. Can improve the performance.
53
+
54
+ You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that
55
+ purpose.
56
+
57
+ This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.
58
+ By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'
59
+ toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.
60
+ Custom logging format and handler can be set manually.
61
+ """
62
+
63
+ if not isinstance(sequences, (bytearray, bytes)):
64
+ raise TypeError(
65
+ "Expected object of type bytes or bytearray, got: {0}".format(
66
+ type(sequences)
67
+ )
68
+ )
69
+
70
+ if explain:
71
+ previous_logger_level: int = logger.level
72
+ logger.addHandler(explain_handler)
73
+ logger.setLevel(TRACE)
74
+
75
+ length: int = len(sequences)
76
+
77
+ if length == 0:
78
+ logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.")
79
+ if explain:
80
+ logger.removeHandler(explain_handler)
81
+ logger.setLevel(previous_logger_level or logging.WARNING)
82
+ return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
83
+
84
+ if cp_isolation is not None:
85
+ logger.log(
86
+ TRACE,
87
+ "cp_isolation is set. use this flag for debugging purpose. "
88
+ "limited list of encoding allowed : %s.",
89
+ ", ".join(cp_isolation),
90
+ )
91
+ cp_isolation = [iana_name(cp, False) for cp in cp_isolation]
92
+ else:
93
+ cp_isolation = []
94
+
95
+ if cp_exclusion is not None:
96
+ logger.log(
97
+ TRACE,
98
+ "cp_exclusion is set. use this flag for debugging purpose. "
99
+ "limited list of encoding excluded : %s.",
100
+ ", ".join(cp_exclusion),
101
+ )
102
+ cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion]
103
+ else:
104
+ cp_exclusion = []
105
+
106
+ if length <= (chunk_size * steps):
107
+ logger.log(
108
+ TRACE,
109
+ "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.",
110
+ steps,
111
+ chunk_size,
112
+ length,
113
+ )
114
+ steps = 1
115
+ chunk_size = length
116
+
117
+ if steps > 1 and length / steps < chunk_size:
118
+ chunk_size = int(length / steps)
119
+
120
+ is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE
121
+ is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE
122
+
123
+ if is_too_small_sequence:
124
+ logger.log(
125
+ TRACE,
126
+ "Trying to detect encoding from a tiny portion of ({}) byte(s).".format(
127
+ length
128
+ ),
129
+ )
130
+ elif is_too_large_sequence:
131
+ logger.log(
132
+ TRACE,
133
+ "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format(
134
+ length
135
+ ),
136
+ )
137
+
138
+ prioritized_encodings: List[str] = []
139
+
140
+ specified_encoding: Optional[str] = (
141
+ any_specified_encoding(sequences) if preemptive_behaviour else None
142
+ )
143
+
144
+ if specified_encoding is not None:
145
+ prioritized_encodings.append(specified_encoding)
146
+ logger.log(
147
+ TRACE,
148
+ "Detected declarative mark in sequence. Priority +1 given for %s.",
149
+ specified_encoding,
150
+ )
151
+
152
+ tested: Set[str] = set()
153
+ tested_but_hard_failure: List[str] = []
154
+ tested_but_soft_failure: List[str] = []
155
+
156
+ fallback_ascii: Optional[CharsetMatch] = None
157
+ fallback_u8: Optional[CharsetMatch] = None
158
+ fallback_specified: Optional[CharsetMatch] = None
159
+
160
+ results: CharsetMatches = CharsetMatches()
161
+
162
+ sig_encoding, sig_payload = identify_sig_or_bom(sequences)
163
+
164
+ if sig_encoding is not None:
165
+ prioritized_encodings.append(sig_encoding)
166
+ logger.log(
167
+ TRACE,
168
+ "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.",
169
+ len(sig_payload),
170
+ sig_encoding,
171
+ )
172
+
173
+ prioritized_encodings.append("ascii")
174
+
175
+ if "utf_8" not in prioritized_encodings:
176
+ prioritized_encodings.append("utf_8")
177
+
178
+ for encoding_iana in prioritized_encodings + IANA_SUPPORTED:
179
+ if cp_isolation and encoding_iana not in cp_isolation:
180
+ continue
181
+
182
+ if cp_exclusion and encoding_iana in cp_exclusion:
183
+ continue
184
+
185
+ if encoding_iana in tested:
186
+ continue
187
+
188
+ tested.add(encoding_iana)
189
+
190
+ decoded_payload: Optional[str] = None
191
+ bom_or_sig_available: bool = sig_encoding == encoding_iana
192
+ strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom(
193
+ encoding_iana
194
+ )
195
+
196
+ if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available:
197
+ logger.log(
198
+ TRACE,
199
+ "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.",
200
+ encoding_iana,
201
+ )
202
+ continue
203
+ if encoding_iana in {"utf_7"} and not bom_or_sig_available:
204
+ logger.log(
205
+ TRACE,
206
+ "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.",
207
+ encoding_iana,
208
+ )
209
+ continue
210
+
211
+ try:
212
+ is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana)
213
+ except (ModuleNotFoundError, ImportError):
214
+ logger.log(
215
+ TRACE,
216
+ "Encoding %s does not provide an IncrementalDecoder",
217
+ encoding_iana,
218
+ )
219
+ continue
220
+
221
+ try:
222
+ if is_too_large_sequence and is_multi_byte_decoder is False:
223
+ str(
224
+ sequences[: int(50e4)]
225
+ if strip_sig_or_bom is False
226
+ else sequences[len(sig_payload) : int(50e4)],
227
+ encoding=encoding_iana,
228
+ )
229
+ else:
230
+ decoded_payload = str(
231
+ sequences
232
+ if strip_sig_or_bom is False
233
+ else sequences[len(sig_payload) :],
234
+ encoding=encoding_iana,
235
+ )
236
+ except (UnicodeDecodeError, LookupError) as e:
237
+ if not isinstance(e, LookupError):
238
+ logger.log(
239
+ TRACE,
240
+ "Code page %s does not fit given bytes sequence at ALL. %s",
241
+ encoding_iana,
242
+ str(e),
243
+ )
244
+ tested_but_hard_failure.append(encoding_iana)
245
+ continue
246
+
247
+ similar_soft_failure_test: bool = False
248
+
249
+ for encoding_soft_failed in tested_but_soft_failure:
250
+ if is_cp_similar(encoding_iana, encoding_soft_failed):
251
+ similar_soft_failure_test = True
252
+ break
253
+
254
+ if similar_soft_failure_test:
255
+ logger.log(
256
+ TRACE,
257
+ "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!",
258
+ encoding_iana,
259
+ encoding_soft_failed,
260
+ )
261
+ continue
262
+
263
+ r_ = range(
264
+ 0 if not bom_or_sig_available else len(sig_payload),
265
+ length,
266
+ int(length / steps),
267
+ )
268
+
269
+ multi_byte_bonus: bool = (
270
+ is_multi_byte_decoder
271
+ and decoded_payload is not None
272
+ and len(decoded_payload) < length
273
+ )
274
+
275
+ if multi_byte_bonus:
276
+ logger.log(
277
+ TRACE,
278
+ "Code page %s is a multi byte encoding table and it appear that at least one character "
279
+ "was encoded using n-bytes.",
280
+ encoding_iana,
281
+ )
282
+
283
+ max_chunk_gave_up: int = int(len(r_) / 4)
284
+
285
+ max_chunk_gave_up = max(max_chunk_gave_up, 2)
286
+ early_stop_count: int = 0
287
+ lazy_str_hard_failure = False
288
+
289
+ md_chunks: List[str] = []
290
+ md_ratios = []
291
+
292
+ try:
293
+ for chunk in cut_sequence_chunks(
294
+ sequences,
295
+ encoding_iana,
296
+ r_,
297
+ chunk_size,
298
+ bom_or_sig_available,
299
+ strip_sig_or_bom,
300
+ sig_payload,
301
+ is_multi_byte_decoder,
302
+ decoded_payload,
303
+ ):
304
+ md_chunks.append(chunk)
305
+
306
+ md_ratios.append(
307
+ mess_ratio(
308
+ chunk,
309
+ threshold,
310
+ explain is True and 1 <= len(cp_isolation) <= 2,
311
+ )
312
+ )
313
+
314
+ if md_ratios[-1] >= threshold:
315
+ early_stop_count += 1
316
+
317
+ if (early_stop_count >= max_chunk_gave_up) or (
318
+ bom_or_sig_available and strip_sig_or_bom is False
319
+ ):
320
+ break
321
+ except (
322
+ UnicodeDecodeError
323
+ ) as e: # Lazy str loading may have missed something there
324
+ logger.log(
325
+ TRACE,
326
+ "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s",
327
+ encoding_iana,
328
+ str(e),
329
+ )
330
+ early_stop_count = max_chunk_gave_up
331
+ lazy_str_hard_failure = True
332
+
333
+ # We might want to check the sequence again with the whole content
334
+ # Only if initial MD tests passes
335
+ if (
336
+ not lazy_str_hard_failure
337
+ and is_too_large_sequence
338
+ and not is_multi_byte_decoder
339
+ ):
340
+ try:
341
+ sequences[int(50e3) :].decode(encoding_iana, errors="strict")
342
+ except UnicodeDecodeError as e:
343
+ logger.log(
344
+ TRACE,
345
+ "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s",
346
+ encoding_iana,
347
+ str(e),
348
+ )
349
+ tested_but_hard_failure.append(encoding_iana)
350
+ continue
351
+
352
+ mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0
353
+ if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up:
354
+ tested_but_soft_failure.append(encoding_iana)
355
+ logger.log(
356
+ TRACE,
357
+ "%s was excluded because of initial chaos probing. Gave up %i time(s). "
358
+ "Computed mean chaos is %f %%.",
359
+ encoding_iana,
360
+ early_stop_count,
361
+ round(mean_mess_ratio * 100, ndigits=3),
362
+ )
363
+ # Preparing those fallbacks in case we got nothing.
364
+ if (
365
+ enable_fallback
366
+ and encoding_iana in ["ascii", "utf_8", specified_encoding]
367
+ and not lazy_str_hard_failure
368
+ ):
369
+ fallback_entry = CharsetMatch(
370
+ sequences, encoding_iana, threshold, False, [], decoded_payload
371
+ )
372
+ if encoding_iana == specified_encoding:
373
+ fallback_specified = fallback_entry
374
+ elif encoding_iana == "ascii":
375
+ fallback_ascii = fallback_entry
376
+ else:
377
+ fallback_u8 = fallback_entry
378
+ continue
379
+
380
+ logger.log(
381
+ TRACE,
382
+ "%s passed initial chaos probing. Mean measured chaos is %f %%",
383
+ encoding_iana,
384
+ round(mean_mess_ratio * 100, ndigits=3),
385
+ )
386
+
387
+ if not is_multi_byte_decoder:
388
+ target_languages: List[str] = encoding_languages(encoding_iana)
389
+ else:
390
+ target_languages = mb_encoding_languages(encoding_iana)
391
+
392
+ if target_languages:
393
+ logger.log(
394
+ TRACE,
395
+ "{} should target any language(s) of {}".format(
396
+ encoding_iana, str(target_languages)
397
+ ),
398
+ )
399
+
400
+ cd_ratios = []
401
+
402
+ # We shall skip the CD when its about ASCII
403
+ # Most of the time its not relevant to run "language-detection" on it.
404
+ if encoding_iana != "ascii":
405
+ for chunk in md_chunks:
406
+ chunk_languages = coherence_ratio(
407
+ chunk,
408
+ language_threshold,
409
+ ",".join(target_languages) if target_languages else None,
410
+ )
411
+
412
+ cd_ratios.append(chunk_languages)
413
+
414
+ cd_ratios_merged = merge_coherence_ratios(cd_ratios)
415
+
416
+ if cd_ratios_merged:
417
+ logger.log(
418
+ TRACE,
419
+ "We detected language {} using {}".format(
420
+ cd_ratios_merged, encoding_iana
421
+ ),
422
+ )
423
+
424
+ results.append(
425
+ CharsetMatch(
426
+ sequences,
427
+ encoding_iana,
428
+ mean_mess_ratio,
429
+ bom_or_sig_available,
430
+ cd_ratios_merged,
431
+ decoded_payload,
432
+ )
433
+ )
434
+
435
+ if (
436
+ encoding_iana in [specified_encoding, "ascii", "utf_8"]
437
+ and mean_mess_ratio < 0.1
438
+ ):
439
+ logger.debug(
440
+ "Encoding detection: %s is most likely the one.", encoding_iana
441
+ )
442
+ if explain:
443
+ logger.removeHandler(explain_handler)
444
+ logger.setLevel(previous_logger_level)
445
+ return CharsetMatches([results[encoding_iana]])
446
+
447
+ if encoding_iana == sig_encoding:
448
+ logger.debug(
449
+ "Encoding detection: %s is most likely the one as we detected a BOM or SIG within "
450
+ "the beginning of the sequence.",
451
+ encoding_iana,
452
+ )
453
+ if explain:
454
+ logger.removeHandler(explain_handler)
455
+ logger.setLevel(previous_logger_level)
456
+ return CharsetMatches([results[encoding_iana]])
457
+
458
+ if len(results) == 0:
459
+ if fallback_u8 or fallback_ascii or fallback_specified:
460
+ logger.log(
461
+ TRACE,
462
+ "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.",
463
+ )
464
+
465
+ if fallback_specified:
466
+ logger.debug(
467
+ "Encoding detection: %s will be used as a fallback match",
468
+ fallback_specified.encoding,
469
+ )
470
+ results.append(fallback_specified)
471
+ elif (
472
+ (fallback_u8 and fallback_ascii is None)
473
+ or (
474
+ fallback_u8
475
+ and fallback_ascii
476
+ and fallback_u8.fingerprint != fallback_ascii.fingerprint
477
+ )
478
+ or (fallback_u8 is not None)
479
+ ):
480
+ logger.debug("Encoding detection: utf_8 will be used as a fallback match")
481
+ results.append(fallback_u8)
482
+ elif fallback_ascii:
483
+ logger.debug("Encoding detection: ascii will be used as a fallback match")
484
+ results.append(fallback_ascii)
485
+
486
+ if results:
487
+ logger.debug(
488
+ "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.",
489
+ results.best().encoding, # type: ignore
490
+ len(results) - 1,
491
+ )
492
+ else:
493
+ logger.debug("Encoding detection: Unable to determine any suitable charset.")
494
+
495
+ if explain:
496
+ logger.removeHandler(explain_handler)
497
+ logger.setLevel(previous_logger_level)
498
+
499
+ return results
500
+
501
+
502
+ def from_fp(
503
+ fp: BinaryIO,
504
+ steps: int = 5,
505
+ chunk_size: int = 512,
506
+ threshold: float = 0.20,
507
+ cp_isolation: Optional[List[str]] = None,
508
+ cp_exclusion: Optional[List[str]] = None,
509
+ preemptive_behaviour: bool = True,
510
+ explain: bool = False,
511
+ language_threshold: float = 0.1,
512
+ enable_fallback: bool = True,
513
+ ) -> CharsetMatches:
514
+ """
515
+ Same thing than the function from_bytes but using a file pointer that is already ready.
516
+ Will not close the file pointer.
517
+ """
518
+ return from_bytes(
519
+ fp.read(),
520
+ steps,
521
+ chunk_size,
522
+ threshold,
523
+ cp_isolation,
524
+ cp_exclusion,
525
+ preemptive_behaviour,
526
+ explain,
527
+ language_threshold,
528
+ enable_fallback,
529
+ )
530
+
531
+
532
+ def from_path(
533
+ path: Union[str, bytes, PathLike], # type: ignore[type-arg]
534
+ steps: int = 5,
535
+ chunk_size: int = 512,
536
+ threshold: float = 0.20,
537
+ cp_isolation: Optional[List[str]] = None,
538
+ cp_exclusion: Optional[List[str]] = None,
539
+ preemptive_behaviour: bool = True,
540
+ explain: bool = False,
541
+ language_threshold: float = 0.1,
542
+ enable_fallback: bool = True,
543
+ ) -> CharsetMatches:
544
+ """
545
+ Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode.
546
+ Can raise IOError.
547
+ """
548
+ with open(path, "rb") as fp:
549
+ return from_fp(
550
+ fp,
551
+ steps,
552
+ chunk_size,
553
+ threshold,
554
+ cp_isolation,
555
+ cp_exclusion,
556
+ preemptive_behaviour,
557
+ explain,
558
+ language_threshold,
559
+ enable_fallback,
560
+ )
561
+
562
+
563
+ def is_binary(
564
+ fp_or_path_or_payload: Union[PathLike, str, BinaryIO, bytes], # type: ignore[type-arg]
565
+ steps: int = 5,
566
+ chunk_size: int = 512,
567
+ threshold: float = 0.20,
568
+ cp_isolation: Optional[List[str]] = None,
569
+ cp_exclusion: Optional[List[str]] = None,
570
+ preemptive_behaviour: bool = True,
571
+ explain: bool = False,
572
+ language_threshold: float = 0.1,
573
+ enable_fallback: bool = False,
574
+ ) -> bool:
575
+ """
576
+ Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string.
577
+ Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match
578
+ are disabled to be stricter around ASCII-compatible but unlikely to be a string.
579
+ """
580
+ if isinstance(fp_or_path_or_payload, (str, PathLike)):
581
+ guesses = from_path(
582
+ fp_or_path_or_payload,
583
+ steps=steps,
584
+ chunk_size=chunk_size,
585
+ threshold=threshold,
586
+ cp_isolation=cp_isolation,
587
+ cp_exclusion=cp_exclusion,
588
+ preemptive_behaviour=preemptive_behaviour,
589
+ explain=explain,
590
+ language_threshold=language_threshold,
591
+ enable_fallback=enable_fallback,
592
+ )
593
+ elif isinstance(
594
+ fp_or_path_or_payload,
595
+ (
596
+ bytes,
597
+ bytearray,
598
+ ),
599
+ ):
600
+ guesses = from_bytes(
601
+ fp_or_path_or_payload,
602
+ steps=steps,
603
+ chunk_size=chunk_size,
604
+ threshold=threshold,
605
+ cp_isolation=cp_isolation,
606
+ cp_exclusion=cp_exclusion,
607
+ preemptive_behaviour=preemptive_behaviour,
608
+ explain=explain,
609
+ language_threshold=language_threshold,
610
+ enable_fallback=enable_fallback,
611
+ )
612
+ else:
613
+ guesses = from_fp(
614
+ fp_or_path_or_payload,
615
+ steps=steps,
616
+ chunk_size=chunk_size,
617
+ threshold=threshold,
618
+ cp_isolation=cp_isolation,
619
+ cp_exclusion=cp_exclusion,
620
+ preemptive_behaviour=preemptive_behaviour,
621
+ explain=explain,
622
+ language_threshold=language_threshold,
623
+ enable_fallback=enable_fallback,
624
+ )
625
+
626
+ return not guesses
venv/lib/python3.10/site-packages/charset_normalizer/cli/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .__main__ import cli_detect, query_yes_no
2
+
3
+ __all__ = (
4
+ "cli_detect",
5
+ "query_yes_no",
6
+ )
venv/lib/python3.10/site-packages/charset_normalizer/cli/__main__.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+ from json import dumps
4
+ from os.path import abspath, basename, dirname, join, realpath
5
+ from platform import python_version
6
+ from typing import List, Optional
7
+ from unicodedata import unidata_version
8
+
9
+ import charset_normalizer.md as md_module
10
+ from charset_normalizer import from_fp
11
+ from charset_normalizer.models import CliDetectionResult
12
+ from charset_normalizer.version import __version__
13
+
14
+
15
+ def query_yes_no(question: str, default: str = "yes") -> bool:
16
+ """Ask a yes/no question via input() and return their answer.
17
+
18
+ "question" is a string that is presented to the user.
19
+ "default" is the presumed answer if the user just hits <Enter>.
20
+ It must be "yes" (the default), "no" or None (meaning
21
+ an answer is required of the user).
22
+
23
+ The "answer" return value is True for "yes" or False for "no".
24
+
25
+ Credit goes to (c) https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input
26
+ """
27
+ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
28
+ if default is None:
29
+ prompt = " [y/n] "
30
+ elif default == "yes":
31
+ prompt = " [Y/n] "
32
+ elif default == "no":
33
+ prompt = " [y/N] "
34
+ else:
35
+ raise ValueError("invalid default answer: '%s'" % default)
36
+
37
+ while True:
38
+ sys.stdout.write(question + prompt)
39
+ choice = input().lower()
40
+ if default is not None and choice == "":
41
+ return valid[default]
42
+ elif choice in valid:
43
+ return valid[choice]
44
+ else:
45
+ sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
46
+
47
+
48
+ def cli_detect(argv: Optional[List[str]] = None) -> int:
49
+ """
50
+ CLI assistant using ARGV and ArgumentParser
51
+ :param argv:
52
+ :return: 0 if everything is fine, anything else equal trouble
53
+ """
54
+ parser = argparse.ArgumentParser(
55
+ description="The Real First Universal Charset Detector. "
56
+ "Discover originating encoding used on text file. "
57
+ "Normalize text to unicode."
58
+ )
59
+
60
+ parser.add_argument(
61
+ "files", type=argparse.FileType("rb"), nargs="+", help="File(s) to be analysed"
62
+ )
63
+ parser.add_argument(
64
+ "-v",
65
+ "--verbose",
66
+ action="store_true",
67
+ default=False,
68
+ dest="verbose",
69
+ help="Display complementary information about file if any. "
70
+ "Stdout will contain logs about the detection process.",
71
+ )
72
+ parser.add_argument(
73
+ "-a",
74
+ "--with-alternative",
75
+ action="store_true",
76
+ default=False,
77
+ dest="alternatives",
78
+ help="Output complementary possibilities if any. Top-level JSON WILL be a list.",
79
+ )
80
+ parser.add_argument(
81
+ "-n",
82
+ "--normalize",
83
+ action="store_true",
84
+ default=False,
85
+ dest="normalize",
86
+ help="Permit to normalize input file. If not set, program does not write anything.",
87
+ )
88
+ parser.add_argument(
89
+ "-m",
90
+ "--minimal",
91
+ action="store_true",
92
+ default=False,
93
+ dest="minimal",
94
+ help="Only output the charset detected to STDOUT. Disabling JSON output.",
95
+ )
96
+ parser.add_argument(
97
+ "-r",
98
+ "--replace",
99
+ action="store_true",
100
+ default=False,
101
+ dest="replace",
102
+ help="Replace file when trying to normalize it instead of creating a new one.",
103
+ )
104
+ parser.add_argument(
105
+ "-f",
106
+ "--force",
107
+ action="store_true",
108
+ default=False,
109
+ dest="force",
110
+ help="Replace file without asking if you are sure, use this flag with caution.",
111
+ )
112
+ parser.add_argument(
113
+ "-t",
114
+ "--threshold",
115
+ action="store",
116
+ default=0.2,
117
+ type=float,
118
+ dest="threshold",
119
+ help="Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1.",
120
+ )
121
+ parser.add_argument(
122
+ "--version",
123
+ action="version",
124
+ version="Charset-Normalizer {} - Python {} - Unicode {} - SpeedUp {}".format(
125
+ __version__,
126
+ python_version(),
127
+ unidata_version,
128
+ "OFF" if md_module.__file__.lower().endswith(".py") else "ON",
129
+ ),
130
+ help="Show version information and exit.",
131
+ )
132
+
133
+ args = parser.parse_args(argv)
134
+
135
+ if args.replace is True and args.normalize is False:
136
+ print("Use --replace in addition of --normalize only.", file=sys.stderr)
137
+ return 1
138
+
139
+ if args.force is True and args.replace is False:
140
+ print("Use --force in addition of --replace only.", file=sys.stderr)
141
+ return 1
142
+
143
+ if args.threshold < 0.0 or args.threshold > 1.0:
144
+ print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr)
145
+ return 1
146
+
147
+ x_ = []
148
+
149
+ for my_file in args.files:
150
+ matches = from_fp(my_file, threshold=args.threshold, explain=args.verbose)
151
+
152
+ best_guess = matches.best()
153
+
154
+ if best_guess is None:
155
+ print(
156
+ 'Unable to identify originating encoding for "{}". {}'.format(
157
+ my_file.name,
158
+ "Maybe try increasing maximum amount of chaos."
159
+ if args.threshold < 1.0
160
+ else "",
161
+ ),
162
+ file=sys.stderr,
163
+ )
164
+ x_.append(
165
+ CliDetectionResult(
166
+ abspath(my_file.name),
167
+ None,
168
+ [],
169
+ [],
170
+ "Unknown",
171
+ [],
172
+ False,
173
+ 1.0,
174
+ 0.0,
175
+ None,
176
+ True,
177
+ )
178
+ )
179
+ else:
180
+ x_.append(
181
+ CliDetectionResult(
182
+ abspath(my_file.name),
183
+ best_guess.encoding,
184
+ best_guess.encoding_aliases,
185
+ [
186
+ cp
187
+ for cp in best_guess.could_be_from_charset
188
+ if cp != best_guess.encoding
189
+ ],
190
+ best_guess.language,
191
+ best_guess.alphabets,
192
+ best_guess.bom,
193
+ best_guess.percent_chaos,
194
+ best_guess.percent_coherence,
195
+ None,
196
+ True,
197
+ )
198
+ )
199
+
200
+ if len(matches) > 1 and args.alternatives:
201
+ for el in matches:
202
+ if el != best_guess:
203
+ x_.append(
204
+ CliDetectionResult(
205
+ abspath(my_file.name),
206
+ el.encoding,
207
+ el.encoding_aliases,
208
+ [
209
+ cp
210
+ for cp in el.could_be_from_charset
211
+ if cp != el.encoding
212
+ ],
213
+ el.language,
214
+ el.alphabets,
215
+ el.bom,
216
+ el.percent_chaos,
217
+ el.percent_coherence,
218
+ None,
219
+ False,
220
+ )
221
+ )
222
+
223
+ if args.normalize is True:
224
+ if best_guess.encoding.startswith("utf") is True:
225
+ print(
226
+ '"{}" file does not need to be normalized, as it already came from unicode.'.format(
227
+ my_file.name
228
+ ),
229
+ file=sys.stderr,
230
+ )
231
+ if my_file.closed is False:
232
+ my_file.close()
233
+ continue
234
+
235
+ dir_path = dirname(realpath(my_file.name))
236
+ file_name = basename(realpath(my_file.name))
237
+
238
+ o_: List[str] = file_name.split(".")
239
+
240
+ if args.replace is False:
241
+ o_.insert(-1, best_guess.encoding)
242
+ if my_file.closed is False:
243
+ my_file.close()
244
+ elif (
245
+ args.force is False
246
+ and query_yes_no(
247
+ 'Are you sure to normalize "{}" by replacing it ?'.format(
248
+ my_file.name
249
+ ),
250
+ "no",
251
+ )
252
+ is False
253
+ ):
254
+ if my_file.closed is False:
255
+ my_file.close()
256
+ continue
257
+
258
+ try:
259
+ x_[0].unicode_path = join(dir_path, ".".join(o_))
260
+
261
+ with open(x_[0].unicode_path, "w", encoding="utf-8") as fp:
262
+ fp.write(str(best_guess))
263
+ except IOError as e:
264
+ print(str(e), file=sys.stderr)
265
+ if my_file.closed is False:
266
+ my_file.close()
267
+ return 2
268
+
269
+ if my_file.closed is False:
270
+ my_file.close()
271
+
272
+ if args.minimal is False:
273
+ print(
274
+ dumps(
275
+ [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__,
276
+ ensure_ascii=True,
277
+ indent=4,
278
+ )
279
+ )
280
+ else:
281
+ for my_file in args.files:
282
+ print(
283
+ ", ".join(
284
+ [
285
+ el.encoding or "undefined"
286
+ for el in x_
287
+ if el.path == abspath(my_file.name)
288
+ ]
289
+ )
290
+ )
291
+
292
+ return 0
293
+
294
+
295
+ if __name__ == "__main__":
296
+ cli_detect()
venv/lib/python3.10/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (271 Bytes). View file
 
venv/lib/python3.10/site-packages/charset_normalizer/cli/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (6.46 kB). View file
 
venv/lib/python3.10/site-packages/charset_normalizer/md.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from logging import getLogger
3
+ from typing import List, Optional
4
+
5
+ from .constant import (
6
+ COMMON_SAFE_ASCII_CHARACTERS,
7
+ TRACE,
8
+ UNICODE_SECONDARY_RANGE_KEYWORD,
9
+ )
10
+ from .utils import (
11
+ is_accentuated,
12
+ is_arabic,
13
+ is_arabic_isolated_form,
14
+ is_case_variable,
15
+ is_cjk,
16
+ is_emoticon,
17
+ is_hangul,
18
+ is_hiragana,
19
+ is_katakana,
20
+ is_latin,
21
+ is_punctuation,
22
+ is_separator,
23
+ is_symbol,
24
+ is_thai,
25
+ is_unprintable,
26
+ remove_accent,
27
+ unicode_range,
28
+ )
29
+
30
+
31
+ class MessDetectorPlugin:
32
+ """
33
+ Base abstract class used for mess detection plugins.
34
+ All detectors MUST extend and implement given methods.
35
+ """
36
+
37
+ def eligible(self, character: str) -> bool:
38
+ """
39
+ Determine if given character should be fed in.
40
+ """
41
+ raise NotImplementedError # pragma: nocover
42
+
43
+ def feed(self, character: str) -> None:
44
+ """
45
+ The main routine to be executed upon character.
46
+ Insert the logic in witch the text would be considered chaotic.
47
+ """
48
+ raise NotImplementedError # pragma: nocover
49
+
50
+ def reset(self) -> None: # pragma: no cover
51
+ """
52
+ Permit to reset the plugin to the initial state.
53
+ """
54
+ raise NotImplementedError
55
+
56
+ @property
57
+ def ratio(self) -> float:
58
+ """
59
+ Compute the chaos ratio based on what your feed() has seen.
60
+ Must NOT be lower than 0.; No restriction gt 0.
61
+ """
62
+ raise NotImplementedError # pragma: nocover
63
+
64
+
65
+ class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
66
+ def __init__(self) -> None:
67
+ self._punctuation_count: int = 0
68
+ self._symbol_count: int = 0
69
+ self._character_count: int = 0
70
+
71
+ self._last_printable_char: Optional[str] = None
72
+ self._frenzy_symbol_in_word: bool = False
73
+
74
+ def eligible(self, character: str) -> bool:
75
+ return character.isprintable()
76
+
77
+ def feed(self, character: str) -> None:
78
+ self._character_count += 1
79
+
80
+ if (
81
+ character != self._last_printable_char
82
+ and character not in COMMON_SAFE_ASCII_CHARACTERS
83
+ ):
84
+ if is_punctuation(character):
85
+ self._punctuation_count += 1
86
+ elif (
87
+ character.isdigit() is False
88
+ and is_symbol(character)
89
+ and is_emoticon(character) is False
90
+ ):
91
+ self._symbol_count += 2
92
+
93
+ self._last_printable_char = character
94
+
95
+ def reset(self) -> None: # pragma: no cover
96
+ self._punctuation_count = 0
97
+ self._character_count = 0
98
+ self._symbol_count = 0
99
+
100
+ @property
101
+ def ratio(self) -> float:
102
+ if self._character_count == 0:
103
+ return 0.0
104
+
105
+ ratio_of_punctuation: float = (
106
+ self._punctuation_count + self._symbol_count
107
+ ) / self._character_count
108
+
109
+ return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
110
+
111
+
112
+ class TooManyAccentuatedPlugin(MessDetectorPlugin):
113
+ def __init__(self) -> None:
114
+ self._character_count: int = 0
115
+ self._accentuated_count: int = 0
116
+
117
+ def eligible(self, character: str) -> bool:
118
+ return character.isalpha()
119
+
120
+ def feed(self, character: str) -> None:
121
+ self._character_count += 1
122
+
123
+ if is_accentuated(character):
124
+ self._accentuated_count += 1
125
+
126
+ def reset(self) -> None: # pragma: no cover
127
+ self._character_count = 0
128
+ self._accentuated_count = 0
129
+
130
+ @property
131
+ def ratio(self) -> float:
132
+ if self._character_count < 8:
133
+ return 0.0
134
+
135
+ ratio_of_accentuation: float = self._accentuated_count / self._character_count
136
+ return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
137
+
138
+
139
+ class UnprintablePlugin(MessDetectorPlugin):
140
+ def __init__(self) -> None:
141
+ self._unprintable_count: int = 0
142
+ self._character_count: int = 0
143
+
144
+ def eligible(self, character: str) -> bool:
145
+ return True
146
+
147
+ def feed(self, character: str) -> None:
148
+ if is_unprintable(character):
149
+ self._unprintable_count += 1
150
+ self._character_count += 1
151
+
152
+ def reset(self) -> None: # pragma: no cover
153
+ self._unprintable_count = 0
154
+
155
+ @property
156
+ def ratio(self) -> float:
157
+ if self._character_count == 0:
158
+ return 0.0
159
+
160
+ return (self._unprintable_count * 8) / self._character_count
161
+
162
+
163
+ class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
164
+ def __init__(self) -> None:
165
+ self._successive_count: int = 0
166
+ self._character_count: int = 0
167
+
168
+ self._last_latin_character: Optional[str] = None
169
+
170
+ def eligible(self, character: str) -> bool:
171
+ return character.isalpha() and is_latin(character)
172
+
173
+ def feed(self, character: str) -> None:
174
+ self._character_count += 1
175
+ if (
176
+ self._last_latin_character is not None
177
+ and is_accentuated(character)
178
+ and is_accentuated(self._last_latin_character)
179
+ ):
180
+ if character.isupper() and self._last_latin_character.isupper():
181
+ self._successive_count += 1
182
+ # Worse if its the same char duplicated with different accent.
183
+ if remove_accent(character) == remove_accent(self._last_latin_character):
184
+ self._successive_count += 1
185
+ self._last_latin_character = character
186
+
187
+ def reset(self) -> None: # pragma: no cover
188
+ self._successive_count = 0
189
+ self._character_count = 0
190
+ self._last_latin_character = None
191
+
192
+ @property
193
+ def ratio(self) -> float:
194
+ if self._character_count == 0:
195
+ return 0.0
196
+
197
+ return (self._successive_count * 2) / self._character_count
198
+
199
+
200
+ class SuspiciousRange(MessDetectorPlugin):
201
+ def __init__(self) -> None:
202
+ self._suspicious_successive_range_count: int = 0
203
+ self._character_count: int = 0
204
+ self._last_printable_seen: Optional[str] = None
205
+
206
+ def eligible(self, character: str) -> bool:
207
+ return character.isprintable()
208
+
209
+ def feed(self, character: str) -> None:
210
+ self._character_count += 1
211
+
212
+ if (
213
+ character.isspace()
214
+ or is_punctuation(character)
215
+ or character in COMMON_SAFE_ASCII_CHARACTERS
216
+ ):
217
+ self._last_printable_seen = None
218
+ return
219
+
220
+ if self._last_printable_seen is None:
221
+ self._last_printable_seen = character
222
+ return
223
+
224
+ unicode_range_a: Optional[str] = unicode_range(self._last_printable_seen)
225
+ unicode_range_b: Optional[str] = unicode_range(character)
226
+
227
+ if is_suspiciously_successive_range(unicode_range_a, unicode_range_b):
228
+ self._suspicious_successive_range_count += 1
229
+
230
+ self._last_printable_seen = character
231
+
232
+ def reset(self) -> None: # pragma: no cover
233
+ self._character_count = 0
234
+ self._suspicious_successive_range_count = 0
235
+ self._last_printable_seen = None
236
+
237
+ @property
238
+ def ratio(self) -> float:
239
+ if self._character_count <= 24:
240
+ return 0.0
241
+
242
+ ratio_of_suspicious_range_usage: float = (
243
+ self._suspicious_successive_range_count * 2
244
+ ) / self._character_count
245
+
246
+ return ratio_of_suspicious_range_usage
247
+
248
+
249
+ class SuperWeirdWordPlugin(MessDetectorPlugin):
250
+ def __init__(self) -> None:
251
+ self._word_count: int = 0
252
+ self._bad_word_count: int = 0
253
+ self._foreign_long_count: int = 0
254
+
255
+ self._is_current_word_bad: bool = False
256
+ self._foreign_long_watch: bool = False
257
+
258
+ self._character_count: int = 0
259
+ self._bad_character_count: int = 0
260
+
261
+ self._buffer: str = ""
262
+ self._buffer_accent_count: int = 0
263
+
264
+ def eligible(self, character: str) -> bool:
265
+ return True
266
+
267
+ def feed(self, character: str) -> None:
268
+ if character.isalpha():
269
+ self._buffer += character
270
+ if is_accentuated(character):
271
+ self._buffer_accent_count += 1
272
+ if (
273
+ self._foreign_long_watch is False
274
+ and (is_latin(character) is False or is_accentuated(character))
275
+ and is_cjk(character) is False
276
+ and is_hangul(character) is False
277
+ and is_katakana(character) is False
278
+ and is_hiragana(character) is False
279
+ and is_thai(character) is False
280
+ ):
281
+ self._foreign_long_watch = True
282
+ return
283
+ if not self._buffer:
284
+ return
285
+ if (
286
+ character.isspace() or is_punctuation(character) or is_separator(character)
287
+ ) and self._buffer:
288
+ self._word_count += 1
289
+ buffer_length: int = len(self._buffer)
290
+
291
+ self._character_count += buffer_length
292
+
293
+ if buffer_length >= 4:
294
+ if self._buffer_accent_count / buffer_length > 0.34:
295
+ self._is_current_word_bad = True
296
+ # Word/Buffer ending with an upper case accentuated letter are so rare,
297
+ # that we will consider them all as suspicious. Same weight as foreign_long suspicious.
298
+ if (
299
+ is_accentuated(self._buffer[-1])
300
+ and self._buffer[-1].isupper()
301
+ and all(_.isupper() for _ in self._buffer) is False
302
+ ):
303
+ self._foreign_long_count += 1
304
+ self._is_current_word_bad = True
305
+ if buffer_length >= 24 and self._foreign_long_watch:
306
+ camel_case_dst = [
307
+ i
308
+ for c, i in zip(self._buffer, range(0, buffer_length))
309
+ if c.isupper()
310
+ ]
311
+ probable_camel_cased: bool = False
312
+
313
+ if camel_case_dst and (len(camel_case_dst) / buffer_length <= 0.3):
314
+ probable_camel_cased = True
315
+
316
+ if not probable_camel_cased:
317
+ self._foreign_long_count += 1
318
+ self._is_current_word_bad = True
319
+
320
+ if self._is_current_word_bad:
321
+ self._bad_word_count += 1
322
+ self._bad_character_count += len(self._buffer)
323
+ self._is_current_word_bad = False
324
+
325
+ self._foreign_long_watch = False
326
+ self._buffer = ""
327
+ self._buffer_accent_count = 0
328
+ elif (
329
+ character not in {"<", ">", "-", "=", "~", "|", "_"}
330
+ and character.isdigit() is False
331
+ and is_symbol(character)
332
+ ):
333
+ self._is_current_word_bad = True
334
+ self._buffer += character
335
+
336
+ def reset(self) -> None: # pragma: no cover
337
+ self._buffer = ""
338
+ self._is_current_word_bad = False
339
+ self._foreign_long_watch = False
340
+ self._bad_word_count = 0
341
+ self._word_count = 0
342
+ self._character_count = 0
343
+ self._bad_character_count = 0
344
+ self._foreign_long_count = 0
345
+
346
+ @property
347
+ def ratio(self) -> float:
348
+ if self._word_count <= 10 and self._foreign_long_count == 0:
349
+ return 0.0
350
+
351
+ return self._bad_character_count / self._character_count
352
+
353
+
354
+ class CjkInvalidStopPlugin(MessDetectorPlugin):
355
+ """
356
+ GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and
357
+ can be easily detected. Searching for the overuse of '丅' and '丄'.
358
+ """
359
+
360
+ def __init__(self) -> None:
361
+ self._wrong_stop_count: int = 0
362
+ self._cjk_character_count: int = 0
363
+
364
+ def eligible(self, character: str) -> bool:
365
+ return True
366
+
367
+ def feed(self, character: str) -> None:
368
+ if character in {"丅", "丄"}:
369
+ self._wrong_stop_count += 1
370
+ return
371
+ if is_cjk(character):
372
+ self._cjk_character_count += 1
373
+
374
+ def reset(self) -> None: # pragma: no cover
375
+ self._wrong_stop_count = 0
376
+ self._cjk_character_count = 0
377
+
378
+ @property
379
+ def ratio(self) -> float:
380
+ if self._cjk_character_count < 16:
381
+ return 0.0
382
+ return self._wrong_stop_count / self._cjk_character_count
383
+
384
+
385
+ class ArchaicUpperLowerPlugin(MessDetectorPlugin):
386
+ def __init__(self) -> None:
387
+ self._buf: bool = False
388
+
389
+ self._character_count_since_last_sep: int = 0
390
+
391
+ self._successive_upper_lower_count: int = 0
392
+ self._successive_upper_lower_count_final: int = 0
393
+
394
+ self._character_count: int = 0
395
+
396
+ self._last_alpha_seen: Optional[str] = None
397
+ self._current_ascii_only: bool = True
398
+
399
+ def eligible(self, character: str) -> bool:
400
+ return True
401
+
402
+ def feed(self, character: str) -> None:
403
+ is_concerned = character.isalpha() and is_case_variable(character)
404
+ chunk_sep = is_concerned is False
405
+
406
+ if chunk_sep and self._character_count_since_last_sep > 0:
407
+ if (
408
+ self._character_count_since_last_sep <= 64
409
+ and character.isdigit() is False
410
+ and self._current_ascii_only is False
411
+ ):
412
+ self._successive_upper_lower_count_final += (
413
+ self._successive_upper_lower_count
414
+ )
415
+
416
+ self._successive_upper_lower_count = 0
417
+ self._character_count_since_last_sep = 0
418
+ self._last_alpha_seen = None
419
+ self._buf = False
420
+ self._character_count += 1
421
+ self._current_ascii_only = True
422
+
423
+ return
424
+
425
+ if self._current_ascii_only is True and character.isascii() is False:
426
+ self._current_ascii_only = False
427
+
428
+ if self._last_alpha_seen is not None:
429
+ if (character.isupper() and self._last_alpha_seen.islower()) or (
430
+ character.islower() and self._last_alpha_seen.isupper()
431
+ ):
432
+ if self._buf is True:
433
+ self._successive_upper_lower_count += 2
434
+ self._buf = False
435
+ else:
436
+ self._buf = True
437
+ else:
438
+ self._buf = False
439
+
440
+ self._character_count += 1
441
+ self._character_count_since_last_sep += 1
442
+ self._last_alpha_seen = character
443
+
444
+ def reset(self) -> None: # pragma: no cover
445
+ self._character_count = 0
446
+ self._character_count_since_last_sep = 0
447
+ self._successive_upper_lower_count = 0
448
+ self._successive_upper_lower_count_final = 0
449
+ self._last_alpha_seen = None
450
+ self._buf = False
451
+ self._current_ascii_only = True
452
+
453
+ @property
454
+ def ratio(self) -> float:
455
+ if self._character_count == 0:
456
+ return 0.0
457
+
458
+ return self._successive_upper_lower_count_final / self._character_count
459
+
460
+
461
+ class ArabicIsolatedFormPlugin(MessDetectorPlugin):
462
+ def __init__(self) -> None:
463
+ self._character_count: int = 0
464
+ self._isolated_form_count: int = 0
465
+
466
+ def reset(self) -> None: # pragma: no cover
467
+ self._character_count = 0
468
+ self._isolated_form_count = 0
469
+
470
+ def eligible(self, character: str) -> bool:
471
+ return is_arabic(character)
472
+
473
+ def feed(self, character: str) -> None:
474
+ self._character_count += 1
475
+
476
+ if is_arabic_isolated_form(character):
477
+ self._isolated_form_count += 1
478
+
479
+ @property
480
+ def ratio(self) -> float:
481
+ if self._character_count < 8:
482
+ return 0.0
483
+
484
+ isolated_form_usage: float = self._isolated_form_count / self._character_count
485
+
486
+ return isolated_form_usage
487
+
488
+
489
+ @lru_cache(maxsize=1024)
490
+ def is_suspiciously_successive_range(
491
+ unicode_range_a: Optional[str], unicode_range_b: Optional[str]
492
+ ) -> bool:
493
+ """
494
+ Determine if two Unicode range seen next to each other can be considered as suspicious.
495
+ """
496
+ if unicode_range_a is None or unicode_range_b is None:
497
+ return True
498
+
499
+ if unicode_range_a == unicode_range_b:
500
+ return False
501
+
502
+ if "Latin" in unicode_range_a and "Latin" in unicode_range_b:
503
+ return False
504
+
505
+ if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b:
506
+ return False
507
+
508
+ # Latin characters can be accompanied with a combining diacritical mark
509
+ # eg. Vietnamese.
510
+ if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and (
511
+ "Combining" in unicode_range_a or "Combining" in unicode_range_b
512
+ ):
513
+ return False
514
+
515
+ keywords_range_a, keywords_range_b = unicode_range_a.split(
516
+ " "
517
+ ), unicode_range_b.split(" ")
518
+
519
+ for el in keywords_range_a:
520
+ if el in UNICODE_SECONDARY_RANGE_KEYWORD:
521
+ continue
522
+ if el in keywords_range_b:
523
+ return False
524
+
525
+ # Japanese Exception
526
+ range_a_jp_chars, range_b_jp_chars = (
527
+ unicode_range_a
528
+ in (
529
+ "Hiragana",
530
+ "Katakana",
531
+ ),
532
+ unicode_range_b in ("Hiragana", "Katakana"),
533
+ )
534
+ if (range_a_jp_chars or range_b_jp_chars) and (
535
+ "CJK" in unicode_range_a or "CJK" in unicode_range_b
536
+ ):
537
+ return False
538
+ if range_a_jp_chars and range_b_jp_chars:
539
+ return False
540
+
541
+ if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b:
542
+ if "CJK" in unicode_range_a or "CJK" in unicode_range_b:
543
+ return False
544
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
545
+ return False
546
+
547
+ # Chinese/Japanese use dedicated range for punctuation and/or separators.
548
+ if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or (
549
+ unicode_range_a in ["Katakana", "Hiragana"]
550
+ and unicode_range_b in ["Katakana", "Hiragana"]
551
+ ):
552
+ if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b:
553
+ return False
554
+ if "Forms" in unicode_range_a or "Forms" in unicode_range_b:
555
+ return False
556
+ if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
557
+ return False
558
+
559
+ return True
560
+
561
+
562
+ @lru_cache(maxsize=2048)
563
+ def mess_ratio(
564
+ decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False
565
+ ) -> float:
566
+ """
567
+ Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier.
568
+ """
569
+
570
+ detectors: List[MessDetectorPlugin] = [
571
+ md_class() for md_class in MessDetectorPlugin.__subclasses__()
572
+ ]
573
+
574
+ length: int = len(decoded_sequence) + 1
575
+
576
+ mean_mess_ratio: float = 0.0
577
+
578
+ if length < 512:
579
+ intermediary_mean_mess_ratio_calc: int = 32
580
+ elif length <= 1024:
581
+ intermediary_mean_mess_ratio_calc = 64
582
+ else:
583
+ intermediary_mean_mess_ratio_calc = 128
584
+
585
+ for character, index in zip(decoded_sequence + "\n", range(length)):
586
+ for detector in detectors:
587
+ if detector.eligible(character):
588
+ detector.feed(character)
589
+
590
+ if (
591
+ index > 0 and index % intermediary_mean_mess_ratio_calc == 0
592
+ ) or index == length - 1:
593
+ mean_mess_ratio = sum(dt.ratio for dt in detectors)
594
+
595
+ if mean_mess_ratio >= maximum_threshold:
596
+ break
597
+
598
+ if debug:
599
+ logger = getLogger("charset_normalizer")
600
+
601
+ logger.log(
602
+ TRACE,
603
+ "Mess-detector extended-analysis start. "
604
+ f"intermediary_mean_mess_ratio_calc={intermediary_mean_mess_ratio_calc} mean_mess_ratio={mean_mess_ratio} "
605
+ f"maximum_threshold={maximum_threshold}",
606
+ )
607
+
608
+ if len(decoded_sequence) > 16:
609
+ logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}")
610
+ logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}")
611
+
612
+ for dt in detectors: # pragma: nocover
613
+ logger.log(TRACE, f"{dt.__class__}: {dt.ratio}")
614
+
615
+ return round(mean_mess_ratio, 3)
venv/lib/python3.10/site-packages/lxml/ElementInclude.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # ElementTree
3
+ # $Id: ElementInclude.py 1862 2004-06-18 07:31:02Z Fredrik $
4
+ #
5
+ # limited xinclude support for element trees
6
+ #
7
+ # history:
8
+ # 2003-08-15 fl created
9
+ # 2003-11-14 fl fixed default loader
10
+ #
11
+ # Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
12
+ #
13
14
+ # http://www.pythonware.com
15
+ #
16
+ # --------------------------------------------------------------------
17
+ # The ElementTree toolkit is
18
+ #
19
+ # Copyright (c) 1999-2004 by Fredrik Lundh
20
+ #
21
+ # By obtaining, using, and/or copying this software and/or its
22
+ # associated documentation, you agree that you have read, understood,
23
+ # and will comply with the following terms and conditions:
24
+ #
25
+ # Permission to use, copy, modify, and distribute this software and
26
+ # its associated documentation for any purpose and without fee is
27
+ # hereby granted, provided that the above copyright notice appears in
28
+ # all copies, and that both that copyright notice and this permission
29
+ # notice appear in supporting documentation, and that the name of
30
+ # Secret Labs AB or the author not be used in advertising or publicity
31
+ # pertaining to distribution of the software without specific, written
32
+ # prior permission.
33
+ #
34
+ # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
35
+ # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
36
+ # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
37
+ # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
38
+ # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
39
+ # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
40
+ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
41
+ # OF THIS SOFTWARE.
42
+ # --------------------------------------------------------------------
43
+
44
+ """
45
+ Limited XInclude support for the ElementTree package.
46
+
47
+ While lxml.etree has full support for XInclude (see
48
+ `etree.ElementTree.xinclude()`), this module provides a simpler, pure
49
+ Python, ElementTree compatible implementation that supports a simple
50
+ form of custom URL resolvers.
51
+ """
52
+
53
+ from lxml import etree
54
+ try:
55
+ from urlparse import urljoin
56
+ from urllib2 import urlopen
57
+ except ImportError:
58
+ # Python 3
59
+ from urllib.parse import urljoin
60
+ from urllib.request import urlopen
61
+
62
+ XINCLUDE = "{http://www.w3.org/2001/XInclude}"
63
+
64
+ XINCLUDE_INCLUDE = XINCLUDE + "include"
65
+ XINCLUDE_FALLBACK = XINCLUDE + "fallback"
66
+ XINCLUDE_ITER_TAG = XINCLUDE + "*"
67
+
68
+ # For security reasons, the inclusion depth is limited to this read-only value by default.
69
+ DEFAULT_MAX_INCLUSION_DEPTH = 6
70
+
71
+
72
+ ##
73
+ # Fatal include error.
74
+
75
+ class FatalIncludeError(etree.LxmlSyntaxError):
76
+ pass
77
+
78
+
79
+ class LimitedRecursiveIncludeError(FatalIncludeError):
80
+ pass
81
+
82
+
83
+ ##
84
+ # ET compatible default loader.
85
+ # This loader reads an included resource from disk.
86
+ #
87
+ # @param href Resource reference.
88
+ # @param parse Parse mode. Either "xml" or "text".
89
+ # @param encoding Optional text encoding.
90
+ # @return The expanded resource. If the parse mode is "xml", this
91
+ # is an ElementTree instance. If the parse mode is "text", this
92
+ # is a Unicode string. If the loader fails, it can return None
93
+ # or raise an IOError exception.
94
+ # @throws IOError If the loader fails to load the resource.
95
+
96
+ def default_loader(href, parse, encoding=None):
97
+ file = open(href, 'rb')
98
+ if parse == "xml":
99
+ data = etree.parse(file).getroot()
100
+ else:
101
+ data = file.read()
102
+ if not encoding:
103
+ encoding = 'utf-8'
104
+ data = data.decode(encoding)
105
+ file.close()
106
+ return data
107
+
108
+
109
+ ##
110
+ # Default loader used by lxml.etree - handles custom resolvers properly
111
+ #
112
+
113
+ def _lxml_default_loader(href, parse, encoding=None, parser=None):
114
+ if parse == "xml":
115
+ data = etree.parse(href, parser).getroot()
116
+ else:
117
+ if "://" in href:
118
+ f = urlopen(href)
119
+ else:
120
+ f = open(href, 'rb')
121
+ data = f.read()
122
+ f.close()
123
+ if not encoding:
124
+ encoding = 'utf-8'
125
+ data = data.decode(encoding)
126
+ return data
127
+
128
+
129
+ ##
130
+ # Wrapper for ET compatibility - drops the parser
131
+
132
+ def _wrap_et_loader(loader):
133
+ def load(href, parse, encoding=None, parser=None):
134
+ return loader(href, parse, encoding)
135
+ return load
136
+
137
+
138
+ ##
139
+ # Expand XInclude directives.
140
+ #
141
+ # @param elem Root element.
142
+ # @param loader Optional resource loader. If omitted, it defaults
143
+ # to {@link default_loader}. If given, it should be a callable
144
+ # that implements the same interface as <b>default_loader</b>.
145
+ # @param base_url The base URL of the original file, to resolve
146
+ # relative include file references.
147
+ # @param max_depth The maximum number of recursive inclusions.
148
+ # Limited to reduce the risk of malicious content explosion.
149
+ # Pass None to disable the limitation.
150
+ # @throws LimitedRecursiveIncludeError If the {@link max_depth} was exceeded.
151
+ # @throws FatalIncludeError If the function fails to include a given
152
+ # resource, or if the tree contains malformed XInclude elements.
153
+ # @throws IOError If the function fails to load a given resource.
154
+ # @returns the node or its replacement if it was an XInclude node
155
+
156
+ def include(elem, loader=None, base_url=None,
157
+ max_depth=DEFAULT_MAX_INCLUSION_DEPTH):
158
+ if max_depth is None:
159
+ max_depth = -1
160
+ elif max_depth < 0:
161
+ raise ValueError("expected non-negative depth or None for 'max_depth', got %r" % max_depth)
162
+
163
+ if base_url is None:
164
+ if hasattr(elem, 'getroot'):
165
+ tree = elem
166
+ elem = elem.getroot()
167
+ else:
168
+ tree = elem.getroottree()
169
+ if hasattr(tree, 'docinfo'):
170
+ base_url = tree.docinfo.URL
171
+ elif hasattr(elem, 'getroot'):
172
+ elem = elem.getroot()
173
+ _include(elem, loader, base_url, max_depth)
174
+
175
+
176
+ def _include(elem, loader=None, base_url=None,
177
+ max_depth=DEFAULT_MAX_INCLUSION_DEPTH, _parent_hrefs=None):
178
+ if loader is not None:
179
+ load_include = _wrap_et_loader(loader)
180
+ else:
181
+ load_include = _lxml_default_loader
182
+
183
+ if _parent_hrefs is None:
184
+ _parent_hrefs = set()
185
+
186
+ parser = elem.getroottree().parser
187
+
188
+ include_elements = list(
189
+ elem.iter(XINCLUDE_ITER_TAG))
190
+
191
+ for e in include_elements:
192
+ if e.tag == XINCLUDE_INCLUDE:
193
+ # process xinclude directive
194
+ href = urljoin(base_url, e.get("href"))
195
+ parse = e.get("parse", "xml")
196
+ parent = e.getparent()
197
+ if parse == "xml":
198
+ if href in _parent_hrefs:
199
+ raise FatalIncludeError(
200
+ "recursive include of %r detected" % href
201
+ )
202
+ if max_depth == 0:
203
+ raise LimitedRecursiveIncludeError(
204
+ "maximum xinclude depth reached when including file %s" % href)
205
+ node = load_include(href, parse, parser=parser)
206
+ if node is None:
207
+ raise FatalIncludeError(
208
+ "cannot load %r as %r" % (href, parse)
209
+ )
210
+ node = _include(node, loader, href, max_depth - 1, {href} | _parent_hrefs)
211
+ if e.tail:
212
+ node.tail = (node.tail or "") + e.tail
213
+ if parent is None:
214
+ return node # replaced the root node!
215
+ parent.replace(e, node)
216
+ elif parse == "text":
217
+ text = load_include(href, parse, encoding=e.get("encoding"))
218
+ if text is None:
219
+ raise FatalIncludeError(
220
+ "cannot load %r as %r" % (href, parse)
221
+ )
222
+ predecessor = e.getprevious()
223
+ if predecessor is not None:
224
+ predecessor.tail = (predecessor.tail or "") + text
225
+ elif parent is None:
226
+ return text # replaced the root node!
227
+ else:
228
+ parent.text = (parent.text or "") + text + (e.tail or "")
229
+ parent.remove(e)
230
+ else:
231
+ raise FatalIncludeError(
232
+ "unknown parse type in xi:include tag (%r)" % parse
233
+ )
234
+ elif e.tag == XINCLUDE_FALLBACK:
235
+ parent = e.getparent()
236
+ if parent is not None and parent.tag != XINCLUDE_INCLUDE:
237
+ raise FatalIncludeError(
238
+ "xi:fallback tag must be child of xi:include (%r)" % e.tag
239
+ )
240
+ else:
241
+ raise FatalIncludeError(
242
+ "Invalid element found in XInclude namespace (%r)" % e.tag
243
+ )
244
+ return elem
venv/lib/python3.10/site-packages/lxml/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # this is a package
2
+
3
+ __version__ = "5.2.1"
4
+
5
+
6
+ def get_include():
7
+ """
8
+ Returns a list of header include paths (for lxml itself, libxml2
9
+ and libxslt) needed to compile C code against lxml if it was built
10
+ with statically linked libraries.
11
+ """
12
+ import os
13
+ lxml_path = __path__[0]
14
+ include_path = os.path.join(lxml_path, 'includes')
15
+ includes = [include_path, lxml_path]
16
+
17
+ for name in os.listdir(include_path):
18
+ path = os.path.join(include_path, name)
19
+ if os.path.isdir(path):
20
+ includes.append(path)
21
+
22
+ return includes
venv/lib/python3.10/site-packages/lxml/__pycache__/ElementInclude.cpython-310.pyc ADDED
Binary file (3.81 kB). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (697 Bytes). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/_elementpath.cpython-310.pyc ADDED
Binary file (6.38 kB). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/builder.cpython-310.pyc ADDED
Binary file (5.88 kB). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/cssselect.cpython-310.pyc ADDED
Binary file (3.59 kB). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/doctestcompare.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/pyclasslookup.cpython-310.pyc ADDED
Binary file (236 Bytes). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/sax.cpython-310.pyc ADDED
Binary file (8.13 kB). View file
 
venv/lib/python3.10/site-packages/lxml/__pycache__/usedoctest.cpython-310.pyc ADDED
Binary file (426 Bytes). View file
 
venv/lib/python3.10/site-packages/lxml/_elementpath.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (209 kB). View file
 
venv/lib/python3.10/site-packages/lxml/_elementpath.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=2
2
+
3
+ #
4
+ # ElementTree
5
+ # $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
6
+ #
7
+ # limited xpath support for element trees
8
+ #
9
+ # history:
10
+ # 2003-05-23 fl created
11
+ # 2003-05-28 fl added support for // etc
12
+ # 2003-08-27 fl fixed parsing of periods in element names
13
+ # 2007-09-10 fl new selection engine
14
+ # 2007-09-12 fl fixed parent selector
15
+ # 2007-09-13 fl added iterfind; changed findall to return a list
16
+ # 2007-11-30 fl added namespaces support
17
+ # 2009-10-30 fl added child element value filter
18
+ #
19
+ # Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved.
20
+ #
21
22
+ # http://www.pythonware.com
23
+ #
24
+ # --------------------------------------------------------------------
25
+ # The ElementTree toolkit is
26
+ #
27
+ # Copyright (c) 1999-2009 by Fredrik Lundh
28
+ #
29
+ # By obtaining, using, and/or copying this software and/or its
30
+ # associated documentation, you agree that you have read, understood,
31
+ # and will comply with the following terms and conditions:
32
+ #
33
+ # Permission to use, copy, modify, and distribute this software and
34
+ # its associated documentation for any purpose and without fee is
35
+ # hereby granted, provided that the above copyright notice appears in
36
+ # all copies, and that both that copyright notice and this permission
37
+ # notice appear in supporting documentation, and that the name of
38
+ # Secret Labs AB or the author not be used in advertising or publicity
39
+ # pertaining to distribution of the software without specific, written
40
+ # prior permission.
41
+ #
42
+ # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
43
+ # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
44
+ # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
45
+ # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
46
+ # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
47
+ # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
48
+ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
49
+ # OF THIS SOFTWARE.
50
+ # --------------------------------------------------------------------
51
+
52
+ ##
53
+ # Implementation module for XPath support. There's usually no reason
54
+ # to import this module directly; the <b>ElementTree</b> does this for
55
+ # you, if needed.
56
+ ##
57
+
58
+
59
+ import re
60
+
61
+ xpath_tokenizer_re = re.compile(
62
+ "("
63
+ "'[^']*'|\"[^\"]*\"|"
64
+ "::|"
65
+ "//?|"
66
+ r"\.\.|"
67
+ r"\(\)|"
68
+ r"[/.*:\[\]\(\)@=])|"
69
+ r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
70
+ r"\s+"
71
+ )
72
+
73
+ def xpath_tokenizer(pattern, namespaces=None, with_prefixes=True):
74
+ # ElementTree uses '', lxml used None originally.
75
+ default_namespace = (namespaces.get(None) or namespaces.get('')) if namespaces else None
76
+ parsing_attribute = False
77
+ for token in xpath_tokenizer_re.findall(pattern):
78
+ ttype, tag = token
79
+ if tag and tag[0] != "{":
80
+ if ":" in tag and with_prefixes:
81
+ prefix, uri = tag.split(":", 1)
82
+ try:
83
+ if not namespaces:
84
+ raise KeyError
85
+ yield ttype, "{%s}%s" % (namespaces[prefix], uri)
86
+ except KeyError:
87
+ raise SyntaxError("prefix %r not found in prefix map" % prefix)
88
+ elif default_namespace and not parsing_attribute:
89
+ yield ttype, "{%s}%s" % (default_namespace, tag)
90
+ else:
91
+ yield token
92
+ parsing_attribute = False
93
+ else:
94
+ yield token
95
+ parsing_attribute = ttype == '@'
96
+
97
+
98
+ def prepare_child(next, token):
99
+ tag = token[1]
100
+ def select(result):
101
+ for elem in result:
102
+ yield from elem.iterchildren(tag)
103
+ return select
104
+
105
+ def prepare_star(next, token):
106
+ def select(result):
107
+ for elem in result:
108
+ yield from elem.iterchildren('*')
109
+ return select
110
+
111
+ def prepare_self(next, token):
112
+ def select(result):
113
+ return result
114
+ return select
115
+
116
+ def prepare_descendant(next, token):
117
+ token = next()
118
+ if token[0] == "*":
119
+ tag = "*"
120
+ elif not token[0]:
121
+ tag = token[1]
122
+ else:
123
+ raise SyntaxError("invalid descendant")
124
+ def select(result):
125
+ for elem in result:
126
+ yield from elem.iterdescendants(tag)
127
+ return select
128
+
129
+ def prepare_parent(next, token):
130
+ def select(result):
131
+ for elem in result:
132
+ parent = elem.getparent()
133
+ if parent is not None:
134
+ yield parent
135
+ return select
136
+
137
+ def prepare_predicate(next, token):
138
+ # FIXME: replace with real parser!!! refs:
139
+ # http://effbot.org/zone/simple-iterator-parser.htm
140
+ # http://javascript.crockford.com/tdop/tdop.html
141
+ signature = ''
142
+ predicate = []
143
+ while 1:
144
+ token = next()
145
+ if token[0] == "]":
146
+ break
147
+ if token == ('', ''):
148
+ # ignore whitespace
149
+ continue
150
+ if token[0] and token[0][:1] in "'\"":
151
+ token = "'", token[0][1:-1]
152
+ signature += token[0] or "-"
153
+ predicate.append(token[1])
154
+
155
+ # use signature to determine predicate type
156
+ if signature == "@-":
157
+ # [@attribute] predicate
158
+ key = predicate[1]
159
+ def select(result):
160
+ for elem in result:
161
+ if elem.get(key) is not None:
162
+ yield elem
163
+ return select
164
+ if signature == "@-='":
165
+ # [@attribute='value']
166
+ key = predicate[1]
167
+ value = predicate[-1]
168
+ def select(result):
169
+ for elem in result:
170
+ if elem.get(key) == value:
171
+ yield elem
172
+ return select
173
+ if signature == "-" and not re.match(r"-?\d+$", predicate[0]):
174
+ # [tag]
175
+ tag = predicate[0]
176
+ def select(result):
177
+ for elem in result:
178
+ for _ in elem.iterchildren(tag):
179
+ yield elem
180
+ break
181
+ return select
182
+ if signature == ".='" or (signature == "-='" and not re.match(r"-?\d+$", predicate[0])):
183
+ # [.='value'] or [tag='value']
184
+ tag = predicate[0]
185
+ value = predicate[-1]
186
+ if tag:
187
+ def select(result):
188
+ for elem in result:
189
+ for e in elem.iterchildren(tag):
190
+ if "".join(e.itertext()) == value:
191
+ yield elem
192
+ break
193
+ else:
194
+ def select(result):
195
+ for elem in result:
196
+ if "".join(elem.itertext()) == value:
197
+ yield elem
198
+ return select
199
+ if signature == "-" or signature == "-()" or signature == "-()-":
200
+ # [index] or [last()] or [last()-index]
201
+ if signature == "-":
202
+ # [index]
203
+ index = int(predicate[0]) - 1
204
+ if index < 0:
205
+ if index == -1:
206
+ raise SyntaxError(
207
+ "indices in path predicates are 1-based, not 0-based")
208
+ else:
209
+ raise SyntaxError("path index >= 1 expected")
210
+ else:
211
+ if predicate[0] != "last":
212
+ raise SyntaxError("unsupported function")
213
+ if signature == "-()-":
214
+ try:
215
+ index = int(predicate[2]) - 1
216
+ except ValueError:
217
+ raise SyntaxError("unsupported expression")
218
+ else:
219
+ index = -1
220
+ def select(result):
221
+ for elem in result:
222
+ parent = elem.getparent()
223
+ if parent is None:
224
+ continue
225
+ try:
226
+ # FIXME: what if the selector is "*" ?
227
+ elems = list(parent.iterchildren(elem.tag))
228
+ if elems[index] is elem:
229
+ yield elem
230
+ except IndexError:
231
+ pass
232
+ return select
233
+ raise SyntaxError("invalid predicate")
234
+
235
+ ops = {
236
+ "": prepare_child,
237
+ "*": prepare_star,
238
+ ".": prepare_self,
239
+ "..": prepare_parent,
240
+ "//": prepare_descendant,
241
+ "[": prepare_predicate,
242
+ }
243
+
244
+
245
+ # --------------------------------------------------------------------
246
+
247
+ _cache = {}
248
+
249
+
250
+ def _build_path_iterator(path, namespaces, with_prefixes=True):
251
+ """compile selector pattern"""
252
+ if path[-1:] == "/":
253
+ path += "*" # implicit all (FIXME: keep this?)
254
+
255
+ cache_key = (path,)
256
+ if namespaces:
257
+ # lxml originally used None for the default namespace but ElementTree uses the
258
+ # more convenient (all-strings-dict) empty string, so we support both here,
259
+ # preferring the more convenient '', as long as they aren't ambiguous.
260
+ if None in namespaces:
261
+ if '' in namespaces and namespaces[None] != namespaces['']:
262
+ raise ValueError("Ambiguous default namespace provided: %r versus %r" % (
263
+ namespaces[None], namespaces['']))
264
+ cache_key += (namespaces[None],) + tuple(sorted(
265
+ item for item in namespaces.items() if item[0] is not None))
266
+ else:
267
+ cache_key += tuple(sorted(namespaces.items()))
268
+
269
+ try:
270
+ return _cache[cache_key]
271
+ except KeyError:
272
+ pass
273
+ if len(_cache) > 100:
274
+ _cache.clear()
275
+
276
+ if path[:1] == "/":
277
+ raise SyntaxError("cannot use absolute path on element")
278
+ stream = iter(xpath_tokenizer(path, namespaces, with_prefixes=with_prefixes))
279
+ try:
280
+ _next = stream.next
281
+ except AttributeError:
282
+ # Python 3
283
+ _next = stream.__next__
284
+ try:
285
+ token = _next()
286
+ except StopIteration:
287
+ raise SyntaxError("empty path expression")
288
+ selector = []
289
+ while 1:
290
+ try:
291
+ selector.append(ops[token[0]](_next, token))
292
+ except StopIteration:
293
+ raise SyntaxError("invalid path")
294
+ try:
295
+ token = _next()
296
+ if token[0] == "/":
297
+ token = _next()
298
+ except StopIteration:
299
+ break
300
+ _cache[cache_key] = selector
301
+ return selector
302
+
303
+
304
+ ##
305
+ # Iterate over the matching nodes
306
+
307
+ def iterfind(elem, path, namespaces=None, with_prefixes=True):
308
+ selector = _build_path_iterator(path, namespaces, with_prefixes=with_prefixes)
309
+ result = iter((elem,))
310
+ for select in selector:
311
+ result = select(result)
312
+ return result
313
+
314
+
315
+ ##
316
+ # Find first matching object.
317
+
318
+ def find(elem, path, namespaces=None, with_prefixes=True):
319
+ it = iterfind(elem, path, namespaces, with_prefixes=with_prefixes)
320
+ try:
321
+ return next(it)
322
+ except StopIteration:
323
+ return None
324
+
325
+
326
+ ##
327
+ # Find all matching objects.
328
+
329
+ def findall(elem, path, namespaces=None, with_prefixes=True):
330
+ return list(iterfind(elem, path, namespaces))
331
+
332
+
333
+ ##
334
+ # Find text for first matching object.
335
+
336
+ def findtext(elem, path, default=None, namespaces=None, with_prefixes=True):
337
+ el = find(elem, path, namespaces, with_prefixes=with_prefixes)
338
+ if el is None:
339
+ return default
340
+ else:
341
+ return el.text or ''
venv/lib/python3.10/site-packages/lxml/apihelpers.pxi ADDED
@@ -0,0 +1,1793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Private/public helper functions for API functions
2
+
3
+ from lxml.includes cimport uri
4
+
5
+
6
+ cdef void displayNode(xmlNode* c_node, indent) noexcept:
7
+ # to help with debugging
8
+ cdef xmlNode* c_child
9
+ try:
10
+ print(indent * ' ', <long>c_node)
11
+ c_child = c_node.children
12
+ while c_child is not NULL:
13
+ displayNode(c_child, indent + 1)
14
+ c_child = c_child.next
15
+ finally:
16
+ return # swallow any exceptions
17
+
18
+ cdef inline bint _isHtmlDocument(_Element element) except -1:
19
+ cdef xmlNode* c_node = element._c_node
20
+ return (
21
+ c_node is not NULL and c_node.doc is not NULL and
22
+ c_node.doc.properties & tree.XML_DOC_HTML != 0
23
+ )
24
+
25
+ cdef inline int _assertValidNode(_Element element) except -1:
26
+ assert element._c_node is not NULL, "invalid Element proxy at %s" % id(element)
27
+
28
+ cdef inline int _assertValidDoc(_Document doc) except -1:
29
+ assert doc._c_doc is not NULL, "invalid Document proxy at %s" % id(doc)
30
+
31
+ cdef _Document _documentOrRaise(object input):
32
+ """Call this to get the document of a _Document, _ElementTree or _Element
33
+ object, or to raise an exception if it can't be determined.
34
+
35
+ Should be used in all API functions for consistency.
36
+ """
37
+ cdef _Document doc
38
+ if isinstance(input, _ElementTree):
39
+ if (<_ElementTree>input)._context_node is not None:
40
+ doc = (<_ElementTree>input)._context_node._doc
41
+ else:
42
+ doc = None
43
+ elif isinstance(input, _Element):
44
+ doc = (<_Element>input)._doc
45
+ elif isinstance(input, _Document):
46
+ doc = <_Document>input
47
+ else:
48
+ raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}"
49
+ if doc is None:
50
+ raise ValueError, f"Input object has no document: {python._fqtypename(input).decode('utf8')}"
51
+ _assertValidDoc(doc)
52
+ return doc
53
+
54
+ cdef _Element _rootNodeOrRaise(object input):
55
+ """Call this to get the root node of a _Document, _ElementTree or
56
+ _Element object, or to raise an exception if it can't be determined.
57
+
58
+ Should be used in all API functions for consistency.
59
+ """
60
+ cdef _Element node
61
+ if isinstance(input, _ElementTree):
62
+ node = (<_ElementTree>input)._context_node
63
+ elif isinstance(input, _Element):
64
+ node = <_Element>input
65
+ elif isinstance(input, _Document):
66
+ node = (<_Document>input).getroot()
67
+ else:
68
+ raise TypeError, f"Invalid input object: {python._fqtypename(input).decode('utf8')}"
69
+ if (node is None or not node._c_node or
70
+ node._c_node.type != tree.XML_ELEMENT_NODE):
71
+ raise ValueError, f"Input object is not an XML element: {python._fqtypename(input).decode('utf8')}"
72
+ _assertValidNode(node)
73
+ return node
74
+
75
+ cdef bint _isAncestorOrSame(xmlNode* c_ancestor, xmlNode* c_node) noexcept:
76
+ while c_node:
77
+ if c_node is c_ancestor:
78
+ return True
79
+ c_node = c_node.parent
80
+ return False
81
+
82
+ cdef _Element _makeElement(tag, xmlDoc* c_doc, _Document doc,
83
+ _BaseParser parser, text, tail, attrib, nsmap,
84
+ dict extra_attrs):
85
+ """Create a new element and initialize text content, namespaces and
86
+ attributes.
87
+
88
+ This helper function will reuse as much of the existing document as
89
+ possible:
90
+
91
+ If 'parser' is None, the parser will be inherited from 'doc' or the
92
+ default parser will be used.
93
+
94
+ If 'doc' is None, 'c_doc' is used to create a new _Document and the new
95
+ element is made its root node.
96
+
97
+ If 'c_doc' is also NULL, a new xmlDoc will be created.
98
+ """
99
+ cdef xmlNode* c_node
100
+ if doc is not None:
101
+ c_doc = doc._c_doc
102
+ ns_utf, name_utf = _getNsTag(tag)
103
+ if parser is not None and parser._for_html:
104
+ _htmlTagValidOrRaise(name_utf)
105
+ if c_doc is NULL:
106
+ c_doc = _newHTMLDoc()
107
+ else:
108
+ _tagValidOrRaise(name_utf)
109
+ if c_doc is NULL:
110
+ c_doc = _newXMLDoc()
111
+ c_node = _createElement(c_doc, name_utf)
112
+ if c_node is NULL:
113
+ if doc is None and c_doc is not NULL:
114
+ tree.xmlFreeDoc(c_doc)
115
+ raise MemoryError()
116
+ try:
117
+ if doc is None:
118
+ tree.xmlDocSetRootElement(c_doc, c_node)
119
+ doc = _documentFactory(c_doc, parser)
120
+ if text is not None:
121
+ _setNodeText(c_node, text)
122
+ if tail is not None:
123
+ _setTailText(c_node, tail)
124
+ # add namespaces to node if necessary
125
+ _setNodeNamespaces(c_node, doc, ns_utf, nsmap)
126
+ _initNodeAttributes(c_node, doc, attrib, extra_attrs)
127
+ return _elementFactory(doc, c_node)
128
+ except:
129
+ # free allocated c_node/c_doc unless Python does it for us
130
+ if c_node.doc is not c_doc:
131
+ # node not yet in document => will not be freed by document
132
+ if tail is not None:
133
+ _removeText(c_node.next) # tail
134
+ tree.xmlFreeNode(c_node)
135
+ if doc is None:
136
+ # c_doc will not be freed by doc
137
+ tree.xmlFreeDoc(c_doc)
138
+ raise
139
+
140
+ cdef int _initNewElement(_Element element, bint is_html, name_utf, ns_utf,
141
+ _BaseParser parser, attrib, nsmap, dict extra_attrs) except -1:
142
+ """Initialise a new Element object.
143
+
144
+ This is used when users instantiate a Python Element subclass
145
+ directly, without it being mapped to an existing XML node.
146
+ """
147
+ cdef xmlDoc* c_doc
148
+ cdef xmlNode* c_node
149
+ cdef _Document doc
150
+ if is_html:
151
+ _htmlTagValidOrRaise(name_utf)
152
+ c_doc = _newHTMLDoc()
153
+ else:
154
+ _tagValidOrRaise(name_utf)
155
+ c_doc = _newXMLDoc()
156
+ c_node = _createElement(c_doc, name_utf)
157
+ if c_node is NULL:
158
+ if c_doc is not NULL:
159
+ tree.xmlFreeDoc(c_doc)
160
+ raise MemoryError()
161
+ tree.xmlDocSetRootElement(c_doc, c_node)
162
+ doc = _documentFactory(c_doc, parser)
163
+ # add namespaces to node if necessary
164
+ _setNodeNamespaces(c_node, doc, ns_utf, nsmap)
165
+ _initNodeAttributes(c_node, doc, attrib, extra_attrs)
166
+ _registerProxy(element, doc, c_node)
167
+ element._init()
168
+ return 0
169
+
170
+ cdef _Element _makeSubElement(_Element parent, tag, text, tail,
171
+ attrib, nsmap, dict extra_attrs):
172
+ """Create a new child element and initialize text content, namespaces and
173
+ attributes.
174
+ """
175
+ cdef xmlNode* c_node
176
+ cdef xmlDoc* c_doc
177
+ if parent is None or parent._doc is None:
178
+ return None
179
+ _assertValidNode(parent)
180
+ ns_utf, name_utf = _getNsTag(tag)
181
+ c_doc = parent._doc._c_doc
182
+
183
+ if parent._doc._parser is not None and parent._doc._parser._for_html:
184
+ _htmlTagValidOrRaise(name_utf)
185
+ else:
186
+ _tagValidOrRaise(name_utf)
187
+
188
+ c_node = _createElement(c_doc, name_utf)
189
+ if c_node is NULL:
190
+ raise MemoryError()
191
+ tree.xmlAddChild(parent._c_node, c_node)
192
+
193
+ try:
194
+ if text is not None:
195
+ _setNodeText(c_node, text)
196
+ if tail is not None:
197
+ _setTailText(c_node, tail)
198
+
199
+ # add namespaces to node if necessary
200
+ _setNodeNamespaces(c_node, parent._doc, ns_utf, nsmap)
201
+ _initNodeAttributes(c_node, parent._doc, attrib, extra_attrs)
202
+ return _elementFactory(parent._doc, c_node)
203
+ except:
204
+ # make sure we clean up in case of an error
205
+ _removeNode(parent._doc, c_node)
206
+ raise
207
+
208
+
209
+ cdef int _setNodeNamespaces(xmlNode* c_node, _Document doc,
210
+ object node_ns_utf, object nsmap) except -1:
211
+ """Lookup current namespace prefixes, then set namespace structure for
212
+ node (if 'node_ns_utf' was provided) and register new ns-prefix mappings.
213
+
214
+ 'node_ns_utf' should only be passed for a newly created node.
215
+ """
216
+ cdef xmlNs* c_ns
217
+ cdef list nsdefs
218
+
219
+ if nsmap:
220
+ for prefix, href in _iter_nsmap(nsmap):
221
+ href_utf = _utf8(href)
222
+ _uriValidOrRaise(href_utf)
223
+ c_href = _xcstr(href_utf)
224
+ if prefix is not None:
225
+ prefix_utf = _utf8(prefix)
226
+ _prefixValidOrRaise(prefix_utf)
227
+ c_prefix = _xcstr(prefix_utf)
228
+ else:
229
+ c_prefix = <const_xmlChar*>NULL
230
+ # add namespace with prefix if it is not already known
231
+ c_ns = tree.xmlSearchNs(doc._c_doc, c_node, c_prefix)
232
+ if c_ns is NULL or \
233
+ c_ns.href is NULL or \
234
+ tree.xmlStrcmp(c_ns.href, c_href) != 0:
235
+ c_ns = tree.xmlNewNs(c_node, c_href, c_prefix)
236
+ if href_utf == node_ns_utf:
237
+ tree.xmlSetNs(c_node, c_ns)
238
+ node_ns_utf = None
239
+
240
+ if node_ns_utf is not None:
241
+ _uriValidOrRaise(node_ns_utf)
242
+ doc._setNodeNs(c_node, _xcstr(node_ns_utf))
243
+ return 0
244
+
245
+
246
+ cdef dict _build_nsmap(xmlNode* c_node):
247
+ """
248
+ Namespace prefix->URI mapping known in the context of this Element.
249
+ This includes all namespace declarations of the parents.
250
+ """
251
+ cdef xmlNs* c_ns
252
+ nsmap = {}
253
+ while c_node is not NULL and c_node.type == tree.XML_ELEMENT_NODE:
254
+ c_ns = c_node.nsDef
255
+ while c_ns is not NULL:
256
+ if c_ns.prefix or c_ns.href:
257
+ prefix = funicodeOrNone(c_ns.prefix)
258
+ if prefix not in nsmap:
259
+ nsmap[prefix] = funicodeOrNone(c_ns.href)
260
+ c_ns = c_ns.next
261
+ c_node = c_node.parent
262
+ return nsmap
263
+
264
+
265
+ cdef _iter_nsmap(nsmap):
266
+ """
267
+ Create a reproducibly ordered iterable from an nsmap mapping.
268
+ Tries to preserve an existing order and sorts if it assumes no order.
269
+
270
+ The difference to _iter_attrib() is that None doesn't sort with strings
271
+ in Py3.x.
272
+ """
273
+ if isinstance(nsmap, dict):
274
+ # dicts are insertion-ordered in Py3.6+ => keep the user provided order.
275
+ return nsmap.items()
276
+ if len(nsmap) <= 1:
277
+ return nsmap.items()
278
+ # nsmap will usually be a plain unordered dict => avoid type checking overhead
279
+ if type(nsmap) is not dict and isinstance(nsmap, OrderedDict):
280
+ return nsmap.items() # keep existing order
281
+ if None not in nsmap:
282
+ return sorted(nsmap.items())
283
+
284
+ # Move the default namespace to the end. This makes sure libxml2
285
+ # prefers a prefix if the ns is defined redundantly on the same
286
+ # element. That way, users can work around a problem themselves
287
+ # where default namespace attributes on non-default namespaced
288
+ # elements serialise without prefix (i.e. into the non-default
289
+ # namespace).
290
+ default_ns = nsmap[None]
291
+ nsdefs = [(k, v) for k, v in nsmap.items() if k is not None]
292
+ nsdefs.sort()
293
+ nsdefs.append((None, default_ns))
294
+ return nsdefs
295
+
296
+
297
+ cdef _iter_attrib(attrib):
298
+ """
299
+ Create a reproducibly ordered iterable from an attrib mapping.
300
+ Tries to preserve an existing order and sorts if it assumes no order.
301
+ """
302
+ # dicts are insertion-ordered in Py3.6+ => keep the user provided order.
303
+ if isinstance(attrib, (dict, _Attrib, OrderedDict)):
304
+ return attrib.items()
305
+ # assume it's an unordered mapping of some kind
306
+ return sorted(attrib.items())
307
+
308
+
309
+ cdef _initNodeAttributes(xmlNode* c_node, _Document doc, attrib, dict extra):
310
+ """Initialise the attributes of an element node.
311
+ """
312
+ cdef bint is_html
313
+ cdef xmlNs* c_ns
314
+ if attrib is not None and not hasattr(attrib, 'items'):
315
+ raise TypeError, f"Invalid attribute dictionary: {python._fqtypename(attrib).decode('utf8')}"
316
+ if not attrib and not extra:
317
+ return # nothing to do
318
+ is_html = doc._parser._for_html
319
+ seen = set()
320
+ if extra:
321
+ for name, value in extra.items():
322
+ _addAttributeToNode(c_node, doc, is_html, name, value, seen)
323
+ if attrib:
324
+ for name, value in _iter_attrib(attrib):
325
+ _addAttributeToNode(c_node, doc, is_html, name, value, seen)
326
+
327
+
328
+ cdef int _addAttributeToNode(xmlNode* c_node, _Document doc, bint is_html,
329
+ name, value, set seen_tags) except -1:
330
+ ns_utf, name_utf = tag = _getNsTag(name)
331
+ if tag in seen_tags:
332
+ return 0
333
+ seen_tags.add(tag)
334
+ if not is_html:
335
+ _attributeValidOrRaise(name_utf)
336
+ value_utf = _utf8(value)
337
+ if ns_utf is None:
338
+ tree.xmlNewProp(c_node, _xcstr(name_utf), _xcstr(value_utf))
339
+ else:
340
+ _uriValidOrRaise(ns_utf)
341
+ c_ns = doc._findOrBuildNodeNs(c_node, _xcstr(ns_utf), NULL, 1)
342
+ tree.xmlNewNsProp(c_node, c_ns,
343
+ _xcstr(name_utf), _xcstr(value_utf))
344
+ return 0
345
+
346
+
347
+ ctypedef struct _ns_node_ref:
348
+ xmlNs* ns
349
+ xmlNode* node
350
+
351
+
352
+ cdef int _collectNsDefs(xmlNode* c_element, _ns_node_ref **_c_ns_list,
353
+ size_t *_c_ns_list_len, size_t *_c_ns_list_size) except -1:
354
+ c_ns_list = _c_ns_list[0]
355
+ cdef size_t c_ns_list_len = _c_ns_list_len[0]
356
+ cdef size_t c_ns_list_size = _c_ns_list_size[0]
357
+
358
+ c_nsdef = c_element.nsDef
359
+ while c_nsdef is not NULL:
360
+ if c_ns_list_len >= c_ns_list_size:
361
+ if c_ns_list is NULL:
362
+ c_ns_list_size = 20
363
+ else:
364
+ c_ns_list_size *= 2
365
+ c_nsref_ptr = <_ns_node_ref*> python.lxml_realloc(
366
+ c_ns_list, c_ns_list_size, sizeof(_ns_node_ref))
367
+ if c_nsref_ptr is NULL:
368
+ if c_ns_list is not NULL:
369
+ python.lxml_free(c_ns_list)
370
+ _c_ns_list[0] = NULL
371
+ raise MemoryError()
372
+ c_ns_list = c_nsref_ptr
373
+
374
+ c_ns_list[c_ns_list_len] = _ns_node_ref(c_nsdef, c_element)
375
+ c_ns_list_len += 1
376
+ c_nsdef = c_nsdef.next
377
+
378
+ _c_ns_list_size[0] = c_ns_list_size
379
+ _c_ns_list_len[0] = c_ns_list_len
380
+ _c_ns_list[0] = c_ns_list
381
+
382
+
383
+ cdef int _removeUnusedNamespaceDeclarations(xmlNode* c_element, set prefixes_to_keep) except -1:
384
+ """Remove any namespace declarations from a subtree that are not used by
385
+ any of its elements (or attributes).
386
+
387
+ If a 'prefixes_to_keep' is provided, it must be a set of prefixes.
388
+ Any corresponding namespace mappings will not be removed as part of the cleanup.
389
+ """
390
+ cdef xmlNode* c_node
391
+ cdef _ns_node_ref* c_ns_list = NULL
392
+ cdef size_t c_ns_list_size = 0
393
+ cdef size_t c_ns_list_len = 0
394
+ cdef size_t i
395
+
396
+ if c_element.parent and c_element.parent.type == tree.XML_DOCUMENT_NODE:
397
+ # include declarations on the document node
398
+ _collectNsDefs(c_element.parent, &c_ns_list, &c_ns_list_len, &c_ns_list_size)
399
+
400
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_element, c_element, 1)
401
+ # collect all new namespace declarations into the ns list
402
+ if c_element.nsDef:
403
+ _collectNsDefs(c_element, &c_ns_list, &c_ns_list_len, &c_ns_list_size)
404
+
405
+ # remove all namespace declarations from the list that are referenced
406
+ if c_ns_list_len and c_element.type == tree.XML_ELEMENT_NODE:
407
+ c_node = c_element
408
+ while c_node and c_ns_list_len:
409
+ if c_node.ns:
410
+ for i in range(c_ns_list_len):
411
+ if c_node.ns is c_ns_list[i].ns:
412
+ c_ns_list_len -= 1
413
+ c_ns_list[i] = c_ns_list[c_ns_list_len]
414
+ #c_ns_list[c_ns_list_len] = _ns_node_ref(NULL, NULL)
415
+ break
416
+ if c_node is c_element:
417
+ # continue with attributes
418
+ c_node = <xmlNode*>c_element.properties
419
+ else:
420
+ c_node = c_node.next
421
+ tree.END_FOR_EACH_ELEMENT_FROM(c_element)
422
+
423
+ if c_ns_list is NULL:
424
+ return 0
425
+
426
+ # free all namespace declarations that remained in the list,
427
+ # except for those we should keep explicitly
428
+ cdef xmlNs* c_nsdef
429
+ for i in range(c_ns_list_len):
430
+ if prefixes_to_keep is not None:
431
+ if c_ns_list[i].ns.prefix and c_ns_list[i].ns.prefix in prefixes_to_keep:
432
+ continue
433
+ c_node = c_ns_list[i].node
434
+ c_nsdef = c_node.nsDef
435
+ if c_nsdef is c_ns_list[i].ns:
436
+ c_node.nsDef = c_node.nsDef.next
437
+ else:
438
+ while c_nsdef.next is not c_ns_list[i].ns:
439
+ c_nsdef = c_nsdef.next
440
+ c_nsdef.next = c_nsdef.next.next
441
+ tree.xmlFreeNs(c_ns_list[i].ns)
442
+
443
+ if c_ns_list is not NULL:
444
+ python.lxml_free(c_ns_list)
445
+ return 0
446
+
447
+ cdef xmlNs* _searchNsByHref(xmlNode* c_node, const_xmlChar* c_href, bint is_attribute) noexcept:
448
+ """Search a namespace declaration that covers a node (element or
449
+ attribute).
450
+
451
+ For attributes, try to find a prefixed namespace declaration
452
+ instead of the default namespaces. This helps in supporting
453
+ round-trips for attributes on elements with a different namespace.
454
+ """
455
+ cdef xmlNs* c_ns
456
+ cdef xmlNs* c_default_ns = NULL
457
+ cdef xmlNode* c_element
458
+ if c_href is NULL or c_node is NULL or c_node.type == tree.XML_ENTITY_REF_NODE:
459
+ return NULL
460
+ if tree.xmlStrcmp(c_href, tree.XML_XML_NAMESPACE) == 0:
461
+ # no special cases here, let libxml2 handle this
462
+ return tree.xmlSearchNsByHref(c_node.doc, c_node, c_href)
463
+ if c_node.type == tree.XML_ATTRIBUTE_NODE:
464
+ is_attribute = 1
465
+ while c_node is not NULL and c_node.type != tree.XML_ELEMENT_NODE:
466
+ c_node = c_node.parent
467
+ c_element = c_node
468
+ while c_node is not NULL:
469
+ if c_node.type == tree.XML_ELEMENT_NODE:
470
+ c_ns = c_node.nsDef
471
+ while c_ns is not NULL:
472
+ if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0:
473
+ if c_ns.prefix is NULL and is_attribute:
474
+ # for attributes, continue searching a named
475
+ # prefix, but keep the first default namespace
476
+ # declaration that we found
477
+ if c_default_ns is NULL:
478
+ c_default_ns = c_ns
479
+ elif tree.xmlSearchNs(
480
+ c_element.doc, c_element, c_ns.prefix) is c_ns:
481
+ # start node is in namespace scope => found!
482
+ return c_ns
483
+ c_ns = c_ns.next
484
+ if c_node is not c_element and c_node.ns is not NULL:
485
+ # optimise: the node may have the namespace itself
486
+ c_ns = c_node.ns
487
+ if c_ns.href is not NULL and tree.xmlStrcmp(c_href, c_ns.href) == 0:
488
+ if c_ns.prefix is NULL and is_attribute:
489
+ # for attributes, continue searching a named
490
+ # prefix, but keep the first default namespace
491
+ # declaration that we found
492
+ if c_default_ns is NULL:
493
+ c_default_ns = c_ns
494
+ elif tree.xmlSearchNs(
495
+ c_element.doc, c_element, c_ns.prefix) is c_ns:
496
+ # start node is in namespace scope => found!
497
+ return c_ns
498
+ c_node = c_node.parent
499
+ # nothing found => use a matching default namespace or fail
500
+ if c_default_ns is not NULL:
501
+ if tree.xmlSearchNs(c_element.doc, c_element, NULL) is c_default_ns:
502
+ return c_default_ns
503
+ return NULL
504
+
505
+ cdef int _replaceNodeByChildren(_Document doc, xmlNode* c_node) except -1:
506
+ # NOTE: this does not deallocate the node, just unlink it!
507
+ cdef xmlNode* c_parent
508
+ cdef xmlNode* c_child
509
+ if c_node.children is NULL:
510
+ tree.xmlUnlinkNode(c_node)
511
+ return 0
512
+
513
+ c_parent = c_node.parent
514
+ # fix parent links of children
515
+ c_child = c_node.children
516
+ while c_child is not NULL:
517
+ c_child.parent = c_parent
518
+ c_child = c_child.next
519
+
520
+ # fix namespace references of children if their parent's namespace
521
+ # declarations get lost
522
+ if c_node.nsDef is not NULL:
523
+ c_child = c_node.children
524
+ while c_child is not NULL:
525
+ moveNodeToDocument(doc, doc._c_doc, c_child)
526
+ c_child = c_child.next
527
+
528
+ # fix sibling links to/from child slice
529
+ if c_node.prev is NULL:
530
+ c_parent.children = c_node.children
531
+ else:
532
+ c_node.prev.next = c_node.children
533
+ c_node.children.prev = c_node.prev
534
+ if c_node.next is NULL:
535
+ c_parent.last = c_node.last
536
+ else:
537
+ c_node.next.prev = c_node.last
538
+ c_node.last.next = c_node.next
539
+
540
+ # unlink c_node
541
+ c_node.children = c_node.last = NULL
542
+ c_node.parent = c_node.next = c_node.prev = NULL
543
+ return 0
544
+
545
+ cdef unicode _attributeValue(xmlNode* c_element, xmlAttr* c_attrib_node):
546
+ c_href = _getNs(<xmlNode*>c_attrib_node)
547
+ value = tree.xmlGetNsProp(c_element, c_attrib_node.name, c_href)
548
+ try:
549
+ result = funicode(value)
550
+ finally:
551
+ tree.xmlFree(value)
552
+ return result
553
+
554
+ cdef unicode _attributeValueFromNsName(xmlNode* c_element,
555
+ const_xmlChar* c_href, const_xmlChar* c_name):
556
+ c_result = tree.xmlGetNsProp(c_element, c_name, c_href)
557
+ if c_result is NULL:
558
+ return None
559
+ try:
560
+ result = funicode(c_result)
561
+ finally:
562
+ tree.xmlFree(c_result)
563
+ return result
564
+
565
+ cdef object _getNodeAttributeValue(xmlNode* c_node, key, default):
566
+ ns, tag = _getNsTag(key)
567
+ c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
568
+ c_result = tree.xmlGetNsProp(c_node, _xcstr(tag), c_href)
569
+ if c_result is NULL:
570
+ # XXX free namespace that is not in use..?
571
+ return default
572
+ try:
573
+ result = funicode(c_result)
574
+ finally:
575
+ tree.xmlFree(c_result)
576
+ return result
577
+
578
+ cdef inline object _getAttributeValue(_Element element, key, default):
579
+ return _getNodeAttributeValue(element._c_node, key, default)
580
+
581
+ cdef int _setAttributeValue(_Element element, key, value) except -1:
582
+ cdef const_xmlChar* c_value
583
+ cdef xmlNs* c_ns
584
+ ns, tag = _getNsTag(key)
585
+ is_html = element._doc._parser._for_html
586
+ if not is_html:
587
+ _attributeValidOrRaise(tag)
588
+ c_tag = _xcstr(tag)
589
+ if value is None and is_html:
590
+ c_value = NULL
591
+ else:
592
+ if isinstance(value, QName):
593
+ value = _resolveQNameText(element, value)
594
+ else:
595
+ value = _utf8(value)
596
+ c_value = _xcstr(value)
597
+ if ns is None:
598
+ c_ns = NULL
599
+ else:
600
+ c_ns = element._doc._findOrBuildNodeNs(element._c_node, _xcstr(ns), NULL, 1)
601
+ tree.xmlSetNsProp(element._c_node, c_ns, c_tag, c_value)
602
+ return 0
603
+
604
+ cdef int _delAttribute(_Element element, key) except -1:
605
+ ns, tag = _getNsTag(key)
606
+ c_href = <const_xmlChar*>NULL if ns is None else _xcstr(ns)
607
+ if _delAttributeFromNsName(element._c_node, c_href, _xcstr(tag)):
608
+ raise KeyError, key
609
+ return 0
610
+
611
+ cdef int _delAttributeFromNsName(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
612
+ c_attr = tree.xmlHasNsProp(c_node, c_name, c_href)
613
+ if c_attr is NULL:
614
+ # XXX free namespace that is not in use..?
615
+ return -1
616
+ tree.xmlRemoveProp(c_attr)
617
+ return 0
618
+
619
+ cdef list _collectAttributes(xmlNode* c_node, int collecttype):
620
+ """Collect all attributes of a node in a list. Depending on collecttype,
621
+ it collects either the name (1), the value (2) or the name-value tuples.
622
+ """
623
+ cdef Py_ssize_t count
624
+ c_attr = c_node.properties
625
+ count = 0
626
+ while c_attr is not NULL:
627
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
628
+ count += 1
629
+ c_attr = c_attr.next
630
+
631
+ if not count:
632
+ return []
633
+
634
+ attributes = [None] * count
635
+ c_attr = c_node.properties
636
+ count = 0
637
+ while c_attr is not NULL:
638
+ if c_attr.type == tree.XML_ATTRIBUTE_NODE:
639
+ if collecttype == 1:
640
+ item = _namespacedName(<xmlNode*>c_attr)
641
+ elif collecttype == 2:
642
+ item = _attributeValue(c_node, c_attr)
643
+ else:
644
+ item = (_namespacedName(<xmlNode*>c_attr),
645
+ _attributeValue(c_node, c_attr))
646
+ attributes[count] = item
647
+ count += 1
648
+ c_attr = c_attr.next
649
+ return attributes
650
+
651
+ cdef object __RE_XML_ENCODING = re.compile(
652
+ r'^(<\?xml[^>]+)\s+encoding\s*=\s*["\'][^"\']*["\'](\s*\?>|)', re.U)
653
+
654
+ cdef object __REPLACE_XML_ENCODING = __RE_XML_ENCODING.sub
655
+ cdef object __HAS_XML_ENCODING = __RE_XML_ENCODING.match
656
+
657
+ cdef object _stripEncodingDeclaration(object xml_string):
658
+ # this is a hack to remove the XML encoding declaration from unicode
659
+ return __REPLACE_XML_ENCODING(r'\g<1>\g<2>', xml_string)
660
+
661
+ cdef bint _hasEncodingDeclaration(object xml_string) except -1:
662
+ # check if a (unicode) string has an XML encoding declaration
663
+ return __HAS_XML_ENCODING(xml_string) is not None
664
+
665
+ cdef inline bint _hasText(xmlNode* c_node) noexcept:
666
+ return c_node is not NULL and _textNodeOrSkip(c_node.children) is not NULL
667
+
668
+ cdef inline bint _hasTail(xmlNode* c_node) noexcept:
669
+ return c_node is not NULL and _textNodeOrSkip(c_node.next) is not NULL
670
+
671
+ cdef inline bint _hasNonWhitespaceTail(xmlNode* c_node) except -1:
672
+ return _hasNonWhitespaceText(c_node, tail=True)
673
+
674
+ cdef bint _hasNonWhitespaceText(xmlNode* c_node, bint tail=False) except -1:
675
+ c_text_node = c_node and _textNodeOrSkip(c_node.next if tail else c_node.children)
676
+ if c_text_node is NULL:
677
+ return False
678
+ while c_text_node is not NULL:
679
+ if c_text_node.content[0] != c'\0' and not _collectText(c_text_node).isspace():
680
+ return True
681
+ c_text_node = _textNodeOrSkip(c_text_node.next)
682
+ return False
683
+
684
+ cdef unicode _collectText(xmlNode* c_node):
685
+ """Collect all text nodes and return them as a unicode string.
686
+
687
+ Start collecting at c_node.
688
+
689
+ If there was no text to collect, return None
690
+ """
691
+ cdef Py_ssize_t scount
692
+ cdef xmlChar* c_text
693
+ cdef xmlNode* c_node_cur
694
+ # check for multiple text nodes
695
+ scount = 0
696
+ c_text = NULL
697
+ c_node_cur = c_node = _textNodeOrSkip(c_node)
698
+ while c_node_cur is not NULL:
699
+ if c_node_cur.content[0] != c'\0':
700
+ c_text = c_node_cur.content
701
+ scount += 1
702
+ c_node_cur = _textNodeOrSkip(c_node_cur.next)
703
+
704
+ # handle two most common cases first
705
+ if c_text is NULL:
706
+ return '' if scount > 0 else None
707
+ if scount == 1:
708
+ return funicode(c_text)
709
+
710
+ # the rest is not performance critical anymore
711
+ result = b''
712
+ while c_node is not NULL:
713
+ result += <unsigned char*>c_node.content
714
+ c_node = _textNodeOrSkip(c_node.next)
715
+ return funicode(<const_xmlChar*><unsigned char*>result)
716
+
717
+ cdef void _removeText(xmlNode* c_node) noexcept:
718
+ """Remove all text nodes.
719
+
720
+ Start removing at c_node.
721
+ """
722
+ cdef xmlNode* c_next
723
+ c_node = _textNodeOrSkip(c_node)
724
+ while c_node is not NULL:
725
+ c_next = _textNodeOrSkip(c_node.next)
726
+ tree.xmlUnlinkNode(c_node)
727
+ tree.xmlFreeNode(c_node)
728
+ c_node = c_next
729
+
730
+ cdef xmlNode* _createTextNode(xmlDoc* doc, value) except NULL:
731
+ cdef xmlNode* c_text_node
732
+ if isinstance(value, CDATA):
733
+ c_text_node = tree.xmlNewCDataBlock(
734
+ doc, _xcstr((<CDATA>value)._utf8_data),
735
+ python.PyBytes_GET_SIZE((<CDATA>value)._utf8_data))
736
+ else:
737
+ text = _utf8(value)
738
+ c_text_node = tree.xmlNewDocText(doc, _xcstr(text))
739
+ if not c_text_node:
740
+ raise MemoryError()
741
+ return c_text_node
742
+
743
+ cdef int _setNodeText(xmlNode* c_node, value) except -1:
744
+ # remove all text nodes at the start first
745
+ _removeText(c_node.children)
746
+ if value is None:
747
+ return 0
748
+ # now add new text node with value at start
749
+ c_text_node = _createTextNode(c_node.doc, value)
750
+ if c_node.children is NULL:
751
+ tree.xmlAddChild(c_node, c_text_node)
752
+ else:
753
+ tree.xmlAddPrevSibling(c_node.children, c_text_node)
754
+ return 0
755
+
756
+ cdef int _setTailText(xmlNode* c_node, value) except -1:
757
+ # remove all text nodes at the start first
758
+ _removeText(c_node.next)
759
+ if value is None:
760
+ return 0
761
+ # now append new text node with value
762
+ c_text_node = _createTextNode(c_node.doc, value)
763
+ tree.xmlAddNextSibling(c_node, c_text_node)
764
+ return 0
765
+
766
+ cdef bytes _resolveQNameText(_Element element, value):
767
+ cdef xmlNs* c_ns
768
+ ns, tag = _getNsTag(value)
769
+ if ns is None:
770
+ return tag
771
+ else:
772
+ c_ns = element._doc._findOrBuildNodeNs(
773
+ element._c_node, _xcstr(ns), NULL, 0)
774
+ return python.PyBytes_FromFormat('%s:%s', c_ns.prefix, _cstr(tag))
775
+
776
+ cdef inline bint _hasChild(xmlNode* c_node) noexcept:
777
+ return c_node is not NULL and _findChildForwards(c_node, 0) is not NULL
778
+
779
+ cdef inline Py_ssize_t _countElements(xmlNode* c_node) noexcept:
780
+ "Counts the elements within the following siblings and the node itself."
781
+ cdef Py_ssize_t count
782
+ count = 0
783
+ while c_node is not NULL:
784
+ if _isElement(c_node):
785
+ count += 1
786
+ c_node = c_node.next
787
+ return count
788
+
789
+ cdef int _findChildSlice(
790
+ slice sliceobject, xmlNode* c_parent,
791
+ xmlNode** c_start_node, Py_ssize_t* c_step, Py_ssize_t* c_length) except -1:
792
+ """Resolve a children slice.
793
+
794
+ Returns the start node, step size and the slice length in the
795
+ pointer arguments.
796
+ """
797
+ cdef Py_ssize_t start = 0, stop = 0, childcount
798
+ childcount = _countElements(c_parent.children)
799
+ if childcount == 0:
800
+ c_start_node[0] = NULL
801
+ c_length[0] = 0
802
+ if sliceobject.step is None:
803
+ c_step[0] = 1
804
+ else:
805
+ python._PyEval_SliceIndex(sliceobject.step, c_step)
806
+ return 0
807
+ python.PySlice_GetIndicesEx(
808
+ sliceobject, childcount, &start, &stop, c_step, c_length)
809
+ if start > childcount // 2:
810
+ c_start_node[0] = _findChildBackwards(c_parent, childcount - start - 1)
811
+ else:
812
+ c_start_node[0] = _findChild(c_parent, start)
813
+ return 0
814
+
815
+ cdef bint _isFullSlice(slice sliceobject) except -1:
816
+ """Conservative guess if this slice is a full slice as in ``s[:]``.
817
+ """
818
+ cdef Py_ssize_t step = 0
819
+ if sliceobject is None:
820
+ return 0
821
+ if sliceobject.start is None and \
822
+ sliceobject.stop is None:
823
+ if sliceobject.step is None:
824
+ return 1
825
+ python._PyEval_SliceIndex(sliceobject.step, &step)
826
+ if step == 1:
827
+ return 1
828
+ return 0
829
+ return 0
830
+
831
+ cdef _collectChildren(_Element element):
832
+ cdef xmlNode* c_node
833
+ cdef list result = []
834
+ c_node = element._c_node.children
835
+ if c_node is not NULL:
836
+ if not _isElement(c_node):
837
+ c_node = _nextElement(c_node)
838
+ while c_node is not NULL:
839
+ result.append(_elementFactory(element._doc, c_node))
840
+ c_node = _nextElement(c_node)
841
+ return result
842
+
843
+ cdef inline xmlNode* _findChild(xmlNode* c_node, Py_ssize_t index) noexcept:
844
+ if index < 0:
845
+ return _findChildBackwards(c_node, -index - 1)
846
+ else:
847
+ return _findChildForwards(c_node, index)
848
+
849
+ cdef inline xmlNode* _findChildForwards(xmlNode* c_node, Py_ssize_t index) noexcept:
850
+ """Return child element of c_node with index, or return NULL if not found.
851
+ """
852
+ cdef xmlNode* c_child
853
+ cdef Py_ssize_t c
854
+ c_child = c_node.children
855
+ c = 0
856
+ while c_child is not NULL:
857
+ if _isElement(c_child):
858
+ if c == index:
859
+ return c_child
860
+ c += 1
861
+ c_child = c_child.next
862
+ return NULL
863
+
864
+ cdef inline xmlNode* _findChildBackwards(xmlNode* c_node, Py_ssize_t index) noexcept:
865
+ """Return child element of c_node with index, or return NULL if not found.
866
+ Search from the end.
867
+ """
868
+ cdef xmlNode* c_child
869
+ cdef Py_ssize_t c
870
+ c_child = c_node.last
871
+ c = 0
872
+ while c_child is not NULL:
873
+ if _isElement(c_child):
874
+ if c == index:
875
+ return c_child
876
+ c += 1
877
+ c_child = c_child.prev
878
+ return NULL
879
+
880
+ cdef inline xmlNode* _textNodeOrSkip(xmlNode* c_node) noexcept nogil:
881
+ """Return the node if it's a text node. Skip over ignorable nodes in a
882
+ series of text nodes. Return NULL if a non-ignorable node is found.
883
+
884
+ This is used to skip over XInclude nodes when collecting adjacent text
885
+ nodes.
886
+ """
887
+ while c_node is not NULL:
888
+ if c_node.type == tree.XML_TEXT_NODE or \
889
+ c_node.type == tree.XML_CDATA_SECTION_NODE:
890
+ return c_node
891
+ elif c_node.type == tree.XML_XINCLUDE_START or \
892
+ c_node.type == tree.XML_XINCLUDE_END:
893
+ c_node = c_node.next
894
+ else:
895
+ return NULL
896
+ return NULL
897
+
898
+ cdef inline xmlNode* _nextElement(xmlNode* c_node) noexcept:
899
+ """Given a node, find the next sibling that is an element.
900
+ """
901
+ if c_node is NULL:
902
+ return NULL
903
+ c_node = c_node.next
904
+ while c_node is not NULL:
905
+ if _isElement(c_node):
906
+ return c_node
907
+ c_node = c_node.next
908
+ return NULL
909
+
910
+ cdef inline xmlNode* _previousElement(xmlNode* c_node) noexcept:
911
+ """Given a node, find the next sibling that is an element.
912
+ """
913
+ if c_node is NULL:
914
+ return NULL
915
+ c_node = c_node.prev
916
+ while c_node is not NULL:
917
+ if _isElement(c_node):
918
+ return c_node
919
+ c_node = c_node.prev
920
+ return NULL
921
+
922
+ cdef inline xmlNode* _parentElement(xmlNode* c_node) noexcept:
923
+ "Given a node, find the parent element."
924
+ if c_node is NULL or not _isElement(c_node):
925
+ return NULL
926
+ c_node = c_node.parent
927
+ if c_node is NULL or not _isElement(c_node):
928
+ return NULL
929
+ return c_node
930
+
931
+ cdef inline bint _tagMatches(xmlNode* c_node, const_xmlChar* c_href, const_xmlChar* c_name) noexcept:
932
+ """Tests if the node matches namespace URI and tag name.
933
+
934
+ A node matches if it matches both c_href and c_name.
935
+
936
+ A node matches c_href if any of the following is true:
937
+ * c_href is NULL
938
+ * its namespace is NULL and c_href is the empty string
939
+ * its namespace string equals the c_href string
940
+
941
+ A node matches c_name if any of the following is true:
942
+ * c_name is NULL
943
+ * its name string equals the c_name string
944
+ """
945
+ if c_node is NULL:
946
+ return 0
947
+ if c_node.type != tree.XML_ELEMENT_NODE:
948
+ # not an element, only succeed if we match everything
949
+ return c_name is NULL and c_href is NULL
950
+ if c_name is NULL:
951
+ if c_href is NULL:
952
+ # always match
953
+ return 1
954
+ else:
955
+ c_node_href = _getNs(c_node)
956
+ if c_node_href is NULL:
957
+ return c_href[0] == c'\0'
958
+ else:
959
+ return tree.xmlStrcmp(c_node_href, c_href) == 0
960
+ elif c_href is NULL:
961
+ if _getNs(c_node) is not NULL:
962
+ return 0
963
+ return c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0
964
+ elif c_node.name == c_name or tree.xmlStrcmp(c_node.name, c_name) == 0:
965
+ c_node_href = _getNs(c_node)
966
+ if c_node_href is NULL:
967
+ return c_href[0] == c'\0'
968
+ else:
969
+ return tree.xmlStrcmp(c_node_href, c_href) == 0
970
+ else:
971
+ return 0
972
+
973
+ cdef inline bint _tagMatchesExactly(xmlNode* c_node, qname* c_qname) noexcept:
974
+ """Tests if the node matches namespace URI and tag name.
975
+
976
+ This differs from _tagMatches() in that it does not consider a
977
+ NULL value in qname.href a wildcard, and that it expects the c_name
978
+ to be taken from the doc dict, i.e. it only compares the names by
979
+ address.
980
+
981
+ A node matches if it matches both href and c_name of the qname.
982
+
983
+ A node matches c_href if any of the following is true:
984
+ * its namespace is NULL and c_href is the empty string
985
+ * its namespace string equals the c_href string
986
+
987
+ A node matches c_name if any of the following is true:
988
+ * c_name is NULL
989
+ * its name string points to the same address (!) as c_name
990
+ """
991
+ return _nsTagMatchesExactly(_getNs(c_node), c_node.name, c_qname)
992
+
993
+ cdef inline bint _nsTagMatchesExactly(const_xmlChar* c_node_href,
994
+ const_xmlChar* c_node_name,
995
+ qname* c_qname) noexcept:
996
+ """Tests if name and namespace URI match those of c_qname.
997
+
998
+ This differs from _tagMatches() in that it does not consider a
999
+ NULL value in qname.href a wildcard, and that it expects the c_name
1000
+ to be taken from the doc dict, i.e. it only compares the names by
1001
+ address.
1002
+
1003
+ A node matches if it matches both href and c_name of the qname.
1004
+
1005
+ A node matches c_href if any of the following is true:
1006
+ * its namespace is NULL and c_href is the empty string
1007
+ * its namespace string equals the c_href string
1008
+
1009
+ A node matches c_name if any of the following is true:
1010
+ * c_name is NULL
1011
+ * its name string points to the same address (!) as c_name
1012
+ """
1013
+ cdef char* c_href
1014
+ if c_qname.c_name is not NULL and c_qname.c_name is not c_node_name:
1015
+ return 0
1016
+ if c_qname.href is NULL:
1017
+ return 1
1018
+ c_href = python.__cstr(c_qname.href)
1019
+ if c_href[0] == b'\0':
1020
+ return c_node_href is NULL or c_node_href[0] == b'\0'
1021
+ elif c_node_href is NULL:
1022
+ return 0
1023
+ else:
1024
+ return tree.xmlStrcmp(<const_xmlChar*>c_href, c_node_href) == 0
1025
+
1026
+ cdef Py_ssize_t _mapTagsToQnameMatchArray(xmlDoc* c_doc, list ns_tags,
1027
+ qname* c_ns_tags, bint force_into_dict) except -1:
1028
+ """Map a sequence of (name, namespace) pairs to a qname array for efficient
1029
+ matching with _tagMatchesExactly() above.
1030
+
1031
+ Note that each qname struct in the array owns its href byte string object
1032
+ if it is not NULL.
1033
+ """
1034
+ cdef Py_ssize_t count = 0, i
1035
+ cdef bytes ns, tag
1036
+ for ns, tag in ns_tags:
1037
+ if tag is None:
1038
+ c_tag = <const_xmlChar*>NULL
1039
+ elif force_into_dict:
1040
+ c_tag = tree.xmlDictLookup(c_doc.dict, _xcstr(tag), len(tag))
1041
+ if c_tag is NULL:
1042
+ # clean up before raising the error
1043
+ for i in xrange(count):
1044
+ cpython.ref.Py_XDECREF(c_ns_tags[i].href)
1045
+ raise MemoryError()
1046
+ else:
1047
+ c_tag = tree.xmlDictExists(c_doc.dict, _xcstr(tag), len(tag))
1048
+ if c_tag is NULL:
1049
+ # not in the dict => not in the document
1050
+ continue
1051
+ c_ns_tags[count].c_name = c_tag
1052
+ if ns is None:
1053
+ c_ns_tags[count].href = NULL
1054
+ else:
1055
+ cpython.ref.Py_INCREF(ns) # keep an owned reference!
1056
+ c_ns_tags[count].href = <python.PyObject*>ns
1057
+ count += 1
1058
+ return count
1059
+
1060
+ cdef int _removeNode(_Document doc, xmlNode* c_node) except -1:
1061
+ """Unlink and free a node and subnodes if possible. Otherwise, make sure
1062
+ it's self-contained.
1063
+ """
1064
+ cdef xmlNode* c_next
1065
+ c_next = c_node.next
1066
+ tree.xmlUnlinkNode(c_node)
1067
+ _moveTail(c_next, c_node)
1068
+ if not attemptDeallocation(c_node):
1069
+ # make namespaces absolute
1070
+ moveNodeToDocument(doc, c_node.doc, c_node)
1071
+ return 0
1072
+
1073
+ cdef int _removeSiblings(xmlNode* c_element, tree.xmlElementType node_type, bint with_tail) except -1:
1074
+ cdef xmlNode* c_node
1075
+ cdef xmlNode* c_next
1076
+ c_node = c_element.next
1077
+ while c_node is not NULL:
1078
+ c_next = _nextElement(c_node)
1079
+ if c_node.type == node_type:
1080
+ if with_tail:
1081
+ _removeText(c_node.next)
1082
+ tree.xmlUnlinkNode(c_node)
1083
+ attemptDeallocation(c_node)
1084
+ c_node = c_next
1085
+ c_node = c_element.prev
1086
+ while c_node is not NULL:
1087
+ c_next = _previousElement(c_node)
1088
+ if c_node.type == node_type:
1089
+ if with_tail:
1090
+ _removeText(c_node.next)
1091
+ tree.xmlUnlinkNode(c_node)
1092
+ attemptDeallocation(c_node)
1093
+ c_node = c_next
1094
+ return 0
1095
+
1096
+ cdef void _moveTail(xmlNode* c_tail, xmlNode* c_target) noexcept:
1097
+ cdef xmlNode* c_next
1098
+ # tail support: look for any text nodes trailing this node and
1099
+ # move them too
1100
+ c_tail = _textNodeOrSkip(c_tail)
1101
+ while c_tail is not NULL:
1102
+ c_next = _textNodeOrSkip(c_tail.next)
1103
+ c_target = tree.xmlAddNextSibling(c_target, c_tail)
1104
+ c_tail = c_next
1105
+
1106
+ cdef int _copyTail(xmlNode* c_tail, xmlNode* c_target) except -1:
1107
+ cdef xmlNode* c_new_tail
1108
+ # tail copying support: look for any text nodes trailing this node and
1109
+ # copy it to the target node
1110
+ c_tail = _textNodeOrSkip(c_tail)
1111
+ while c_tail is not NULL:
1112
+ if c_target.doc is not c_tail.doc:
1113
+ c_new_tail = tree.xmlDocCopyNode(c_tail, c_target.doc, 0)
1114
+ else:
1115
+ c_new_tail = tree.xmlCopyNode(c_tail, 0)
1116
+ if c_new_tail is NULL:
1117
+ raise MemoryError()
1118
+ c_target = tree.xmlAddNextSibling(c_target, c_new_tail)
1119
+ c_tail = _textNodeOrSkip(c_tail.next)
1120
+ return 0
1121
+
1122
+ cdef int _copyNonElementSiblings(xmlNode* c_node, xmlNode* c_target) except -1:
1123
+ cdef xmlNode* c_copy
1124
+ cdef xmlNode* c_sibling = c_node
1125
+ while c_sibling.prev != NULL and \
1126
+ (c_sibling.prev.type == tree.XML_PI_NODE or
1127
+ c_sibling.prev.type == tree.XML_COMMENT_NODE or
1128
+ c_sibling.prev.type == tree.XML_DTD_NODE):
1129
+ c_sibling = c_sibling.prev
1130
+ while c_sibling != c_node:
1131
+ if c_sibling.type == tree.XML_DTD_NODE:
1132
+ c_copy = <xmlNode*>_copyDtd(<tree.xmlDtd*>c_sibling)
1133
+ if c_sibling == <xmlNode*>c_node.doc.intSubset:
1134
+ c_target.doc.intSubset = <tree.xmlDtd*>c_copy
1135
+ else: # c_sibling == c_node.doc.extSubset
1136
+ c_target.doc.extSubset = <tree.xmlDtd*>c_copy
1137
+ else:
1138
+ c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1)
1139
+ if c_copy is NULL:
1140
+ raise MemoryError()
1141
+ tree.xmlAddPrevSibling(c_target, c_copy)
1142
+ c_sibling = c_sibling.next
1143
+ while c_sibling.next != NULL and \
1144
+ (c_sibling.next.type == tree.XML_PI_NODE or
1145
+ c_sibling.next.type == tree.XML_COMMENT_NODE):
1146
+ c_sibling = c_sibling.next
1147
+ c_copy = tree.xmlDocCopyNode(c_sibling, c_target.doc, 1)
1148
+ if c_copy is NULL:
1149
+ raise MemoryError()
1150
+ tree.xmlAddNextSibling(c_target, c_copy)
1151
+
1152
+ cdef int _deleteSlice(_Document doc, xmlNode* c_node,
1153
+ Py_ssize_t count, Py_ssize_t step) except -1:
1154
+ """Delete slice, ``count`` items starting with ``c_node`` with a step
1155
+ width of ``step``.
1156
+ """
1157
+ cdef xmlNode* c_next
1158
+ cdef Py_ssize_t c, i
1159
+ cdef _node_to_node_function next_element
1160
+ if c_node is NULL:
1161
+ return 0
1162
+ if step > 0:
1163
+ next_element = _nextElement
1164
+ else:
1165
+ step = -step
1166
+ next_element = _previousElement
1167
+ # now start deleting nodes
1168
+ c = 0
1169
+ c_next = c_node
1170
+ while c_node is not NULL and c < count:
1171
+ for i in range(step):
1172
+ c_next = next_element(c_next)
1173
+ if c_next is NULL:
1174
+ break
1175
+ _removeNode(doc, c_node)
1176
+ c += 1
1177
+ c_node = c_next
1178
+ return 0
1179
+
1180
+ cdef int _replaceSlice(_Element parent, xmlNode* c_node,
1181
+ Py_ssize_t slicelength, Py_ssize_t step,
1182
+ bint left_to_right, elements) except -1:
1183
+ """Replace the slice of ``count`` elements starting at ``c_node`` with
1184
+ positive step width ``step`` by the Elements in ``elements``. The
1185
+ direction is given by the boolean argument ``left_to_right``.
1186
+
1187
+ ``c_node`` may be NULL to indicate the end of the children list.
1188
+ """
1189
+ cdef xmlNode* c_orig_neighbour
1190
+ cdef xmlNode* c_next
1191
+ cdef xmlDoc* c_source_doc
1192
+ cdef _Element element
1193
+ cdef Py_ssize_t seqlength, i, c
1194
+ cdef _node_to_node_function next_element
1195
+ assert step > 0
1196
+ if left_to_right:
1197
+ next_element = _nextElement
1198
+ else:
1199
+ next_element = _previousElement
1200
+
1201
+ if not isinstance(elements, (list, tuple)):
1202
+ elements = list(elements)
1203
+
1204
+ if step != 1 or not left_to_right:
1205
+ # *replacing* children stepwise with list => check size!
1206
+ seqlength = len(elements)
1207
+ if seqlength != slicelength:
1208
+ raise ValueError, f"attempt to assign sequence of size {seqlength} " \
1209
+ f"to extended slice of size {slicelength}"
1210
+
1211
+ if c_node is NULL:
1212
+ # no children yet => add all elements straight away
1213
+ if left_to_right:
1214
+ for element in elements:
1215
+ assert element is not None, "Node must not be None"
1216
+ _appendChild(parent, element)
1217
+ else:
1218
+ for element in elements:
1219
+ assert element is not None, "Node must not be None"
1220
+ _prependChild(parent, element)
1221
+ return 0
1222
+
1223
+ # remove the elements first as some might be re-added
1224
+ if left_to_right:
1225
+ # L->R, remember left neighbour
1226
+ c_orig_neighbour = _previousElement(c_node)
1227
+ else:
1228
+ # R->L, remember right neighbour
1229
+ c_orig_neighbour = _nextElement(c_node)
1230
+
1231
+ # We remove the original slice elements one by one. Since we hold
1232
+ # a Python reference to all elements that we will insert, it is
1233
+ # safe to let _removeNode() try (and fail) to free them even if
1234
+ # the element itself or one of its descendents will be reinserted.
1235
+ c = 0
1236
+ c_next = c_node
1237
+ while c_node is not NULL and c < slicelength:
1238
+ for i in range(step):
1239
+ c_next = next_element(c_next)
1240
+ if c_next is NULL:
1241
+ break
1242
+ _removeNode(parent._doc, c_node)
1243
+ c += 1
1244
+ c_node = c_next
1245
+
1246
+ # make sure each element is inserted only once
1247
+ elements = iter(elements)
1248
+
1249
+ # find the first node right of the new insertion point
1250
+ if left_to_right:
1251
+ if c_orig_neighbour is not NULL:
1252
+ c_node = next_element(c_orig_neighbour)
1253
+ else:
1254
+ # before the first element
1255
+ c_node = _findChildForwards(parent._c_node, 0)
1256
+ elif c_orig_neighbour is NULL:
1257
+ # at the end, but reversed stepping
1258
+ # append one element and go to the next insertion point
1259
+ for element in elements:
1260
+ assert element is not None, "Node must not be None"
1261
+ _appendChild(parent, element)
1262
+ c_node = element._c_node
1263
+ if slicelength > 0:
1264
+ slicelength -= 1
1265
+ for i in range(1, step):
1266
+ c_node = next_element(c_node)
1267
+ if c_node is NULL:
1268
+ break
1269
+ break
1270
+ else:
1271
+ c_node = c_orig_neighbour
1272
+
1273
+ if left_to_right:
1274
+ # adjust step size after removing slice as we are not stepping
1275
+ # over the newly inserted elements
1276
+ step -= 1
1277
+
1278
+ # now insert elements where we removed them
1279
+ if c_node is not NULL:
1280
+ for element in elements:
1281
+ assert element is not None, "Node must not be None"
1282
+ _assertValidNode(element)
1283
+ # move element and tail over
1284
+ c_source_doc = element._c_node.doc
1285
+ c_next = element._c_node.next
1286
+ tree.xmlAddPrevSibling(c_node, element._c_node)
1287
+ _moveTail(c_next, element._c_node)
1288
+
1289
+ # integrate element into new document
1290
+ moveNodeToDocument(parent._doc, c_source_doc, element._c_node)
1291
+
1292
+ # stop at the end of the slice
1293
+ if slicelength > 0:
1294
+ slicelength -= 1
1295
+ for i in range(step):
1296
+ c_node = next_element(c_node)
1297
+ if c_node is NULL:
1298
+ break
1299
+ if c_node is NULL:
1300
+ break
1301
+ else:
1302
+ # everything inserted
1303
+ return 0
1304
+
1305
+ # append the remaining elements at the respective end
1306
+ if left_to_right:
1307
+ for element in elements:
1308
+ assert element is not None, "Node must not be None"
1309
+ _assertValidNode(element)
1310
+ _appendChild(parent, element)
1311
+ else:
1312
+ for element in elements:
1313
+ assert element is not None, "Node must not be None"
1314
+ _assertValidNode(element)
1315
+ _prependChild(parent, element)
1316
+
1317
+ return 0
1318
+
1319
+
1320
+ cdef int _linkChild(xmlNode* c_parent, xmlNode* c_node) except -1:
1321
+ """Adaptation of 'xmlAddChild()' that deep-fix the document links iteratively.
1322
+ """
1323
+ assert _isElement(c_node)
1324
+ c_node.parent = c_parent
1325
+ if c_parent.children is NULL:
1326
+ c_parent.children = c_parent.last = c_node
1327
+ else:
1328
+ c_node.prev = c_parent.last
1329
+ c_parent.last.next = c_node
1330
+ c_parent.last = c_node
1331
+
1332
+ _setTreeDoc(c_node, c_parent.doc)
1333
+ return 0
1334
+
1335
+
1336
+ cdef int _appendChild(_Element parent, _Element child) except -1:
1337
+ """Append a new child to a parent element.
1338
+ """
1339
+ c_node = child._c_node
1340
+ c_source_doc = c_node.doc
1341
+ # prevent cycles
1342
+ if _isAncestorOrSame(c_node, parent._c_node):
1343
+ raise ValueError("cannot append parent to itself")
1344
+ # store possible text node
1345
+ c_next = c_node.next
1346
+ # move node itself
1347
+ tree.xmlUnlinkNode(c_node)
1348
+ # do not call xmlAddChild() here since it would deep-traverse the tree
1349
+ _linkChild(parent._c_node, c_node)
1350
+ _moveTail(c_next, c_node)
1351
+ # uh oh, elements may be pointing to different doc when
1352
+ # parent element has moved; change them too..
1353
+ moveNodeToDocument(parent._doc, c_source_doc, c_node)
1354
+ return 0
1355
+
1356
+ cdef int _prependChild(_Element parent, _Element child) except -1:
1357
+ """Prepend a new child to a parent element.
1358
+ """
1359
+ c_node = child._c_node
1360
+ c_source_doc = c_node.doc
1361
+ # prevent cycles
1362
+ if _isAncestorOrSame(c_node, parent._c_node):
1363
+ raise ValueError("cannot append parent to itself")
1364
+ # store possible text node
1365
+ c_next = c_node.next
1366
+ # move node itself
1367
+ c_child = _findChildForwards(parent._c_node, 0)
1368
+ if c_child is NULL:
1369
+ tree.xmlUnlinkNode(c_node)
1370
+ # do not call xmlAddChild() here since it would deep-traverse the tree
1371
+ _linkChild(parent._c_node, c_node)
1372
+ else:
1373
+ tree.xmlAddPrevSibling(c_child, c_node)
1374
+ _moveTail(c_next, c_node)
1375
+ # uh oh, elements may be pointing to different doc when
1376
+ # parent element has moved; change them too..
1377
+ moveNodeToDocument(parent._doc, c_source_doc, c_node)
1378
+ return 0
1379
+
1380
+ cdef int _appendSibling(_Element element, _Element sibling) except -1:
1381
+ """Add a new sibling behind an element.
1382
+ """
1383
+ return _addSibling(element, sibling, as_next=True)
1384
+
1385
+ cdef int _prependSibling(_Element element, _Element sibling) except -1:
1386
+ """Add a new sibling before an element.
1387
+ """
1388
+ return _addSibling(element, sibling, as_next=False)
1389
+
1390
+ cdef int _addSibling(_Element element, _Element sibling, bint as_next) except -1:
1391
+ c_node = sibling._c_node
1392
+ c_source_doc = c_node.doc
1393
+ # prevent cycles
1394
+ if _isAncestorOrSame(c_node, element._c_node):
1395
+ if element._c_node is c_node:
1396
+ return 0 # nothing to do
1397
+ raise ValueError("cannot add ancestor as sibling, please break cycle first")
1398
+ # store possible text node
1399
+ c_next = c_node.next
1400
+ # move node itself
1401
+ if as_next:
1402
+ # must insert after any tail text
1403
+ c_next_node = _nextElement(element._c_node)
1404
+ if c_next_node is NULL:
1405
+ c_next_node = element._c_node
1406
+ while c_next_node.next:
1407
+ c_next_node = c_next_node.next
1408
+ tree.xmlAddNextSibling(c_next_node, c_node)
1409
+ else:
1410
+ tree.xmlAddPrevSibling(c_next_node, c_node)
1411
+ else:
1412
+ tree.xmlAddPrevSibling(element._c_node, c_node)
1413
+ _moveTail(c_next, c_node)
1414
+ # uh oh, elements may be pointing to different doc when
1415
+ # parent element has moved; change them too..
1416
+ moveNodeToDocument(element._doc, c_source_doc, c_node)
1417
+ return 0
1418
+
1419
+ cdef inline bint isutf8(const_xmlChar* s) noexcept:
1420
+ cdef xmlChar c = s[0]
1421
+ while c != c'\0':
1422
+ if c & 0x80:
1423
+ return True
1424
+ s += 1
1425
+ c = s[0]
1426
+ return False
1427
+
1428
+ cdef bint isutf8l(const_xmlChar* s, size_t length) noexcept:
1429
+ """
1430
+ Search for non-ASCII characters in the string, knowing its length in advance.
1431
+ """
1432
+ cdef unsigned int i
1433
+ cdef unsigned long non_ascii_mask
1434
+ cdef const unsigned long *lptr = <const unsigned long*> s
1435
+
1436
+ cdef const unsigned long *end = lptr + length // sizeof(unsigned long)
1437
+ if length >= sizeof(non_ascii_mask):
1438
+ # Build constant 0x80808080... mask (and let the C compiler fold it).
1439
+ non_ascii_mask = 0
1440
+ for i in range(sizeof(non_ascii_mask) // 2):
1441
+ non_ascii_mask = (non_ascii_mask << 16) | 0x8080
1442
+
1443
+ # Advance to long-aligned character before we start reading longs.
1444
+ while (<size_t>s) % sizeof(unsigned long) and s < <const_xmlChar *>end:
1445
+ if s[0] & 0x80:
1446
+ return True
1447
+ s += 1
1448
+
1449
+ # Read one long at a time
1450
+ lptr = <const unsigned long*> s
1451
+ while lptr < end:
1452
+ if lptr[0] & non_ascii_mask:
1453
+ return True
1454
+ lptr += 1
1455
+ s = <const_xmlChar *>lptr
1456
+
1457
+ while s < (<const_xmlChar *>end + length % sizeof(unsigned long)):
1458
+ if s[0] & 0x80:
1459
+ return True
1460
+ s += 1
1461
+
1462
+ return False
1463
+
1464
+ cdef int _is_valid_xml_ascii(bytes pystring) except -1:
1465
+ """Check if a string is XML ascii content."""
1466
+ cdef signed char ch
1467
+ # When ch is a *signed* char, non-ascii characters are negative integers
1468
+ # and xmlIsChar_ch does not accept them.
1469
+ for ch in pystring:
1470
+ if not tree.xmlIsChar_ch(ch):
1471
+ return 0
1472
+ return 1
1473
+
1474
+ cdef bint _is_valid_xml_utf8(bytes pystring) except -1:
1475
+ """Check if a string is like valid UTF-8 XML content."""
1476
+ cdef const_xmlChar* s = _xcstr(pystring)
1477
+ cdef const_xmlChar* c_end = s + len(pystring)
1478
+ cdef unsigned long next3 = 0
1479
+ if s < c_end - 2:
1480
+ next3 = (s[0] << 8) | (s[1])
1481
+
1482
+ while s < c_end - 2:
1483
+ next3 = 0x00ffffff & ((next3 << 8) | s[2])
1484
+ if s[0] & 0x80:
1485
+ # 0xefbfbe and 0xefbfbf are utf-8 encodings of
1486
+ # forbidden characters \ufffe and \uffff
1487
+ if next3 == 0x00efbfbe or next3 == 0x00efbfbf:
1488
+ return 0
1489
+ # 0xeda080 and 0xedbfbf are utf-8 encodings of
1490
+ # \ud800 and \udfff. Anything between them (inclusive)
1491
+ # is forbidden, because they are surrogate blocks in utf-16.
1492
+ if 0x00eda080 <= next3 <= 0x00edbfbf:
1493
+ return 0
1494
+ elif not tree.xmlIsChar_ch(s[0]):
1495
+ return 0 # invalid ascii char
1496
+ s += 1
1497
+
1498
+ while s < c_end:
1499
+ if not s[0] & 0x80 and not tree.xmlIsChar_ch(s[0]):
1500
+ return 0 # invalid ascii char
1501
+ s += 1
1502
+
1503
+ return 1
1504
+
1505
+ cdef inline unicode funicodeOrNone(const_xmlChar* s):
1506
+ return funicode(s) if s is not NULL else None
1507
+
1508
+ cdef inline unicode funicodeOrEmpty(const_xmlChar* s):
1509
+ return funicode(s) if s is not NULL else ''
1510
+
1511
+ cdef unicode funicode(const_xmlChar* s):
1512
+ return s.decode('UTF-8')
1513
+
1514
+ cdef bytes _utf8(object s):
1515
+ """Test if a string is valid user input and encode it to UTF-8.
1516
+ Reject all bytes/unicode input that contains non-XML characters.
1517
+ Reject all bytes input that contains non-ASCII characters.
1518
+ """
1519
+ cdef int valid
1520
+ cdef bytes utf8_string
1521
+ if isinstance(s, unicode):
1522
+ utf8_string = (<unicode>s).encode('utf8')
1523
+ valid = _is_valid_xml_utf8(utf8_string)
1524
+ elif isinstance(s, (bytes, bytearray)):
1525
+ utf8_string = s if type(s) is bytes else bytes(s)
1526
+ valid = _is_valid_xml_ascii(utf8_string)
1527
+ else:
1528
+ raise TypeError("Argument must be bytes or unicode, got '%.200s'" % type(s).__name__)
1529
+ if not valid:
1530
+ raise ValueError(
1531
+ "All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters")
1532
+ return utf8_string
1533
+
1534
+
1535
+ cdef bytes _utf8orNone(object s):
1536
+ return _utf8(s) if s is not None else None
1537
+
1538
+
1539
+ cdef enum:
1540
+ NO_FILE_PATH = 0
1541
+ ABS_UNIX_FILE_PATH = 1
1542
+ ABS_WIN_FILE_PATH = 2
1543
+ REL_FILE_PATH = 3
1544
+
1545
+
1546
+ cdef bint _isFilePath(const_xmlChar* c_path) noexcept:
1547
+ "simple heuristic to see if a path is a filename"
1548
+ cdef xmlChar c
1549
+ # test if it looks like an absolute Unix path or a Windows network path
1550
+ if c_path[0] == c'/':
1551
+ return ABS_UNIX_FILE_PATH
1552
+
1553
+ # test if it looks like an absolute Windows path or URL
1554
+ if c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z':
1555
+ c_path += 1
1556
+ if c_path[0] == c':' and c_path[1] in b'\0\\':
1557
+ return ABS_WIN_FILE_PATH # C: or C:\...
1558
+
1559
+ # test if it looks like a URL with scheme://
1560
+ while c'a' <= c_path[0] <= c'z' or c'A' <= c_path[0] <= c'Z':
1561
+ c_path += 1
1562
+ if c_path[0] == c':' and c_path[1] == c'/' and c_path[2] == c'/':
1563
+ return NO_FILE_PATH
1564
+
1565
+ # assume it's a relative path
1566
+ return REL_FILE_PATH
1567
+
1568
+
1569
+ cdef object _getFSPathOrObject(object obj):
1570
+ """
1571
+ Get the __fspath__ attribute of an object if it exists.
1572
+ Otherwise, the original object is returned.
1573
+ """
1574
+ if _isString(obj):
1575
+ return obj
1576
+ try:
1577
+ return python.PyOS_FSPath(obj)
1578
+ except TypeError:
1579
+ return obj
1580
+
1581
+
1582
+ cdef object _encodeFilename(object filename):
1583
+ """Make sure a filename is 8-bit encoded (or None).
1584
+ """
1585
+ if filename is None:
1586
+ return None
1587
+ elif isinstance(filename, bytes):
1588
+ return filename
1589
+ elif isinstance(filename, unicode):
1590
+ filename8 = (<unicode>filename).encode('utf8')
1591
+ if _isFilePath(<unsigned char*>filename8):
1592
+ try:
1593
+ return python.PyUnicode_AsEncodedString(
1594
+ filename, _C_FILENAME_ENCODING, NULL)
1595
+ except UnicodeEncodeError:
1596
+ pass
1597
+ return filename8
1598
+ else:
1599
+ raise TypeError("Argument must be string or unicode.")
1600
+
1601
+ cdef object _decodeFilename(const_xmlChar* c_path):
1602
+ """Make the filename a unicode string if we are in Py3.
1603
+ """
1604
+ return _decodeFilenameWithLength(c_path, tree.xmlStrlen(c_path))
1605
+
1606
+ cdef object _decodeFilenameWithLength(const_xmlChar* c_path, size_t c_len):
1607
+ """Make the filename a unicode string if we are in Py3.
1608
+ """
1609
+ if _isFilePath(c_path):
1610
+ try:
1611
+ return python.PyUnicode_Decode(
1612
+ <const_char*>c_path, c_len, _C_FILENAME_ENCODING, NULL)
1613
+ except UnicodeDecodeError:
1614
+ pass
1615
+ try:
1616
+ return (<unsigned char*>c_path)[:c_len].decode('UTF-8')
1617
+ except UnicodeDecodeError:
1618
+ # this is a stupid fallback, but it might still work...
1619
+ return (<unsigned char*>c_path)[:c_len].decode('latin-1', 'replace')
1620
+
1621
+ cdef object _encodeFilenameUTF8(object filename):
1622
+ """Recode filename as UTF-8. Tries ASCII, local filesystem encoding and
1623
+ UTF-8 as source encoding.
1624
+ """
1625
+ cdef char* c_filename
1626
+ if filename is None:
1627
+ return None
1628
+ elif isinstance(filename, bytes):
1629
+ if not isutf8l(<bytes>filename, len(<bytes>filename)):
1630
+ # plain ASCII!
1631
+ return filename
1632
+ c_filename = _cstr(<bytes>filename)
1633
+ try:
1634
+ # try to decode with default encoding
1635
+ filename = python.PyUnicode_Decode(
1636
+ c_filename, len(<bytes>filename),
1637
+ _C_FILENAME_ENCODING, NULL)
1638
+ except UnicodeDecodeError as decode_exc:
1639
+ try:
1640
+ # try if it's proper UTF-8
1641
+ (<bytes>filename).decode('utf8')
1642
+ return filename
1643
+ except UnicodeDecodeError:
1644
+ raise decode_exc # otherwise re-raise original exception
1645
+ if isinstance(filename, unicode):
1646
+ return (<unicode>filename).encode('utf8')
1647
+ else:
1648
+ raise TypeError("Argument must be string or unicode.")
1649
+
1650
+ cdef tuple _getNsTag(tag):
1651
+ """Given a tag, find namespace URI and tag name.
1652
+ Return None for NS uri if no namespace URI provided.
1653
+ """
1654
+ return __getNsTag(tag, 0)
1655
+
1656
+ cdef tuple _getNsTagWithEmptyNs(tag):
1657
+ """Given a tag, find namespace URI and tag name. Return None for NS uri
1658
+ if no namespace URI provided, or the empty string if namespace
1659
+ part is '{}'.
1660
+ """
1661
+ return __getNsTag(tag, 1)
1662
+
1663
+ cdef tuple __getNsTag(tag, bint empty_ns):
1664
+ cdef char* c_tag
1665
+ cdef char* c_ns_end
1666
+ cdef Py_ssize_t taglen
1667
+ cdef Py_ssize_t nslen
1668
+ cdef bytes ns = None
1669
+ # _isString() is much faster than isinstance()
1670
+ if not _isString(tag) and isinstance(tag, QName):
1671
+ tag = (<QName>tag).text
1672
+ tag = _utf8(tag)
1673
+ c_tag = _cstr(tag)
1674
+ if c_tag[0] == c'{':
1675
+ c_tag += 1
1676
+ c_ns_end = cstring_h.strchr(c_tag, c'}')
1677
+ if c_ns_end is NULL:
1678
+ raise ValueError, "Invalid tag name"
1679
+ nslen = c_ns_end - c_tag
1680
+ taglen = python.PyBytes_GET_SIZE(tag) - nslen - 2
1681
+ if taglen == 0:
1682
+ raise ValueError, "Empty tag name"
1683
+ if nslen > 0:
1684
+ ns = <bytes>c_tag[:nslen]
1685
+ elif empty_ns:
1686
+ ns = b''
1687
+ tag = <bytes>c_ns_end[1:taglen+1]
1688
+ elif python.PyBytes_GET_SIZE(tag) == 0:
1689
+ raise ValueError, "Empty tag name"
1690
+ return ns, tag
1691
+
1692
+ cdef inline int _pyXmlNameIsValid(name_utf8):
1693
+ return _xmlNameIsValid(_xcstr(name_utf8)) and b':' not in name_utf8
1694
+
1695
+ cdef inline int _pyHtmlNameIsValid(name_utf8):
1696
+ return _htmlNameIsValid(_xcstr(name_utf8))
1697
+
1698
+ cdef inline int _xmlNameIsValid(const_xmlChar* c_name) noexcept:
1699
+ return tree.xmlValidateNameValue(c_name)
1700
+
1701
+ cdef int _htmlNameIsValid(const_xmlChar* c_name) noexcept:
1702
+ if c_name is NULL or c_name[0] == c'\0':
1703
+ return 0
1704
+ while c_name[0] != c'\0':
1705
+ if c_name[0] in b'&<>/"\'\t\n\x0B\x0C\r ':
1706
+ return 0
1707
+ c_name += 1
1708
+ return 1
1709
+
1710
+ cdef bint _characterReferenceIsValid(const_xmlChar* c_name) noexcept:
1711
+ cdef bint is_hex
1712
+ if c_name[0] == c'x':
1713
+ c_name += 1
1714
+ is_hex = 1
1715
+ else:
1716
+ is_hex = 0
1717
+ if c_name[0] == c'\0':
1718
+ return 0
1719
+ while c_name[0] != c'\0':
1720
+ if c_name[0] < c'0' or c_name[0] > c'9':
1721
+ if not is_hex:
1722
+ return 0
1723
+ if not (c'a' <= c_name[0] <= c'f'):
1724
+ if not (c'A' <= c_name[0] <= c'F'):
1725
+ return 0
1726
+ c_name += 1
1727
+ return 1
1728
+
1729
+ cdef int _tagValidOrRaise(tag_utf) except -1:
1730
+ if not _pyXmlNameIsValid(tag_utf):
1731
+ raise ValueError(f"Invalid tag name {(<bytes>tag_utf).decode('utf8')!r}")
1732
+ return 0
1733
+
1734
+ cdef int _htmlTagValidOrRaise(tag_utf) except -1:
1735
+ if not _pyHtmlNameIsValid(tag_utf):
1736
+ raise ValueError(f"Invalid HTML tag name {(<bytes>tag_utf).decode('utf8')!r}")
1737
+ return 0
1738
+
1739
+ cdef int _attributeValidOrRaise(name_utf) except -1:
1740
+ if not _pyXmlNameIsValid(name_utf):
1741
+ raise ValueError(f"Invalid attribute name {(<bytes>name_utf).decode('utf8')!r}")
1742
+ return 0
1743
+
1744
+ cdef int _prefixValidOrRaise(tag_utf) except -1:
1745
+ if not _pyXmlNameIsValid(tag_utf):
1746
+ raise ValueError(f"Invalid namespace prefix {(<bytes>tag_utf).decode('utf8')!r}")
1747
+ return 0
1748
+
1749
+ cdef int _uriValidOrRaise(uri_utf) except -1:
1750
+ cdef uri.xmlURI* c_uri = uri.xmlParseURI(_cstr(uri_utf))
1751
+ if c_uri is NULL:
1752
+ raise ValueError(f"Invalid namespace URI {(<bytes>uri_utf).decode('utf8')!r}")
1753
+ uri.xmlFreeURI(c_uri)
1754
+ return 0
1755
+
1756
+ cdef inline unicode _namespacedName(xmlNode* c_node):
1757
+ return _namespacedNameFromNsName(_getNs(c_node), c_node.name)
1758
+
1759
+
1760
+ cdef unicode _namespacedNameFromNsName(const_xmlChar* c_href, const_xmlChar* c_name):
1761
+ name = funicode(c_name)
1762
+ if c_href is NULL:
1763
+ return name
1764
+ href = funicode(c_href)
1765
+ return f"{{{href}}}{name}"
1766
+
1767
+
1768
+ cdef _getFilenameForFile(source):
1769
+ """Given a Python File or Gzip object, give filename back.
1770
+
1771
+ Returns None if not a file object.
1772
+ """
1773
+ # urllib2 provides a geturl() method
1774
+ try:
1775
+ return source.geturl()
1776
+ except:
1777
+ pass
1778
+ # file instances have a name attribute
1779
+ try:
1780
+ filename = source.name
1781
+ if _isString(filename):
1782
+ return os_path_abspath(filename)
1783
+ except:
1784
+ pass
1785
+ # gzip file instances have a filename attribute (before Py3k)
1786
+ try:
1787
+ filename = source.filename
1788
+ if _isString(filename):
1789
+ return os_path_abspath(filename)
1790
+ except:
1791
+ pass
1792
+ # can't determine filename
1793
+ return None
venv/lib/python3.10/site-packages/lxml/builder.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (112 kB). View file
 
venv/lib/python3.10/site-packages/lxml/builder.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=2
2
+
3
+ #
4
+ # Element generator factory by Fredrik Lundh.
5
+ #
6
+ # Source:
7
+ # http://online.effbot.org/2006_11_01_archive.htm#et-builder
8
+ # http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/builder.py
9
+ #
10
+ # --------------------------------------------------------------------
11
+ # The ElementTree toolkit is
12
+ #
13
+ # Copyright (c) 1999-2004 by Fredrik Lundh
14
+ #
15
+ # By obtaining, using, and/or copying this software and/or its
16
+ # associated documentation, you agree that you have read, understood,
17
+ # and will comply with the following terms and conditions:
18
+ #
19
+ # Permission to use, copy, modify, and distribute this software and
20
+ # its associated documentation for any purpose and without fee is
21
+ # hereby granted, provided that the above copyright notice appears in
22
+ # all copies, and that both that copyright notice and this permission
23
+ # notice appear in supporting documentation, and that the name of
24
+ # Secret Labs AB or the author not be used in advertising or publicity
25
+ # pertaining to distribution of the software without specific, written
26
+ # prior permission.
27
+ #
28
+ # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
29
+ # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
30
+ # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
31
+ # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
32
+ # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
33
+ # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
34
+ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
35
+ # OF THIS SOFTWARE.
36
+ # --------------------------------------------------------------------
37
+
38
+ """
39
+ The ``E`` Element factory for generating XML documents.
40
+ """
41
+
42
+
43
+ import lxml.etree as ET
44
+ _QName = ET.QName
45
+
46
+ from functools import partial
47
+
48
+ try:
49
+ basestring
50
+ except NameError:
51
+ basestring = str
52
+
53
+ try:
54
+ unicode
55
+ except NameError:
56
+ unicode = str
57
+
58
+
59
+ class ElementMaker:
60
+ """Element generator factory.
61
+
62
+ Unlike the ordinary Element factory, the E factory allows you to pass in
63
+ more than just a tag and some optional attributes; you can also pass in
64
+ text and other elements. The text is added as either text or tail
65
+ attributes, and elements are inserted at the right spot. Some small
66
+ examples::
67
+
68
+ >>> from lxml import etree as ET
69
+ >>> from lxml.builder import E
70
+
71
+ >>> ET.tostring(E("tag"))
72
+ '<tag/>'
73
+ >>> ET.tostring(E("tag", "text"))
74
+ '<tag>text</tag>'
75
+ >>> ET.tostring(E("tag", "text", key="value"))
76
+ '<tag key="value">text</tag>'
77
+ >>> ET.tostring(E("tag", E("subtag", "text"), "tail"))
78
+ '<tag><subtag>text</subtag>tail</tag>'
79
+
80
+ For simple tags, the factory also allows you to write ``E.tag(...)`` instead
81
+ of ``E('tag', ...)``::
82
+
83
+ >>> ET.tostring(E.tag())
84
+ '<tag/>'
85
+ >>> ET.tostring(E.tag("text"))
86
+ '<tag>text</tag>'
87
+ >>> ET.tostring(E.tag(E.subtag("text"), "tail"))
88
+ '<tag><subtag>text</subtag>tail</tag>'
89
+
90
+ Here's a somewhat larger example; this shows how to generate HTML
91
+ documents, using a mix of prepared factory functions for inline elements,
92
+ nested ``E.tag`` calls, and embedded XHTML fragments::
93
+
94
+ # some common inline elements
95
+ A = E.a
96
+ I = E.i
97
+ B = E.b
98
+
99
+ def CLASS(v):
100
+ # helper function, 'class' is a reserved word
101
+ return {'class': v}
102
+
103
+ page = (
104
+ E.html(
105
+ E.head(
106
+ E.title("This is a sample document")
107
+ ),
108
+ E.body(
109
+ E.h1("Hello!", CLASS("title")),
110
+ E.p("This is a paragraph with ", B("bold"), " text in it!"),
111
+ E.p("This is another paragraph, with a ",
112
+ A("link", href="http://www.python.org"), "."),
113
+ E.p("Here are some reserved characters: <spam&egg>."),
114
+ ET.XML("<p>And finally, here is an embedded XHTML fragment.</p>"),
115
+ )
116
+ )
117
+ )
118
+
119
+ print ET.tostring(page)
120
+
121
+ Here's a prettyprinted version of the output from the above script::
122
+
123
+ <html>
124
+ <head>
125
+ <title>This is a sample document</title>
126
+ </head>
127
+ <body>
128
+ <h1 class="title">Hello!</h1>
129
+ <p>This is a paragraph with <b>bold</b> text in it!</p>
130
+ <p>This is another paragraph, with <a href="http://www.python.org">link</a>.</p>
131
+ <p>Here are some reserved characters: &lt;spam&amp;egg&gt;.</p>
132
+ <p>And finally, here is an embedded XHTML fragment.</p>
133
+ </body>
134
+ </html>
135
+
136
+ For namespace support, you can pass a namespace map (``nsmap``)
137
+ and/or a specific target ``namespace`` to the ElementMaker class::
138
+
139
+ >>> E = ElementMaker(namespace="http://my.ns/")
140
+ >>> print(ET.tostring( E.test ))
141
+ <test xmlns="http://my.ns/"/>
142
+
143
+ >>> E = ElementMaker(namespace="http://my.ns/", nsmap={'p':'http://my.ns/'})
144
+ >>> print(ET.tostring( E.test ))
145
+ <p:test xmlns:p="http://my.ns/"/>
146
+ """
147
+
148
+ def __init__(self, typemap=None,
149
+ namespace=None, nsmap=None, makeelement=None):
150
+ self._namespace = '{' + namespace + '}' if namespace is not None else None
151
+ self._nsmap = dict(nsmap) if nsmap else None
152
+
153
+ assert makeelement is None or callable(makeelement)
154
+ self._makeelement = makeelement if makeelement is not None else ET.Element
155
+
156
+ # initialize the default type map functions for this element factory
157
+ typemap = dict(typemap) if typemap else {}
158
+
159
+ def add_text(elem, item):
160
+ try:
161
+ last_child = elem[-1]
162
+ except IndexError:
163
+ elem.text = (elem.text or "") + item
164
+ else:
165
+ last_child.tail = (last_child.tail or "") + item
166
+
167
+ def add_cdata(elem, cdata):
168
+ if elem.text:
169
+ raise ValueError("Can't add a CDATA section. Element already has some text: %r" % elem.text)
170
+ elem.text = cdata
171
+
172
+ if str not in typemap:
173
+ typemap[str] = add_text
174
+ if unicode not in typemap:
175
+ typemap[unicode] = add_text
176
+ if ET.CDATA not in typemap:
177
+ typemap[ET.CDATA] = add_cdata
178
+
179
+ def add_dict(elem, item):
180
+ attrib = elem.attrib
181
+ for k, v in item.items():
182
+ if isinstance(v, basestring):
183
+ attrib[k] = v
184
+ else:
185
+ attrib[k] = typemap[type(v)](None, v)
186
+
187
+ if dict not in typemap:
188
+ typemap[dict] = add_dict
189
+
190
+ self._typemap = typemap
191
+
192
+ def __call__(self, tag, *children, **attrib):
193
+ typemap = self._typemap
194
+
195
+ # We'll usually get a 'str', and the compiled type check is very fast.
196
+ if not isinstance(tag, str) and isinstance(tag, _QName):
197
+ # A QName is explicitly qualified, do not look at self._namespace.
198
+ tag = tag.text
199
+ elif self._namespace is not None and tag[0] != '{':
200
+ tag = self._namespace + tag
201
+ elem = self._makeelement(tag, nsmap=self._nsmap)
202
+ if attrib:
203
+ typemap[dict](elem, attrib)
204
+
205
+ for item in children:
206
+ if callable(item):
207
+ item = item()
208
+ t = typemap.get(type(item))
209
+ if t is None:
210
+ if ET.iselement(item):
211
+ elem.append(item)
212
+ continue
213
+ for basetype in type(item).__mro__:
214
+ # See if the typemap knows of any of this type's bases.
215
+ t = typemap.get(basetype)
216
+ if t is not None:
217
+ break
218
+ else:
219
+ raise TypeError("bad argument type: %s(%r)" %
220
+ (type(item).__name__, item))
221
+ v = t(elem, item)
222
+ if v:
223
+ typemap.get(type(v))(elem, v)
224
+
225
+ return elem
226
+
227
+ def __getattr__(self, tag):
228
+ return partial(self, tag)
229
+
230
+
231
+ # create factory object
232
+ E = ElementMaker()
venv/lib/python3.10/site-packages/lxml/classlookup.pxi ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configurable Element class lookup
2
+
3
+ ################################################################################
4
+ # Custom Element classes
5
+
6
+ cdef public class ElementBase(_Element) [ type LxmlElementBaseType,
7
+ object LxmlElementBase ]:
8
+ """ElementBase(*children, attrib=None, nsmap=None, **_extra)
9
+
10
+ The public Element class. All custom Element classes must inherit
11
+ from this one. To create an Element, use the `Element()` factory.
12
+
13
+ BIG FAT WARNING: Subclasses *must not* override __init__ or
14
+ __new__ as it is absolutely undefined when these objects will be
15
+ created or destroyed. All persistent state of Elements must be
16
+ stored in the underlying XML. If you really need to initialize
17
+ the object after creation, you can implement an ``_init(self)``
18
+ method that will be called directly after object creation.
19
+
20
+ Subclasses of this class can be instantiated to create a new
21
+ Element. By default, the tag name will be the class name and the
22
+ namespace will be empty. You can modify this with the following
23
+ class attributes:
24
+
25
+ * TAG - the tag name, possibly containing a namespace in Clark
26
+ notation
27
+
28
+ * NAMESPACE - the default namespace URI, unless provided as part
29
+ of the TAG attribute.
30
+
31
+ * HTML - flag if the class is an HTML tag, as opposed to an XML
32
+ tag. This only applies to un-namespaced tags and defaults to
33
+ false (i.e. XML).
34
+
35
+ * PARSER - the parser that provides the configuration for the
36
+ newly created document. Providing an HTML parser here will
37
+ default to creating an HTML element.
38
+
39
+ In user code, the latter three are commonly inherited in class
40
+ hierarchies that implement a common namespace.
41
+ """
42
+ def __init__(self, *children, attrib=None, nsmap=None, **_extra):
43
+ """ElementBase(*children, attrib=None, nsmap=None, **_extra)
44
+ """
45
+ cdef bint is_html = 0
46
+ cdef _BaseParser parser
47
+ cdef _Element last_child
48
+ # don't use normal attribute access as it might be overridden
49
+ _getattr = object.__getattribute__
50
+ try:
51
+ namespace = _utf8(_getattr(self, 'NAMESPACE'))
52
+ except AttributeError:
53
+ namespace = None
54
+ try:
55
+ ns, tag = _getNsTag(_getattr(self, 'TAG'))
56
+ if ns is not None:
57
+ namespace = ns
58
+ except AttributeError:
59
+ tag = _utf8(_getattr(_getattr(self, '__class__'), '__name__'))
60
+ if b'.' in tag:
61
+ tag = tag.split(b'.')[-1]
62
+ try:
63
+ parser = _getattr(self, 'PARSER')
64
+ except AttributeError:
65
+ parser = None
66
+ for child in children:
67
+ if isinstance(child, _Element):
68
+ parser = (<_Element>child)._doc._parser
69
+ break
70
+ if isinstance(parser, HTMLParser):
71
+ is_html = 1
72
+ if namespace is None:
73
+ try:
74
+ is_html = _getattr(self, 'HTML')
75
+ except AttributeError:
76
+ pass
77
+ _initNewElement(self, is_html, tag, namespace, parser,
78
+ attrib, nsmap, _extra)
79
+ last_child = None
80
+ for child in children:
81
+ if _isString(child):
82
+ if last_child is None:
83
+ _setNodeText(self._c_node,
84
+ (_collectText(self._c_node.children) or '') + child)
85
+ else:
86
+ _setTailText(last_child._c_node,
87
+ (_collectText(last_child._c_node.next) or '') + child)
88
+ elif isinstance(child, _Element):
89
+ last_child = child
90
+ _appendChild(self, last_child)
91
+ elif isinstance(child, type) and issubclass(child, ElementBase):
92
+ last_child = child()
93
+ _appendChild(self, last_child)
94
+ else:
95
+ raise TypeError, f"Invalid child type: {type(child)!r}"
96
+
97
+ cdef class CommentBase(_Comment):
98
+ """All custom Comment classes must inherit from this one.
99
+
100
+ To create an XML Comment instance, use the ``Comment()`` factory.
101
+
102
+ Subclasses *must not* override __init__ or __new__ as it is
103
+ absolutely undefined when these objects will be created or
104
+ destroyed. All persistent state of Comments must be stored in the
105
+ underlying XML. If you really need to initialize the object after
106
+ creation, you can implement an ``_init(self)`` method that will be
107
+ called after object creation.
108
+ """
109
+ def __init__(self, text):
110
+ # copied from Comment() factory
111
+ cdef _Document doc
112
+ cdef xmlDoc* c_doc
113
+ if text is None:
114
+ text = b''
115
+ else:
116
+ text = _utf8(text)
117
+ c_doc = _newXMLDoc()
118
+ doc = _documentFactory(c_doc, None)
119
+ self._c_node = _createComment(c_doc, _xcstr(text))
120
+ if self._c_node is NULL:
121
+ raise MemoryError()
122
+ tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
123
+ _registerProxy(self, doc, self._c_node)
124
+ self._init()
125
+
126
+ cdef class PIBase(_ProcessingInstruction):
127
+ """All custom Processing Instruction classes must inherit from this one.
128
+
129
+ To create an XML ProcessingInstruction instance, use the ``PI()``
130
+ factory.
131
+
132
+ Subclasses *must not* override __init__ or __new__ as it is
133
+ absolutely undefined when these objects will be created or
134
+ destroyed. All persistent state of PIs must be stored in the
135
+ underlying XML. If you really need to initialize the object after
136
+ creation, you can implement an ``_init(self)`` method that will be
137
+ called after object creation.
138
+ """
139
+ def __init__(self, target, text=None):
140
+ # copied from PI() factory
141
+ cdef _Document doc
142
+ cdef xmlDoc* c_doc
143
+ target = _utf8(target)
144
+ if text is None:
145
+ text = b''
146
+ else:
147
+ text = _utf8(text)
148
+ c_doc = _newXMLDoc()
149
+ doc = _documentFactory(c_doc, None)
150
+ self._c_node = _createPI(c_doc, _xcstr(target), _xcstr(text))
151
+ if self._c_node is NULL:
152
+ raise MemoryError()
153
+ tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
154
+ _registerProxy(self, doc, self._c_node)
155
+ self._init()
156
+
157
+ cdef class EntityBase(_Entity):
158
+ """All custom Entity classes must inherit from this one.
159
+
160
+ To create an XML Entity instance, use the ``Entity()`` factory.
161
+
162
+ Subclasses *must not* override __init__ or __new__ as it is
163
+ absolutely undefined when these objects will be created or
164
+ destroyed. All persistent state of Entities must be stored in the
165
+ underlying XML. If you really need to initialize the object after
166
+ creation, you can implement an ``_init(self)`` method that will be
167
+ called after object creation.
168
+ """
169
+ def __init__(self, name):
170
+ cdef _Document doc
171
+ cdef xmlDoc* c_doc
172
+ name_utf = _utf8(name)
173
+ c_name = _xcstr(name_utf)
174
+ if c_name[0] == c'#':
175
+ if not _characterReferenceIsValid(c_name + 1):
176
+ raise ValueError, f"Invalid character reference: '{name}'"
177
+ elif not _xmlNameIsValid(c_name):
178
+ raise ValueError, f"Invalid entity reference: '{name}'"
179
+ c_doc = _newXMLDoc()
180
+ doc = _documentFactory(c_doc, None)
181
+ self._c_node = _createEntity(c_doc, c_name)
182
+ if self._c_node is NULL:
183
+ raise MemoryError()
184
+ tree.xmlAddChild(<xmlNode*>c_doc, self._c_node)
185
+ _registerProxy(self, doc, self._c_node)
186
+ self._init()
187
+
188
+
189
+ cdef int _validateNodeClass(xmlNode* c_node, cls) except -1:
190
+ if c_node.type == tree.XML_ELEMENT_NODE:
191
+ expected = ElementBase
192
+ elif c_node.type == tree.XML_COMMENT_NODE:
193
+ expected = CommentBase
194
+ elif c_node.type == tree.XML_ENTITY_REF_NODE:
195
+ expected = EntityBase
196
+ elif c_node.type == tree.XML_PI_NODE:
197
+ expected = PIBase
198
+ else:
199
+ assert False, f"Unknown node type: {c_node.type}"
200
+
201
+ if not (isinstance(cls, type) and issubclass(cls, expected)):
202
+ raise TypeError(
203
+ f"result of class lookup must be subclass of {type(expected)}, got {type(cls)}")
204
+ return 0
205
+
206
+
207
+ ################################################################################
208
+ # Element class lookup
209
+
210
+ ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*)
211
+
212
+ # class to store element class lookup functions
213
+ cdef public class ElementClassLookup [ type LxmlElementClassLookupType,
214
+ object LxmlElementClassLookup ]:
215
+ """ElementClassLookup(self)
216
+ Superclass of Element class lookups.
217
+ """
218
+ cdef _element_class_lookup_function _lookup_function
219
+
220
+
221
+ cdef public class FallbackElementClassLookup(ElementClassLookup) \
222
+ [ type LxmlFallbackElementClassLookupType,
223
+ object LxmlFallbackElementClassLookup ]:
224
+ """FallbackElementClassLookup(self, fallback=None)
225
+
226
+ Superclass of Element class lookups with additional fallback.
227
+ """
228
+ cdef readonly ElementClassLookup fallback
229
+ cdef _element_class_lookup_function _fallback_function
230
+ def __cinit__(self):
231
+ # fall back to default lookup
232
+ self._fallback_function = _lookupDefaultElementClass
233
+
234
+ def __init__(self, ElementClassLookup fallback=None):
235
+ if fallback is not None:
236
+ self._setFallback(fallback)
237
+ else:
238
+ self._fallback_function = _lookupDefaultElementClass
239
+
240
+ cdef void _setFallback(self, ElementClassLookup lookup):
241
+ """Sets the fallback scheme for this lookup method.
242
+ """
243
+ self.fallback = lookup
244
+ self._fallback_function = lookup._lookup_function
245
+ if self._fallback_function is NULL:
246
+ self._fallback_function = _lookupDefaultElementClass
247
+
248
+ def set_fallback(self, ElementClassLookup lookup not None):
249
+ """set_fallback(self, lookup)
250
+
251
+ Sets the fallback scheme for this lookup method.
252
+ """
253
+ self._setFallback(lookup)
254
+
255
+ cdef inline object _callLookupFallback(FallbackElementClassLookup lookup,
256
+ _Document doc, xmlNode* c_node):
257
+ return lookup._fallback_function(lookup.fallback, doc, c_node)
258
+
259
+
260
+ ################################################################################
261
+ # default lookup scheme
262
+
263
+ cdef class ElementDefaultClassLookup(ElementClassLookup):
264
+ """ElementDefaultClassLookup(self, element=None, comment=None, pi=None, entity=None)
265
+ Element class lookup scheme that always returns the default Element
266
+ class.
267
+
268
+ The keyword arguments ``element``, ``comment``, ``pi`` and ``entity``
269
+ accept the respective Element classes.
270
+ """
271
+ cdef readonly object element_class
272
+ cdef readonly object comment_class
273
+ cdef readonly object pi_class
274
+ cdef readonly object entity_class
275
+ def __cinit__(self):
276
+ self._lookup_function = _lookupDefaultElementClass
277
+
278
+ def __init__(self, element=None, comment=None, pi=None, entity=None):
279
+ if element is None:
280
+ self.element_class = _Element
281
+ elif issubclass(element, ElementBase):
282
+ self.element_class = element
283
+ else:
284
+ raise TypeError, "element class must be subclass of ElementBase"
285
+
286
+ if comment is None:
287
+ self.comment_class = _Comment
288
+ elif issubclass(comment, CommentBase):
289
+ self.comment_class = comment
290
+ else:
291
+ raise TypeError, "comment class must be subclass of CommentBase"
292
+
293
+ if entity is None:
294
+ self.entity_class = _Entity
295
+ elif issubclass(entity, EntityBase):
296
+ self.entity_class = entity
297
+ else:
298
+ raise TypeError, "Entity class must be subclass of EntityBase"
299
+
300
+ if pi is None:
301
+ self.pi_class = None # special case, see below
302
+ elif issubclass(pi, PIBase):
303
+ self.pi_class = pi
304
+ else:
305
+ raise TypeError, "PI class must be subclass of PIBase"
306
+
307
+ cdef object _lookupDefaultElementClass(state, _Document _doc, xmlNode* c_node):
308
+ "Trivial class lookup function that always returns the default class."
309
+ if c_node.type == tree.XML_ELEMENT_NODE:
310
+ if state is not None:
311
+ return (<ElementDefaultClassLookup>state).element_class
312
+ else:
313
+ return _Element
314
+ elif c_node.type == tree.XML_COMMENT_NODE:
315
+ if state is not None:
316
+ return (<ElementDefaultClassLookup>state).comment_class
317
+ else:
318
+ return _Comment
319
+ elif c_node.type == tree.XML_ENTITY_REF_NODE:
320
+ if state is not None:
321
+ return (<ElementDefaultClassLookup>state).entity_class
322
+ else:
323
+ return _Entity
324
+ elif c_node.type == tree.XML_PI_NODE:
325
+ if state is None or (<ElementDefaultClassLookup>state).pi_class is None:
326
+ # special case XSLT-PI
327
+ if c_node.name is not NULL and c_node.content is not NULL:
328
+ if tree.xmlStrcmp(c_node.name, <unsigned char*>"xml-stylesheet") == 0:
329
+ if tree.xmlStrstr(c_node.content, <unsigned char*>"text/xsl") is not NULL or \
330
+ tree.xmlStrstr(c_node.content, <unsigned char*>"text/xml") is not NULL:
331
+ return _XSLTProcessingInstruction
332
+ return _ProcessingInstruction
333
+ else:
334
+ return (<ElementDefaultClassLookup>state).pi_class
335
+ else:
336
+ assert False, f"Unknown node type: {c_node.type}"
337
+
338
+
339
+ ################################################################################
340
+ # attribute based lookup scheme
341
+
342
+ cdef class AttributeBasedElementClassLookup(FallbackElementClassLookup):
343
+ """AttributeBasedElementClassLookup(self, attribute_name, class_mapping, fallback=None)
344
+ Checks an attribute of an Element and looks up the value in a
345
+ class dictionary.
346
+
347
+ Arguments:
348
+ - attribute name - '{ns}name' style string
349
+ - class mapping - Python dict mapping attribute values to Element classes
350
+ - fallback - optional fallback lookup mechanism
351
+
352
+ A None key in the class mapping will be checked if the attribute is
353
+ missing.
354
+ """
355
+ cdef object _class_mapping
356
+ cdef tuple _pytag
357
+ cdef const_xmlChar* _c_ns
358
+ cdef const_xmlChar* _c_name
359
+ def __cinit__(self):
360
+ self._lookup_function = _attribute_class_lookup
361
+
362
+ def __init__(self, attribute_name, class_mapping,
363
+ ElementClassLookup fallback=None):
364
+ self._pytag = _getNsTag(attribute_name)
365
+ ns, name = self._pytag
366
+ if ns is None:
367
+ self._c_ns = NULL
368
+ else:
369
+ self._c_ns = _xcstr(ns)
370
+ self._c_name = _xcstr(name)
371
+ self._class_mapping = dict(class_mapping)
372
+
373
+ FallbackElementClassLookup.__init__(self, fallback)
374
+
375
+ cdef object _attribute_class_lookup(state, _Document doc, xmlNode* c_node):
376
+ cdef AttributeBasedElementClassLookup lookup
377
+ cdef python.PyObject* dict_result
378
+
379
+ lookup = <AttributeBasedElementClassLookup>state
380
+ if c_node.type == tree.XML_ELEMENT_NODE:
381
+ value = _attributeValueFromNsName(
382
+ c_node, lookup._c_ns, lookup._c_name)
383
+ dict_result = python.PyDict_GetItem(lookup._class_mapping, value)
384
+ if dict_result is not NULL:
385
+ cls = <object>dict_result
386
+ _validateNodeClass(c_node, cls)
387
+ return cls
388
+ return _callLookupFallback(lookup, doc, c_node)
389
+
390
+
391
+ ################################################################################
392
+ # per-parser lookup scheme
393
+
394
+ cdef class ParserBasedElementClassLookup(FallbackElementClassLookup):
395
+ """ParserBasedElementClassLookup(self, fallback=None)
396
+ Element class lookup based on the XML parser.
397
+ """
398
+ def __cinit__(self):
399
+ self._lookup_function = _parser_class_lookup
400
+
401
+ cdef object _parser_class_lookup(state, _Document doc, xmlNode* c_node):
402
+ if doc._parser._class_lookup is not None:
403
+ return doc._parser._class_lookup._lookup_function(
404
+ doc._parser._class_lookup, doc, c_node)
405
+ return _callLookupFallback(<FallbackElementClassLookup>state, doc, c_node)
406
+
407
+
408
+ ################################################################################
409
+ # custom class lookup based on node type, namespace, name
410
+
411
+ cdef class CustomElementClassLookup(FallbackElementClassLookup):
412
+ """CustomElementClassLookup(self, fallback=None)
413
+ Element class lookup based on a subclass method.
414
+
415
+ You can inherit from this class and override the method::
416
+
417
+ lookup(self, type, doc, namespace, name)
418
+
419
+ to lookup the element class for a node. Arguments of the method:
420
+ * type: one of 'element', 'comment', 'PI', 'entity'
421
+ * doc: document that the node is in
422
+ * namespace: namespace URI of the node (or None for comments/PIs/entities)
423
+ * name: name of the element/entity, None for comments, target for PIs
424
+
425
+ If you return None from this method, the fallback will be called.
426
+ """
427
+ def __cinit__(self):
428
+ self._lookup_function = _custom_class_lookup
429
+
430
+ def lookup(self, type, doc, namespace, name):
431
+ "lookup(self, type, doc, namespace, name)"
432
+ return None
433
+
434
+ cdef object _custom_class_lookup(state, _Document doc, xmlNode* c_node):
435
+ cdef CustomElementClassLookup lookup
436
+
437
+ lookup = <CustomElementClassLookup>state
438
+
439
+ if c_node.type == tree.XML_ELEMENT_NODE:
440
+ element_type = "element"
441
+ elif c_node.type == tree.XML_COMMENT_NODE:
442
+ element_type = "comment"
443
+ elif c_node.type == tree.XML_PI_NODE:
444
+ element_type = "PI"
445
+ elif c_node.type == tree.XML_ENTITY_REF_NODE:
446
+ element_type = "entity"
447
+ else:
448
+ element_type = "element"
449
+ if c_node.name is NULL:
450
+ name = None
451
+ else:
452
+ name = funicode(c_node.name)
453
+ c_str = tree._getNs(c_node)
454
+ ns = funicode(c_str) if c_str is not NULL else None
455
+
456
+ cls = lookup.lookup(element_type, doc, ns, name)
457
+ if cls is not None:
458
+ _validateNodeClass(c_node, cls)
459
+ return cls
460
+ return _callLookupFallback(lookup, doc, c_node)
461
+
462
+
463
+ ################################################################################
464
+ # read-only tree based class lookup
465
+
466
+ cdef class PythonElementClassLookup(FallbackElementClassLookup):
467
+ """PythonElementClassLookup(self, fallback=None)
468
+ Element class lookup based on a subclass method.
469
+
470
+ This class lookup scheme allows access to the entire XML tree in
471
+ read-only mode. To use it, re-implement the ``lookup(self, doc,
472
+ root)`` method in a subclass::
473
+
474
+ from lxml import etree, pyclasslookup
475
+
476
+ class MyElementClass(etree.ElementBase):
477
+ honkey = True
478
+
479
+ class MyLookup(pyclasslookup.PythonElementClassLookup):
480
+ def lookup(self, doc, root):
481
+ if root.tag == "sometag":
482
+ return MyElementClass
483
+ else:
484
+ for child in root:
485
+ if child.tag == "someothertag":
486
+ return MyElementClass
487
+ # delegate to default
488
+ return None
489
+
490
+ If you return None from this method, the fallback will be called.
491
+
492
+ The first argument is the opaque document instance that contains
493
+ the Element. The second argument is a lightweight Element proxy
494
+ implementation that is only valid during the lookup. Do not try
495
+ to keep a reference to it. Once the lookup is done, the proxy
496
+ will be invalid.
497
+
498
+ Also, you cannot wrap such a read-only Element in an ElementTree,
499
+ and you must take care not to keep a reference to them outside of
500
+ the `lookup()` method.
501
+
502
+ Note that the API of the Element objects is not complete. It is
503
+ purely read-only and does not support all features of the normal
504
+ `lxml.etree` API (such as XPath, extended slicing or some
505
+ iteration methods).
506
+
507
+ See https://lxml.de/element_classes.html
508
+ """
509
+ def __cinit__(self):
510
+ self._lookup_function = _python_class_lookup
511
+
512
+ def lookup(self, doc, element):
513
+ """lookup(self, doc, element)
514
+
515
+ Override this method to implement your own lookup scheme.
516
+ """
517
+ return None
518
+
519
+ cdef object _python_class_lookup(state, _Document doc, tree.xmlNode* c_node):
520
+ cdef PythonElementClassLookup lookup
521
+ cdef _ReadOnlyProxy proxy
522
+ lookup = <PythonElementClassLookup>state
523
+
524
+ proxy = _newReadOnlyProxy(None, c_node)
525
+ cls = lookup.lookup(doc, proxy)
526
+ _freeReadOnlyProxies(proxy)
527
+
528
+ if cls is not None:
529
+ _validateNodeClass(c_node, cls)
530
+ return cls
531
+ return _callLookupFallback(lookup, doc, c_node)
532
+
533
+ ################################################################################
534
+ # Global setup
535
+
536
+ cdef _element_class_lookup_function LOOKUP_ELEMENT_CLASS
537
+ cdef object ELEMENT_CLASS_LOOKUP_STATE
538
+
539
+ cdef void _setElementClassLookupFunction(
540
+ _element_class_lookup_function function, object state):
541
+ global LOOKUP_ELEMENT_CLASS, ELEMENT_CLASS_LOOKUP_STATE
542
+ if function is NULL:
543
+ state = DEFAULT_ELEMENT_CLASS_LOOKUP
544
+ function = DEFAULT_ELEMENT_CLASS_LOOKUP._lookup_function
545
+
546
+ ELEMENT_CLASS_LOOKUP_STATE = state
547
+ LOOKUP_ELEMENT_CLASS = function
548
+
549
+ def set_element_class_lookup(ElementClassLookup lookup = None):
550
+ """set_element_class_lookup(lookup = None)
551
+
552
+ Set the global element class lookup method.
553
+
554
+ This defines the main entry point for looking up element implementations.
555
+ The standard implementation uses the :class:`ParserBasedElementClassLookup`
556
+ to delegate to different lookup schemes for each parser.
557
+
558
+ .. warning::
559
+
560
+ This should only be changed by applications, not by library packages.
561
+ In most cases, parser specific lookups should be preferred,
562
+ which can be configured via
563
+ :meth:`~lxml.etree.XMLParser.set_element_class_lookup`
564
+ (and the same for HTML parsers).
565
+
566
+ Globally replacing the element class lookup by something other than a
567
+ :class:`ParserBasedElementClassLookup` will prevent parser specific lookup
568
+ schemes from working. Several tools rely on parser specific lookups,
569
+ including :mod:`lxml.html` and :mod:`lxml.objectify`.
570
+ """
571
+ if lookup is None or lookup._lookup_function is NULL:
572
+ _setElementClassLookupFunction(NULL, None)
573
+ else:
574
+ _setElementClassLookupFunction(lookup._lookup_function, lookup)
575
+
576
+ # default setup: parser delegation
577
+ cdef ParserBasedElementClassLookup DEFAULT_ELEMENT_CLASS_LOOKUP
578
+ DEFAULT_ELEMENT_CLASS_LOOKUP = ParserBasedElementClassLookup()
579
+
580
+ set_element_class_lookup(DEFAULT_ELEMENT_CLASS_LOOKUP)
venv/lib/python3.10/site-packages/lxml/cleanup.pxi ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # functions for tree cleanup and removing elements from subtrees
2
+
3
+ def cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None):
4
+ """cleanup_namespaces(tree_or_element, top_nsmap=None, keep_ns_prefixes=None)
5
+
6
+ Remove all namespace declarations from a subtree that are not used
7
+ by any of the elements or attributes in that tree.
8
+
9
+ If a 'top_nsmap' is provided, it must be a mapping from prefixes
10
+ to namespace URIs. These namespaces will be declared on the top
11
+ element of the subtree before running the cleanup, which allows
12
+ moving namespace declarations to the top of the tree.
13
+
14
+ If a 'keep_ns_prefixes' is provided, it must be a list of prefixes.
15
+ These prefixes will not be removed as part of the cleanup.
16
+ """
17
+ element = _rootNodeOrRaise(tree_or_element)
18
+ c_element = element._c_node
19
+
20
+ if top_nsmap:
21
+ doc = element._doc
22
+ # declare namespaces from nsmap, then apply them to the subtree
23
+ _setNodeNamespaces(c_element, doc, None, top_nsmap)
24
+ moveNodeToDocument(doc, c_element.doc, c_element)
25
+
26
+ keep_ns_prefixes = (
27
+ set([_utf8(prefix) for prefix in keep_ns_prefixes])
28
+ if keep_ns_prefixes else None)
29
+
30
+ _removeUnusedNamespaceDeclarations(c_element, keep_ns_prefixes)
31
+
32
+
33
+ def strip_attributes(tree_or_element, *attribute_names):
34
+ """strip_attributes(tree_or_element, *attribute_names)
35
+
36
+ Delete all attributes with the provided attribute names from an
37
+ Element (or ElementTree) and its descendants.
38
+
39
+ Attribute names can contain wildcards as in `_Element.iter`.
40
+
41
+ Example usage::
42
+
43
+ strip_attributes(root_element,
44
+ 'simpleattr',
45
+ '{http://some/ns}attrname',
46
+ '{http://other/ns}*')
47
+ """
48
+ cdef _MultiTagMatcher matcher
49
+ element = _rootNodeOrRaise(tree_or_element)
50
+ if not attribute_names:
51
+ return
52
+
53
+ matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, attribute_names)
54
+ matcher.cacheTags(element._doc)
55
+ if matcher.rejectsAllAttributes():
56
+ return
57
+ _strip_attributes(element._c_node, matcher)
58
+
59
+
60
+ cdef _strip_attributes(xmlNode* c_node, _MultiTagMatcher matcher):
61
+ cdef xmlAttr* c_attr
62
+ cdef xmlAttr* c_next_attr
63
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
64
+ if c_node.type == tree.XML_ELEMENT_NODE:
65
+ c_attr = c_node.properties
66
+ while c_attr is not NULL:
67
+ c_next_attr = c_attr.next
68
+ if matcher.matchesAttribute(c_attr):
69
+ tree.xmlRemoveProp(c_attr)
70
+ c_attr = c_next_attr
71
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
72
+
73
+
74
+ def strip_elements(tree_or_element, *tag_names, bint with_tail=True):
75
+ """strip_elements(tree_or_element, *tag_names, with_tail=True)
76
+
77
+ Delete all elements with the provided tag names from a tree or
78
+ subtree. This will remove the elements and their entire subtree,
79
+ including all their attributes, text content and descendants. It
80
+ will also remove the tail text of the element unless you
81
+ explicitly set the ``with_tail`` keyword argument option to False.
82
+
83
+ Tag names can contain wildcards as in `_Element.iter`.
84
+
85
+ Note that this will not delete the element (or ElementTree root
86
+ element) that you passed even if it matches. It will only treat
87
+ its descendants. If you want to include the root element, check
88
+ its tag name directly before even calling this function.
89
+
90
+ Example usage::
91
+
92
+ strip_elements(some_element,
93
+ 'simpletagname', # non-namespaced tag
94
+ '{http://some/ns}tagname', # namespaced tag
95
+ '{http://some/other/ns}*' # any tag from a namespace
96
+ lxml.etree.Comment # comments
97
+ )
98
+ """
99
+ cdef _MultiTagMatcher matcher
100
+ doc = _documentOrRaise(tree_or_element)
101
+ element = _rootNodeOrRaise(tree_or_element)
102
+ if not tag_names:
103
+ return
104
+
105
+ matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names)
106
+ matcher.cacheTags(doc)
107
+ if matcher.rejectsAll():
108
+ return
109
+
110
+ if isinstance(tree_or_element, _ElementTree):
111
+ # include PIs and comments next to the root node
112
+ if matcher.matchesType(tree.XML_COMMENT_NODE):
113
+ _removeSiblings(element._c_node, tree.XML_COMMENT_NODE, with_tail)
114
+ if matcher.matchesType(tree.XML_PI_NODE):
115
+ _removeSiblings(element._c_node, tree.XML_PI_NODE, with_tail)
116
+ _strip_elements(doc, element._c_node, matcher, with_tail)
117
+
118
+ cdef _strip_elements(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher,
119
+ bint with_tail):
120
+ cdef xmlNode* c_child
121
+ cdef xmlNode* c_next
122
+
123
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
124
+ if c_node.type == tree.XML_ELEMENT_NODE:
125
+ # we run through the children here to prevent any problems
126
+ # with the tree iteration which would occur if we unlinked the
127
+ # c_node itself
128
+ c_child = _findChildForwards(c_node, 0)
129
+ while c_child is not NULL:
130
+ c_next = _nextElement(c_child)
131
+ if matcher.matches(c_child):
132
+ if c_child.type == tree.XML_ELEMENT_NODE:
133
+ if not with_tail:
134
+ tree.xmlUnlinkNode(c_child)
135
+ _removeNode(doc, c_child)
136
+ else:
137
+ if with_tail:
138
+ _removeText(c_child.next)
139
+ tree.xmlUnlinkNode(c_child)
140
+ attemptDeallocation(c_child)
141
+ c_child = c_next
142
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
143
+
144
+
145
+ def strip_tags(tree_or_element, *tag_names):
146
+ """strip_tags(tree_or_element, *tag_names)
147
+
148
+ Delete all elements with the provided tag names from a tree or
149
+ subtree. This will remove the elements and their attributes, but
150
+ *not* their text/tail content or descendants. Instead, it will
151
+ merge the text content and children of the element into its
152
+ parent.
153
+
154
+ Tag names can contain wildcards as in `_Element.iter`.
155
+
156
+ Note that this will not delete the element (or ElementTree root
157
+ element) that you passed even if it matches. It will only treat
158
+ its descendants.
159
+
160
+ Example usage::
161
+
162
+ strip_tags(some_element,
163
+ 'simpletagname', # non-namespaced tag
164
+ '{http://some/ns}tagname', # namespaced tag
165
+ '{http://some/other/ns}*' # any tag from a namespace
166
+ Comment # comments (including their text!)
167
+ )
168
+ """
169
+ cdef _MultiTagMatcher matcher
170
+ doc = _documentOrRaise(tree_or_element)
171
+ element = _rootNodeOrRaise(tree_or_element)
172
+ if not tag_names:
173
+ return
174
+
175
+ matcher = _MultiTagMatcher.__new__(_MultiTagMatcher, tag_names)
176
+ matcher.cacheTags(doc)
177
+ if matcher.rejectsAll():
178
+ return
179
+
180
+ if isinstance(tree_or_element, _ElementTree):
181
+ # include PIs and comments next to the root node
182
+ if matcher.matchesType(tree.XML_COMMENT_NODE):
183
+ _removeSiblings(element._c_node, tree.XML_COMMENT_NODE, 0)
184
+ if matcher.matchesType(tree.XML_PI_NODE):
185
+ _removeSiblings(element._c_node, tree.XML_PI_NODE, 0)
186
+ _strip_tags(doc, element._c_node, matcher)
187
+
188
+ cdef _strip_tags(_Document doc, xmlNode* c_node, _MultiTagMatcher matcher):
189
+ cdef xmlNode* c_child
190
+ cdef xmlNode* c_next
191
+
192
+ tree.BEGIN_FOR_EACH_ELEMENT_FROM(c_node, c_node, 1)
193
+ if c_node.type == tree.XML_ELEMENT_NODE:
194
+ # we run through the children here to prevent any problems
195
+ # with the tree iteration which would occur if we unlinked the
196
+ # c_node itself
197
+ c_child = _findChildForwards(c_node, 0)
198
+ while c_child is not NULL:
199
+ if not matcher.matches(c_child):
200
+ c_child = _nextElement(c_child)
201
+ continue
202
+ if c_child.type == tree.XML_ELEMENT_NODE:
203
+ c_next = _findChildForwards(c_child, 0) or _nextElement(c_child)
204
+ _replaceNodeByChildren(doc, c_child)
205
+ if not attemptDeallocation(c_child):
206
+ if c_child.nsDef is not NULL:
207
+ # make namespaces absolute
208
+ moveNodeToDocument(doc, doc._c_doc, c_child)
209
+ c_child = c_next
210
+ else:
211
+ c_next = _nextElement(c_child)
212
+ tree.xmlUnlinkNode(c_child)
213
+ attemptDeallocation(c_child)
214
+ c_child = c_next
215
+ tree.END_FOR_EACH_ELEMENT_FROM(c_node)
venv/lib/python3.10/site-packages/lxml/cssselect.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CSS Selectors based on XPath.
2
+
3
+ This module supports selecting XML/HTML tags based on CSS selectors.
4
+ See the `CSSSelector` class for details.
5
+
6
+ This is a thin wrapper around cssselect 0.7 or later.
7
+ """
8
+
9
+
10
+ from . import etree
11
+ try:
12
+ import cssselect as external_cssselect
13
+ except ImportError:
14
+ raise ImportError(
15
+ 'cssselect does not seem to be installed. '
16
+ 'See https://pypi.org/project/cssselect/')
17
+
18
+
19
+ SelectorSyntaxError = external_cssselect.SelectorSyntaxError
20
+ ExpressionError = external_cssselect.ExpressionError
21
+ SelectorError = external_cssselect.SelectorError
22
+
23
+
24
+ __all__ = ['SelectorSyntaxError', 'ExpressionError', 'SelectorError',
25
+ 'CSSSelector']
26
+
27
+
28
+ class LxmlTranslator(external_cssselect.GenericTranslator):
29
+ """
30
+ A custom CSS selector to XPath translator with lxml-specific extensions.
31
+ """
32
+ def xpath_contains_function(self, xpath, function):
33
+ # Defined there, removed in later drafts:
34
+ # http://www.w3.org/TR/2001/CR-css3-selectors-20011113/#content-selectors
35
+ if function.argument_types() not in (['STRING'], ['IDENT']):
36
+ raise ExpressionError(
37
+ "Expected a single string or ident for :contains(), got %r"
38
+ % function.arguments)
39
+ value = function.arguments[0].value
40
+ return xpath.add_condition(
41
+ 'contains(__lxml_internal_css:lower-case(string(.)), %s)'
42
+ % self.xpath_literal(value.lower()))
43
+
44
+
45
+ class LxmlHTMLTranslator(LxmlTranslator, external_cssselect.HTMLTranslator):
46
+ """
47
+ lxml extensions + HTML support.
48
+ """
49
+
50
+
51
+ def _make_lower_case(context, s):
52
+ return s.lower()
53
+
54
+ ns = etree.FunctionNamespace('http://codespeak.net/lxml/css/')
55
+ ns.prefix = '__lxml_internal_css'
56
+ ns['lower-case'] = _make_lower_case
57
+
58
+
59
+ class CSSSelector(etree.XPath):
60
+ """A CSS selector.
61
+
62
+ Usage::
63
+
64
+ >>> from lxml import etree, cssselect
65
+ >>> select = cssselect.CSSSelector("a tag > child")
66
+
67
+ >>> root = etree.XML("<a><b><c/><tag><child>TEXT</child></tag></b></a>")
68
+ >>> [ el.tag for el in select(root) ]
69
+ ['child']
70
+
71
+ To use CSS namespaces, you need to pass a prefix-to-namespace
72
+ mapping as ``namespaces`` keyword argument::
73
+
74
+ >>> rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
75
+ >>> select_ns = cssselect.CSSSelector('root > rdf|Description',
76
+ ... namespaces={'rdf': rdfns})
77
+
78
+ >>> rdf = etree.XML((
79
+ ... '<root xmlns:rdf="%s">'
80
+ ... '<rdf:Description>blah</rdf:Description>'
81
+ ... '</root>') % rdfns)
82
+ >>> [(el.tag, el.text) for el in select_ns(rdf)]
83
+ [('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description', 'blah')]
84
+
85
+ """
86
+ def __init__(self, css, namespaces=None, translator='xml'):
87
+ if translator == 'xml':
88
+ translator = LxmlTranslator()
89
+ elif translator == 'html':
90
+ translator = LxmlHTMLTranslator()
91
+ elif translator == 'xhtml':
92
+ translator = LxmlHTMLTranslator(xhtml=True)
93
+ path = translator.css_to_xpath(css)
94
+ super().__init__(path, namespaces=namespaces)
95
+ self.css = css
96
+
97
+ def __repr__(self):
98
+ return '<%s %x for %r>' % (
99
+ self.__class__.__name__,
100
+ abs(id(self)),
101
+ self.css)
venv/lib/python3.10/site-packages/lxml/debug.pxi ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @cython.final
2
+ @cython.internal
3
+ cdef class _MemDebug:
4
+ """Debugging support for the memory allocation in libxml2.
5
+ """
6
+ def bytes_used(self):
7
+ """bytes_used(self)
8
+
9
+ Returns the total amount of memory (in bytes) currently used by libxml2.
10
+ Note that libxml2 constrains this value to a C int, which limits
11
+ the accuracy on 64 bit systems.
12
+ """
13
+ return tree.xmlMemUsed()
14
+
15
+ def blocks_used(self):
16
+ """blocks_used(self)
17
+
18
+ Returns the total number of memory blocks currently allocated by libxml2.
19
+ Note that libxml2 constrains this value to a C int, which limits
20
+ the accuracy on 64 bit systems.
21
+ """
22
+ return tree.xmlMemBlocks()
23
+
24
+ def dict_size(self):
25
+ """dict_size(self)
26
+
27
+ Returns the current size of the global name dictionary used by libxml2
28
+ for the current thread. Each thread has its own dictionary.
29
+ """
30
+ c_dict = __GLOBAL_PARSER_CONTEXT._getThreadDict(NULL)
31
+ if c_dict is NULL:
32
+ raise MemoryError()
33
+ return tree.xmlDictSize(c_dict)
34
+
35
+ def dump(self, output_file=None, byte_count=None):
36
+ """dump(self, output_file=None, byte_count=None)
37
+
38
+ Dumps the current memory blocks allocated by libxml2 to a file.
39
+
40
+ The optional parameter 'output_file' specifies the file path. It defaults
41
+ to the file ".memorylist" in the current directory.
42
+
43
+ The optional parameter 'byte_count' limits the number of bytes in the dump.
44
+ Note that this parameter is ignored when lxml is compiled against a libxml2
45
+ version before 2.7.0.
46
+ """
47
+ cdef Py_ssize_t c_count
48
+ if output_file is None:
49
+ output_file = b'.memorylist'
50
+ elif isinstance(output_file, unicode):
51
+ output_file.encode(sys.getfilesystemencoding())
52
+
53
+ f = stdio.fopen(output_file, "w")
54
+ if f is NULL:
55
+ raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}")
56
+ try:
57
+ if byte_count is None:
58
+ tree.xmlMemDisplay(f)
59
+ else:
60
+ c_count = byte_count
61
+ tree.xmlMemDisplayLast(f, c_count)
62
+ finally:
63
+ stdio.fclose(f)
64
+
65
+ def show(self, output_file=None, block_count=None):
66
+ """show(self, output_file=None, block_count=None)
67
+
68
+ Dumps the current memory blocks allocated by libxml2 to a file.
69
+ The output file format is suitable for line diffing.
70
+
71
+ The optional parameter 'output_file' specifies the file path. It defaults
72
+ to the file ".memorydump" in the current directory.
73
+
74
+ The optional parameter 'block_count' limits the number of blocks
75
+ in the dump.
76
+ """
77
+ if output_file is None:
78
+ output_file = b'.memorydump'
79
+ elif isinstance(output_file, unicode):
80
+ output_file.encode(sys.getfilesystemencoding())
81
+
82
+ f = stdio.fopen(output_file, "w")
83
+ if f is NULL:
84
+ raise IOError(f"Failed to create file {output_file.decode(sys.getfilesystemencoding())}")
85
+ try:
86
+ tree.xmlMemShow(f, block_count if block_count is not None else tree.xmlMemBlocks())
87
+ finally:
88
+ stdio.fclose(f)
89
+
90
+ memory_debugger = _MemDebug()
venv/lib/python3.10/site-packages/lxml/docloader.pxi ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Custom resolver API
2
+
3
+ ctypedef enum _InputDocumentDataType:
4
+ PARSER_DATA_INVALID
5
+ PARSER_DATA_EMPTY
6
+ PARSER_DATA_STRING
7
+ PARSER_DATA_FILENAME
8
+ PARSER_DATA_FILE
9
+
10
+ @cython.final
11
+ @cython.internal
12
+ cdef class _InputDocument:
13
+ cdef _InputDocumentDataType _type
14
+ cdef bytes _data_bytes
15
+ cdef object _filename
16
+ cdef object _file
17
+ cdef bint _close_file
18
+
19
+ def __cinit__(self):
20
+ self._type = PARSER_DATA_INVALID
21
+
22
+
23
+ cdef class Resolver:
24
+ "This is the base class of all resolvers."
25
+ def resolve(self, system_url, public_id, context):
26
+ """resolve(self, system_url, public_id, context)
27
+
28
+ Override this method to resolve an external source by
29
+ ``system_url`` and ``public_id``. The third argument is an
30
+ opaque context object.
31
+
32
+ Return the result of one of the ``resolve_*()`` methods.
33
+ """
34
+ return None
35
+
36
+ def resolve_empty(self, context):
37
+ """resolve_empty(self, context)
38
+
39
+ Return an empty input document.
40
+
41
+ Pass context as parameter.
42
+ """
43
+ cdef _InputDocument doc_ref
44
+ doc_ref = _InputDocument()
45
+ doc_ref._type = PARSER_DATA_EMPTY
46
+ return doc_ref
47
+
48
+ def resolve_string(self, string, context, *, base_url=None):
49
+ """resolve_string(self, string, context, base_url=None)
50
+
51
+ Return a parsable string as input document.
52
+
53
+ Pass data string and context as parameters. You can pass the
54
+ source URL or filename through the ``base_url`` keyword
55
+ argument.
56
+ """
57
+ cdef _InputDocument doc_ref
58
+ if isinstance(string, unicode):
59
+ string = (<unicode>string).encode('utf8')
60
+ elif not isinstance(string, bytes):
61
+ raise TypeError, "argument must be a byte string or unicode string"
62
+ doc_ref = _InputDocument()
63
+ doc_ref._type = PARSER_DATA_STRING
64
+ doc_ref._data_bytes = string
65
+ if base_url is not None:
66
+ doc_ref._filename = _encodeFilename(base_url)
67
+ return doc_ref
68
+
69
+ def resolve_filename(self, filename, context):
70
+ """resolve_filename(self, filename, context)
71
+
72
+ Return the name of a parsable file as input document.
73
+
74
+ Pass filename and context as parameters. You can also pass a
75
+ URL with an HTTP, FTP or file target.
76
+ """
77
+ cdef _InputDocument doc_ref
78
+ doc_ref = _InputDocument()
79
+ doc_ref._type = PARSER_DATA_FILENAME
80
+ doc_ref._filename = _encodeFilename(filename)
81
+ return doc_ref
82
+
83
+ def resolve_file(self, f, context, *, base_url=None, bint close=True):
84
+ """resolve_file(self, f, context, base_url=None, close=True)
85
+
86
+ Return an open file-like object as input document.
87
+
88
+ Pass open file and context as parameters. You can pass the
89
+ base URL or filename of the file through the ``base_url``
90
+ keyword argument. If the ``close`` flag is True (the
91
+ default), the file will be closed after reading.
92
+
93
+ Note that using ``.resolve_filename()`` is more efficient,
94
+ especially in threaded environments.
95
+ """
96
+ cdef _InputDocument doc_ref
97
+ try:
98
+ f.read
99
+ except AttributeError:
100
+ raise TypeError, "Argument is not a file-like object"
101
+ doc_ref = _InputDocument()
102
+ doc_ref._type = PARSER_DATA_FILE
103
+ if base_url is not None:
104
+ doc_ref._filename = _encodeFilename(base_url)
105
+ else:
106
+ doc_ref._filename = _getFilenameForFile(f)
107
+ doc_ref._close_file = close
108
+ doc_ref._file = f
109
+ return doc_ref
110
+
111
+ @cython.final
112
+ @cython.internal
113
+ cdef class _ResolverRegistry:
114
+ cdef object _resolvers
115
+ cdef Resolver _default_resolver
116
+ def __cinit__(self, Resolver default_resolver=None):
117
+ self._resolvers = set()
118
+ self._default_resolver = default_resolver
119
+
120
+ def add(self, Resolver resolver not None):
121
+ """add(self, resolver)
122
+
123
+ Register a resolver.
124
+
125
+ For each requested entity, the 'resolve' method of the resolver will
126
+ be called and the result will be passed to the parser. If this method
127
+ returns None, the request will be delegated to other resolvers or the
128
+ default resolver. The resolvers will be tested in an arbitrary order
129
+ until the first match is found.
130
+ """
131
+ self._resolvers.add(resolver)
132
+
133
+ def remove(self, resolver):
134
+ "remove(self, resolver)"
135
+ self._resolvers.discard(resolver)
136
+
137
+ cdef _ResolverRegistry _copy(self):
138
+ cdef _ResolverRegistry registry
139
+ registry = _ResolverRegistry(self._default_resolver)
140
+ registry._resolvers = self._resolvers.copy()
141
+ return registry
142
+
143
+ def copy(self):
144
+ "copy(self)"
145
+ return self._copy()
146
+
147
+ def resolve(self, system_url, public_id, context):
148
+ "resolve(self, system_url, public_id, context)"
149
+ for resolver in self._resolvers:
150
+ result = resolver.resolve(system_url, public_id, context)
151
+ if result is not None:
152
+ return result
153
+ if self._default_resolver is None:
154
+ return None
155
+ return self._default_resolver.resolve(system_url, public_id, context)
156
+
157
+ def __repr__(self):
158
+ return repr(self._resolvers)
159
+
160
+
161
+ @cython.internal
162
+ cdef class _ResolverContext(_ExceptionContext):
163
+ cdef _ResolverRegistry _resolvers
164
+ cdef _TempStore _storage
165
+
166
+ cdef int clear(self) except -1:
167
+ _ExceptionContext.clear(self)
168
+ self._storage.clear()
169
+ return 0
170
+
171
+
172
+ cdef _initResolverContext(_ResolverContext context,
173
+ _ResolverRegistry resolvers):
174
+ if resolvers is None:
175
+ context._resolvers = _ResolverRegistry()
176
+ else:
177
+ context._resolvers = resolvers
178
+ context._storage = _TempStore()
venv/lib/python3.10/site-packages/lxml/doctestcompare.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ lxml-based doctest output comparison.
3
+
4
+ Note: normally, you should just import the `lxml.usedoctest` and
5
+ `lxml.html.usedoctest` modules from within a doctest, instead of this
6
+ one::
7
+
8
+ >>> import lxml.usedoctest # for XML output
9
+
10
+ >>> import lxml.html.usedoctest # for HTML output
11
+
12
+ To use this module directly, you must call ``lxmldoctest.install()``,
13
+ which will cause doctest to use this in all subsequent calls.
14
+
15
+ This changes the way output is checked and comparisons are made for
16
+ XML or HTML-like content.
17
+
18
+ XML or HTML content is noticed because the example starts with ``<``
19
+ (it's HTML if it starts with ``<html``). You can also use the
20
+ ``PARSE_HTML`` and ``PARSE_XML`` flags to force parsing.
21
+
22
+ Some rough wildcard-like things are allowed. Whitespace is generally
23
+ ignored (except in attributes). In text (attributes and text in the
24
+ body) you can use ``...`` as a wildcard. In an example it also
25
+ matches any trailing tags in the element, though it does not match
26
+ leading tags. You may create a tag ``<any>`` or include an ``any``
27
+ attribute in the tag. An ``any`` tag matches any tag, while the
28
+ attribute matches any and all attributes.
29
+
30
+ When a match fails, the reformatted example and gotten text is
31
+ displayed (indented), and a rough diff-like output is given. Anything
32
+ marked with ``+`` is in the output but wasn't supposed to be, and
33
+ similarly ``-`` means its in the example but wasn't in the output.
34
+
35
+ You can disable parsing on one line with ``# doctest:+NOPARSE_MARKUP``
36
+ """
37
+
38
+ from lxml import etree
39
+ import sys
40
+ import re
41
+ import doctest
42
+ try:
43
+ from html import escape as html_escape
44
+ except ImportError:
45
+ from cgi import escape as html_escape
46
+
47
+ __all__ = ['PARSE_HTML', 'PARSE_XML', 'NOPARSE_MARKUP', 'LXMLOutputChecker',
48
+ 'LHTMLOutputChecker', 'install', 'temp_install']
49
+
50
+ PARSE_HTML = doctest.register_optionflag('PARSE_HTML')
51
+ PARSE_XML = doctest.register_optionflag('PARSE_XML')
52
+ NOPARSE_MARKUP = doctest.register_optionflag('NOPARSE_MARKUP')
53
+
54
+ OutputChecker = doctest.OutputChecker
55
+
56
+ def strip(v):
57
+ if v is None:
58
+ return None
59
+ else:
60
+ return v.strip()
61
+
62
+ def norm_whitespace(v):
63
+ return _norm_whitespace_re.sub(' ', v)
64
+
65
+ _html_parser = etree.HTMLParser(recover=False, remove_blank_text=True)
66
+
67
+ def html_fromstring(html):
68
+ return etree.fromstring(html, _html_parser)
69
+
70
+ # We use this to distinguish repr()s from elements:
71
+ _repr_re = re.compile(r'^<[^>]+ (at|object) ')
72
+ _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
73
+
74
+ class LXMLOutputChecker(OutputChecker):
75
+
76
+ empty_tags = (
77
+ 'param', 'img', 'area', 'br', 'basefont', 'input',
78
+ 'base', 'meta', 'link', 'col')
79
+
80
+ def get_default_parser(self):
81
+ return etree.XML
82
+
83
+ def check_output(self, want, got, optionflags):
84
+ alt_self = getattr(self, '_temp_override_self', None)
85
+ if alt_self is not None:
86
+ super_method = self._temp_call_super_check_output
87
+ self = alt_self
88
+ else:
89
+ super_method = OutputChecker.check_output
90
+ parser = self.get_parser(want, got, optionflags)
91
+ if not parser:
92
+ return super_method(
93
+ self, want, got, optionflags)
94
+ try:
95
+ want_doc = parser(want)
96
+ except etree.XMLSyntaxError:
97
+ return False
98
+ try:
99
+ got_doc = parser(got)
100
+ except etree.XMLSyntaxError:
101
+ return False
102
+ return self.compare_docs(want_doc, got_doc)
103
+
104
+ def get_parser(self, want, got, optionflags):
105
+ parser = None
106
+ if NOPARSE_MARKUP & optionflags:
107
+ return None
108
+ if PARSE_HTML & optionflags:
109
+ parser = html_fromstring
110
+ elif PARSE_XML & optionflags:
111
+ parser = etree.XML
112
+ elif (want.strip().lower().startswith('<html')
113
+ and got.strip().startswith('<html')):
114
+ parser = html_fromstring
115
+ elif (self._looks_like_markup(want)
116
+ and self._looks_like_markup(got)):
117
+ parser = self.get_default_parser()
118
+ return parser
119
+
120
+ def _looks_like_markup(self, s):
121
+ s = s.strip()
122
+ return (s.startswith('<')
123
+ and not _repr_re.search(s))
124
+
125
+ def compare_docs(self, want, got):
126
+ if not self.tag_compare(want.tag, got.tag):
127
+ return False
128
+ if not self.text_compare(want.text, got.text, True):
129
+ return False
130
+ if not self.text_compare(want.tail, got.tail, True):
131
+ return False
132
+ if 'any' not in want.attrib:
133
+ want_keys = sorted(want.attrib.keys())
134
+ got_keys = sorted(got.attrib.keys())
135
+ if want_keys != got_keys:
136
+ return False
137
+ for key in want_keys:
138
+ if not self.text_compare(want.attrib[key], got.attrib[key], False):
139
+ return False
140
+ if want.text != '...' or len(want):
141
+ want_children = list(want)
142
+ got_children = list(got)
143
+ while want_children or got_children:
144
+ if not want_children or not got_children:
145
+ return False
146
+ want_first = want_children.pop(0)
147
+ got_first = got_children.pop(0)
148
+ if not self.compare_docs(want_first, got_first):
149
+ return False
150
+ if not got_children and want_first.tail == '...':
151
+ break
152
+ return True
153
+
154
+ def text_compare(self, want, got, strip):
155
+ want = want or ''
156
+ got = got or ''
157
+ if strip:
158
+ want = norm_whitespace(want).strip()
159
+ got = norm_whitespace(got).strip()
160
+ want = '^%s$' % re.escape(want)
161
+ want = want.replace(r'\.\.\.', '.*')
162
+ if re.search(want, got):
163
+ return True
164
+ else:
165
+ return False
166
+
167
+ def tag_compare(self, want, got):
168
+ if want == 'any':
169
+ return True
170
+ if (not isinstance(want, (str, bytes))
171
+ or not isinstance(got, (str, bytes))):
172
+ return want == got
173
+ want = want or ''
174
+ got = got or ''
175
+ if want.startswith('{...}'):
176
+ # Ellipsis on the namespace
177
+ return want.split('}')[-1] == got.split('}')[-1]
178
+ else:
179
+ return want == got
180
+
181
+ def output_difference(self, example, got, optionflags):
182
+ want = example.want
183
+ parser = self.get_parser(want, got, optionflags)
184
+ errors = []
185
+ if parser is not None:
186
+ try:
187
+ want_doc = parser(want)
188
+ except etree.XMLSyntaxError:
189
+ e = sys.exc_info()[1]
190
+ errors.append('In example: %s' % e)
191
+ try:
192
+ got_doc = parser(got)
193
+ except etree.XMLSyntaxError:
194
+ e = sys.exc_info()[1]
195
+ errors.append('In actual output: %s' % e)
196
+ if parser is None or errors:
197
+ value = OutputChecker.output_difference(
198
+ self, example, got, optionflags)
199
+ if errors:
200
+ errors.append(value)
201
+ return '\n'.join(errors)
202
+ else:
203
+ return value
204
+ html = parser is html_fromstring
205
+ diff_parts = ['Expected:',
206
+ self.format_doc(want_doc, html, 2),
207
+ 'Got:',
208
+ self.format_doc(got_doc, html, 2),
209
+ 'Diff:',
210
+ self.collect_diff(want_doc, got_doc, html, 2)]
211
+ return '\n'.join(diff_parts)
212
+
213
+ def html_empty_tag(self, el, html=True):
214
+ if not html:
215
+ return False
216
+ if el.tag not in self.empty_tags:
217
+ return False
218
+ if el.text or len(el):
219
+ # This shouldn't happen (contents in an empty tag)
220
+ return False
221
+ return True
222
+
223
+ def format_doc(self, doc, html, indent, prefix=''):
224
+ parts = []
225
+ if not len(doc):
226
+ # No children...
227
+ parts.append(' '*indent)
228
+ parts.append(prefix)
229
+ parts.append(self.format_tag(doc))
230
+ if not self.html_empty_tag(doc, html):
231
+ if strip(doc.text):
232
+ parts.append(self.format_text(doc.text))
233
+ parts.append(self.format_end_tag(doc))
234
+ if strip(doc.tail):
235
+ parts.append(self.format_text(doc.tail))
236
+ parts.append('\n')
237
+ return ''.join(parts)
238
+ parts.append(' '*indent)
239
+ parts.append(prefix)
240
+ parts.append(self.format_tag(doc))
241
+ if not self.html_empty_tag(doc, html):
242
+ parts.append('\n')
243
+ if strip(doc.text):
244
+ parts.append(' '*indent)
245
+ parts.append(self.format_text(doc.text))
246
+ parts.append('\n')
247
+ for el in doc:
248
+ parts.append(self.format_doc(el, html, indent+2))
249
+ parts.append(' '*indent)
250
+ parts.append(self.format_end_tag(doc))
251
+ parts.append('\n')
252
+ if strip(doc.tail):
253
+ parts.append(' '*indent)
254
+ parts.append(self.format_text(doc.tail))
255
+ parts.append('\n')
256
+ return ''.join(parts)
257
+
258
+ def format_text(self, text, strip=True):
259
+ if text is None:
260
+ return ''
261
+ if strip:
262
+ text = text.strip()
263
+ return html_escape(text, 1)
264
+
265
+ def format_tag(self, el):
266
+ attrs = []
267
+ if isinstance(el, etree.CommentBase):
268
+ # FIXME: probably PIs should be handled specially too?
269
+ return '<!--'
270
+ for name, value in sorted(el.attrib.items()):
271
+ attrs.append('%s="%s"' % (name, self.format_text(value, False)))
272
+ if not attrs:
273
+ return '<%s>' % el.tag
274
+ return '<%s %s>' % (el.tag, ' '.join(attrs))
275
+
276
+ def format_end_tag(self, el):
277
+ if isinstance(el, etree.CommentBase):
278
+ # FIXME: probably PIs should be handled specially too?
279
+ return '-->'
280
+ return '</%s>' % el.tag
281
+
282
+ def collect_diff(self, want, got, html, indent):
283
+ parts = []
284
+ if not len(want) and not len(got):
285
+ parts.append(' '*indent)
286
+ parts.append(self.collect_diff_tag(want, got))
287
+ if not self.html_empty_tag(got, html):
288
+ parts.append(self.collect_diff_text(want.text, got.text))
289
+ parts.append(self.collect_diff_end_tag(want, got))
290
+ parts.append(self.collect_diff_text(want.tail, got.tail))
291
+ parts.append('\n')
292
+ return ''.join(parts)
293
+ parts.append(' '*indent)
294
+ parts.append(self.collect_diff_tag(want, got))
295
+ parts.append('\n')
296
+ if strip(want.text) or strip(got.text):
297
+ parts.append(' '*indent)
298
+ parts.append(self.collect_diff_text(want.text, got.text))
299
+ parts.append('\n')
300
+ want_children = list(want)
301
+ got_children = list(got)
302
+ while want_children or got_children:
303
+ if not want_children:
304
+ parts.append(self.format_doc(got_children.pop(0), html, indent+2, '+'))
305
+ continue
306
+ if not got_children:
307
+ parts.append(self.format_doc(want_children.pop(0), html, indent+2, '-'))
308
+ continue
309
+ parts.append(self.collect_diff(
310
+ want_children.pop(0), got_children.pop(0), html, indent+2))
311
+ parts.append(' '*indent)
312
+ parts.append(self.collect_diff_end_tag(want, got))
313
+ parts.append('\n')
314
+ if strip(want.tail) or strip(got.tail):
315
+ parts.append(' '*indent)
316
+ parts.append(self.collect_diff_text(want.tail, got.tail))
317
+ parts.append('\n')
318
+ return ''.join(parts)
319
+
320
+ def collect_diff_tag(self, want, got):
321
+ if not self.tag_compare(want.tag, got.tag):
322
+ tag = '%s (got: %s)' % (want.tag, got.tag)
323
+ else:
324
+ tag = got.tag
325
+ attrs = []
326
+ any = want.tag == 'any' or 'any' in want.attrib
327
+ for name, value in sorted(got.attrib.items()):
328
+ if name not in want.attrib and not any:
329
+ attrs.append('+%s="%s"' % (name, self.format_text(value, False)))
330
+ else:
331
+ if name in want.attrib:
332
+ text = self.collect_diff_text(want.attrib[name], value, False)
333
+ else:
334
+ text = self.format_text(value, False)
335
+ attrs.append('%s="%s"' % (name, text))
336
+ if not any:
337
+ for name, value in sorted(want.attrib.items()):
338
+ if name in got.attrib:
339
+ continue
340
+ attrs.append('-%s="%s"' % (name, self.format_text(value, False)))
341
+ if attrs:
342
+ tag = '<%s %s>' % (tag, ' '.join(attrs))
343
+ else:
344
+ tag = '<%s>' % tag
345
+ return tag
346
+
347
+ def collect_diff_end_tag(self, want, got):
348
+ if want.tag != got.tag:
349
+ tag = '%s (got: %s)' % (want.tag, got.tag)
350
+ else:
351
+ tag = got.tag
352
+ return '</%s>' % tag
353
+
354
+ def collect_diff_text(self, want, got, strip=True):
355
+ if self.text_compare(want, got, strip):
356
+ if not got:
357
+ return ''
358
+ return self.format_text(got, strip)
359
+ text = '%s (got: %s)' % (want, got)
360
+ return self.format_text(text, strip)
361
+
362
+ class LHTMLOutputChecker(LXMLOutputChecker):
363
+ def get_default_parser(self):
364
+ return html_fromstring
365
+
366
+ def install(html=False):
367
+ """
368
+ Install doctestcompare for all future doctests.
369
+
370
+ If html is true, then by default the HTML parser will be used;
371
+ otherwise the XML parser is used.
372
+ """
373
+ if html:
374
+ doctest.OutputChecker = LHTMLOutputChecker
375
+ else:
376
+ doctest.OutputChecker = LXMLOutputChecker
377
+
378
+ def temp_install(html=False, del_module=None):
379
+ """
380
+ Use this *inside* a doctest to enable this checker for this
381
+ doctest only.
382
+
383
+ If html is true, then by default the HTML parser will be used;
384
+ otherwise the XML parser is used.
385
+ """
386
+ if html:
387
+ Checker = LHTMLOutputChecker
388
+ else:
389
+ Checker = LXMLOutputChecker
390
+ frame = _find_doctest_frame()
391
+ dt_self = frame.f_locals['self']
392
+ checker = Checker()
393
+ old_checker = dt_self._checker
394
+ dt_self._checker = checker
395
+ # The unfortunate thing is that there is a local variable 'check'
396
+ # in the function that runs the doctests, that is a bound method
397
+ # into the output checker. We have to update that. We can't
398
+ # modify the frame, so we have to modify the object in place. The
399
+ # only way to do this is to actually change the func_code
400
+ # attribute of the method. We change it, and then wait for
401
+ # __record_outcome to be run, which signals the end of the __run
402
+ # method, at which point we restore the previous check_output
403
+ # implementation.
404
+ check_func = frame.f_locals['check'].__func__
405
+ checker_check_func = checker.check_output.__func__
406
+ # Because we can't patch up func_globals, this is the only global
407
+ # in check_output that we care about:
408
+ doctest.etree = etree
409
+ _RestoreChecker(dt_self, old_checker, checker,
410
+ check_func, checker_check_func,
411
+ del_module)
412
+
413
+ class _RestoreChecker:
414
+ def __init__(self, dt_self, old_checker, new_checker, check_func, clone_func,
415
+ del_module):
416
+ self.dt_self = dt_self
417
+ self.checker = old_checker
418
+ self.checker._temp_call_super_check_output = self.call_super
419
+ self.checker._temp_override_self = new_checker
420
+ self.check_func = check_func
421
+ self.clone_func = clone_func
422
+ self.del_module = del_module
423
+ self.install_clone()
424
+ self.install_dt_self()
425
+ def install_clone(self):
426
+ self.func_code = self.check_func.__code__
427
+ self.func_globals = self.check_func.__globals__
428
+ self.check_func.__code__ = self.clone_func.__code__
429
+ def uninstall_clone(self):
430
+ self.check_func.__code__ = self.func_code
431
+ def install_dt_self(self):
432
+ self.prev_func = self.dt_self._DocTestRunner__record_outcome
433
+ self.dt_self._DocTestRunner__record_outcome = self
434
+ def uninstall_dt_self(self):
435
+ self.dt_self._DocTestRunner__record_outcome = self.prev_func
436
+ def uninstall_module(self):
437
+ if self.del_module:
438
+ import sys
439
+ del sys.modules[self.del_module]
440
+ if '.' in self.del_module:
441
+ package, module = self.del_module.rsplit('.', 1)
442
+ package_mod = sys.modules[package]
443
+ delattr(package_mod, module)
444
+ def __call__(self, *args, **kw):
445
+ self.uninstall_clone()
446
+ self.uninstall_dt_self()
447
+ del self.checker._temp_override_self
448
+ del self.checker._temp_call_super_check_output
449
+ result = self.prev_func(*args, **kw)
450
+ self.uninstall_module()
451
+ return result
452
+ def call_super(self, *args, **kw):
453
+ self.uninstall_clone()
454
+ try:
455
+ return self.check_func(*args, **kw)
456
+ finally:
457
+ self.install_clone()
458
+
459
+ def _find_doctest_frame():
460
+ import sys
461
+ frame = sys._getframe(1)
462
+ while frame:
463
+ l = frame.f_locals
464
+ if 'BOOM' in l:
465
+ # Sign of doctest
466
+ return frame
467
+ frame = frame.f_back
468
+ raise LookupError(
469
+ "Could not find doctest (only use this function *inside* a doctest)")
470
+
471
+ __test__ = {
472
+ 'basic': '''
473
+ >>> temp_install()
474
+ >>> print """<xml a="1" b="2">stuff</xml>"""
475
+ <xml b="2" a="1">...</xml>
476
+ >>> print """<xml xmlns="http://example.com"><tag attr="bar" /></xml>"""
477
+ <xml xmlns="...">
478
+ <tag attr="..." />
479
+ </xml>
480
+ >>> print """<xml>blahblahblah<foo /></xml>""" # doctest: +NOPARSE_MARKUP, +ELLIPSIS
481
+ <xml>...foo /></xml>
482
+ '''}
483
+
484
+ if __name__ == '__main__':
485
+ import doctest
486
+ doctest.testmod()
487
+
488
+
venv/lib/python3.10/site-packages/lxml/dtd.pxi ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # support for DTD validation
2
+ from lxml.includes cimport dtdvalid
3
+
4
+ cdef class DTDError(LxmlError):
5
+ """Base class for DTD errors.
6
+ """
7
+
8
+ cdef class DTDParseError(DTDError):
9
+ """Error while parsing a DTD.
10
+ """
11
+
12
+ cdef class DTDValidateError(DTDError):
13
+ """Error while validating an XML document with a DTD.
14
+ """
15
+
16
+
17
+ cdef inline int _assertValidDTDNode(node, void *c_node) except -1:
18
+ assert c_node is not NULL, "invalid DTD proxy at %s" % id(node)
19
+
20
+
21
+ @cython.final
22
+ @cython.internal
23
+ @cython.freelist(8)
24
+ cdef class _DTDElementContentDecl:
25
+ cdef DTD _dtd
26
+ cdef tree.xmlElementContent* _c_node
27
+
28
+ def __repr__(self):
29
+ return "<%s.%s object name=%r type=%r occur=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.type, self.occur, id(self))
30
+
31
+ @property
32
+ def name(self):
33
+ _assertValidDTDNode(self, self._c_node)
34
+ return funicodeOrNone(self._c_node.name)
35
+
36
+ @property
37
+ def type(self):
38
+ _assertValidDTDNode(self, self._c_node)
39
+ cdef int type = self._c_node.type
40
+ if type == tree.XML_ELEMENT_CONTENT_PCDATA:
41
+ return "pcdata"
42
+ elif type == tree.XML_ELEMENT_CONTENT_ELEMENT:
43
+ return "element"
44
+ elif type == tree.XML_ELEMENT_CONTENT_SEQ:
45
+ return "seq"
46
+ elif type == tree.XML_ELEMENT_CONTENT_OR:
47
+ return "or"
48
+ else:
49
+ return None
50
+
51
+ @property
52
+ def occur(self):
53
+ _assertValidDTDNode(self, self._c_node)
54
+ cdef int occur = self._c_node.ocur
55
+ if occur == tree.XML_ELEMENT_CONTENT_ONCE:
56
+ return "once"
57
+ elif occur == tree.XML_ELEMENT_CONTENT_OPT:
58
+ return "opt"
59
+ elif occur == tree.XML_ELEMENT_CONTENT_MULT:
60
+ return "mult"
61
+ elif occur == tree.XML_ELEMENT_CONTENT_PLUS:
62
+ return "plus"
63
+ else:
64
+ return None
65
+
66
+ @property
67
+ def left(self):
68
+ _assertValidDTDNode(self, self._c_node)
69
+ c1 = self._c_node.c1
70
+ if c1:
71
+ node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
72
+ node._dtd = self._dtd
73
+ node._c_node = <tree.xmlElementContent*>c1
74
+ return node
75
+ else:
76
+ return None
77
+
78
+ @property
79
+ def right(self):
80
+ _assertValidDTDNode(self, self._c_node)
81
+ c2 = self._c_node.c2
82
+ if c2:
83
+ node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
84
+ node._dtd = self._dtd
85
+ node._c_node = <tree.xmlElementContent*>c2
86
+ return node
87
+ else:
88
+ return None
89
+
90
+
91
+ @cython.final
92
+ @cython.internal
93
+ @cython.freelist(8)
94
+ cdef class _DTDAttributeDecl:
95
+ cdef DTD _dtd
96
+ cdef tree.xmlAttribute* _c_node
97
+
98
+ def __repr__(self):
99
+ return "<%s.%s object name=%r elemname=%r prefix=%r type=%r default=%r default_value=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.elemname, self.prefix, self.type, self.default, self.default_value, id(self))
100
+
101
+ @property
102
+ def name(self):
103
+ _assertValidDTDNode(self, self._c_node)
104
+ return funicodeOrNone(self._c_node.name)
105
+
106
+ @property
107
+ def elemname(self):
108
+ _assertValidDTDNode(self, self._c_node)
109
+ return funicodeOrNone(self._c_node.elem)
110
+
111
+ @property
112
+ def prefix(self):
113
+ _assertValidDTDNode(self, self._c_node)
114
+ return funicodeOrNone(self._c_node.prefix)
115
+
116
+ @property
117
+ def type(self):
118
+ _assertValidDTDNode(self, self._c_node)
119
+ cdef int type = self._c_node.atype
120
+ if type == tree.XML_ATTRIBUTE_CDATA:
121
+ return "cdata"
122
+ elif type == tree.XML_ATTRIBUTE_ID:
123
+ return "id"
124
+ elif type == tree.XML_ATTRIBUTE_IDREF:
125
+ return "idref"
126
+ elif type == tree.XML_ATTRIBUTE_IDREFS:
127
+ return "idrefs"
128
+ elif type == tree.XML_ATTRIBUTE_ENTITY:
129
+ return "entity"
130
+ elif type == tree.XML_ATTRIBUTE_ENTITIES:
131
+ return "entities"
132
+ elif type == tree.XML_ATTRIBUTE_NMTOKEN:
133
+ return "nmtoken"
134
+ elif type == tree.XML_ATTRIBUTE_NMTOKENS:
135
+ return "nmtokens"
136
+ elif type == tree.XML_ATTRIBUTE_ENUMERATION:
137
+ return "enumeration"
138
+ elif type == tree.XML_ATTRIBUTE_NOTATION:
139
+ return "notation"
140
+ else:
141
+ return None
142
+
143
+ @property
144
+ def default(self):
145
+ _assertValidDTDNode(self, self._c_node)
146
+ cdef int default = self._c_node.def_
147
+ if default == tree.XML_ATTRIBUTE_NONE:
148
+ return "none"
149
+ elif default == tree.XML_ATTRIBUTE_REQUIRED:
150
+ return "required"
151
+ elif default == tree.XML_ATTRIBUTE_IMPLIED:
152
+ return "implied"
153
+ elif default == tree.XML_ATTRIBUTE_FIXED:
154
+ return "fixed"
155
+ else:
156
+ return None
157
+
158
+ @property
159
+ def default_value(self):
160
+ _assertValidDTDNode(self, self._c_node)
161
+ return funicodeOrNone(self._c_node.defaultValue)
162
+
163
+ def itervalues(self):
164
+ _assertValidDTDNode(self, self._c_node)
165
+ cdef tree.xmlEnumeration *c_node = self._c_node.tree
166
+ while c_node is not NULL:
167
+ yield funicode(c_node.name)
168
+ c_node = c_node.next
169
+
170
+ def values(self):
171
+ return list(self.itervalues())
172
+
173
+
174
+ @cython.final
175
+ @cython.internal
176
+ @cython.freelist(8)
177
+ cdef class _DTDElementDecl:
178
+ cdef DTD _dtd
179
+ cdef tree.xmlElement* _c_node
180
+
181
+ def __repr__(self):
182
+ return "<%s.%s object name=%r prefix=%r type=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, self.prefix, self.type, id(self))
183
+
184
+ @property
185
+ def name(self):
186
+ _assertValidDTDNode(self, self._c_node)
187
+ return funicodeOrNone(self._c_node.name)
188
+
189
+ @property
190
+ def prefix(self):
191
+ _assertValidDTDNode(self, self._c_node)
192
+ return funicodeOrNone(self._c_node.prefix)
193
+
194
+ @property
195
+ def type(self):
196
+ _assertValidDTDNode(self, self._c_node)
197
+ cdef int type = self._c_node.etype
198
+ if type == tree.XML_ELEMENT_TYPE_UNDEFINED:
199
+ return "undefined"
200
+ elif type == tree.XML_ELEMENT_TYPE_EMPTY:
201
+ return "empty"
202
+ elif type == tree.XML_ELEMENT_TYPE_ANY:
203
+ return "any"
204
+ elif type == tree.XML_ELEMENT_TYPE_MIXED:
205
+ return "mixed"
206
+ elif type == tree.XML_ELEMENT_TYPE_ELEMENT:
207
+ return "element"
208
+ else:
209
+ return None
210
+
211
+ @property
212
+ def content(self):
213
+ _assertValidDTDNode(self, self._c_node)
214
+ cdef tree.xmlElementContent *content = self._c_node.content
215
+ if content:
216
+ node = <_DTDElementContentDecl>_DTDElementContentDecl.__new__(_DTDElementContentDecl)
217
+ node._dtd = self._dtd
218
+ node._c_node = content
219
+ return node
220
+ else:
221
+ return None
222
+
223
+ def iterattributes(self):
224
+ _assertValidDTDNode(self, self._c_node)
225
+ cdef tree.xmlAttribute *c_node = self._c_node.attributes
226
+ while c_node:
227
+ node = <_DTDAttributeDecl>_DTDAttributeDecl.__new__(_DTDAttributeDecl)
228
+ node._dtd = self._dtd
229
+ node._c_node = c_node
230
+ yield node
231
+ c_node = c_node.nexth
232
+
233
+ def attributes(self):
234
+ return list(self.iterattributes())
235
+
236
+
237
+ @cython.final
238
+ @cython.internal
239
+ @cython.freelist(8)
240
+ cdef class _DTDEntityDecl:
241
+ cdef DTD _dtd
242
+ cdef tree.xmlEntity* _c_node
243
+ def __repr__(self):
244
+ return "<%s.%s object name=%r at 0x%x>" % (self.__class__.__module__, self.__class__.__name__, self.name, id(self))
245
+
246
+ @property
247
+ def name(self):
248
+ _assertValidDTDNode(self, self._c_node)
249
+ return funicodeOrNone(self._c_node.name)
250
+
251
+ @property
252
+ def orig(self):
253
+ _assertValidDTDNode(self, self._c_node)
254
+ return funicodeOrNone(self._c_node.orig)
255
+
256
+ @property
257
+ def content(self):
258
+ _assertValidDTDNode(self, self._c_node)
259
+ return funicodeOrNone(self._c_node.content)
260
+
261
+ @property
262
+ def system_url(self):
263
+ _assertValidDTDNode(self, self._c_node)
264
+ return funicodeOrNone(self._c_node.SystemID)
265
+
266
+
267
+ ################################################################################
268
+ # DTD
269
+
270
+ cdef class DTD(_Validator):
271
+ """DTD(self, file=None, external_id=None)
272
+ A DTD validator.
273
+
274
+ Can load from filesystem directly given a filename or file-like object.
275
+ Alternatively, pass the keyword parameter ``external_id`` to load from a
276
+ catalog.
277
+ """
278
+ cdef tree.xmlDtd* _c_dtd
279
+ def __init__(self, file=None, *, external_id=None):
280
+ _Validator.__init__(self)
281
+ if file is not None:
282
+ file = _getFSPathOrObject(file)
283
+ if _isString(file):
284
+ file = _encodeFilename(file)
285
+ with self._error_log:
286
+ orig_loader = _register_document_loader()
287
+ self._c_dtd = xmlparser.xmlParseDTD(NULL, _xcstr(file))
288
+ _reset_document_loader(orig_loader)
289
+ elif hasattr(file, 'read'):
290
+ orig_loader = _register_document_loader()
291
+ self._c_dtd = _parseDtdFromFilelike(file)
292
+ _reset_document_loader(orig_loader)
293
+ else:
294
+ raise DTDParseError, "file must be a filename, file-like or path-like object"
295
+ elif external_id is not None:
296
+ with self._error_log:
297
+ orig_loader = _register_document_loader()
298
+ self._c_dtd = xmlparser.xmlParseDTD(<const_xmlChar*>external_id, NULL)
299
+ _reset_document_loader(orig_loader)
300
+ else:
301
+ raise DTDParseError, "either filename or external ID required"
302
+
303
+ if self._c_dtd is NULL:
304
+ raise DTDParseError(
305
+ self._error_log._buildExceptionMessage("error parsing DTD"),
306
+ self._error_log)
307
+
308
+ @property
309
+ def name(self):
310
+ if self._c_dtd is NULL:
311
+ return None
312
+ return funicodeOrNone(self._c_dtd.name)
313
+
314
+ @property
315
+ def external_id(self):
316
+ if self._c_dtd is NULL:
317
+ return None
318
+ return funicodeOrNone(self._c_dtd.ExternalID)
319
+
320
+ @property
321
+ def system_url(self):
322
+ if self._c_dtd is NULL:
323
+ return None
324
+ return funicodeOrNone(self._c_dtd.SystemID)
325
+
326
+ def iterelements(self):
327
+ cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL
328
+ while c_node is not NULL:
329
+ if c_node.type == tree.XML_ELEMENT_DECL:
330
+ node = _DTDElementDecl()
331
+ node._dtd = self
332
+ node._c_node = <tree.xmlElement*>c_node
333
+ yield node
334
+ c_node = c_node.next
335
+
336
+ def elements(self):
337
+ return list(self.iterelements())
338
+
339
+ def iterentities(self):
340
+ cdef tree.xmlNode *c_node = self._c_dtd.children if self._c_dtd is not NULL else NULL
341
+ while c_node is not NULL:
342
+ if c_node.type == tree.XML_ENTITY_DECL:
343
+ node = _DTDEntityDecl()
344
+ node._dtd = self
345
+ node._c_node = <tree.xmlEntity*>c_node
346
+ yield node
347
+ c_node = c_node.next
348
+
349
+ def entities(self):
350
+ return list(self.iterentities())
351
+
352
+ def __dealloc__(self):
353
+ tree.xmlFreeDtd(self._c_dtd)
354
+
355
+ def __call__(self, etree):
356
+ """__call__(self, etree)
357
+
358
+ Validate doc using the DTD.
359
+
360
+ Returns true if the document is valid, false if not.
361
+ """
362
+ cdef _Document doc
363
+ cdef _Element root_node
364
+ cdef xmlDoc* c_doc
365
+ cdef dtdvalid.xmlValidCtxt* valid_ctxt
366
+ cdef int ret = -1
367
+
368
+ assert self._c_dtd is not NULL, "DTD not initialised"
369
+ doc = _documentOrRaise(etree)
370
+ root_node = _rootNodeOrRaise(etree)
371
+
372
+ valid_ctxt = dtdvalid.xmlNewValidCtxt()
373
+ if valid_ctxt is NULL:
374
+ raise DTDError("Failed to create validation context")
375
+
376
+ # work around error reporting bug in libxml2 <= 2.9.1 (and later?)
377
+ # https://bugzilla.gnome.org/show_bug.cgi?id=724903
378
+ valid_ctxt.error = <dtdvalid.xmlValidityErrorFunc>_nullGenericErrorFunc
379
+ valid_ctxt.userData = NULL
380
+
381
+ try:
382
+ with self._error_log:
383
+ c_doc = _fakeRootDoc(doc._c_doc, root_node._c_node)
384
+ ret = dtdvalid.xmlValidateDtd(valid_ctxt, c_doc, self._c_dtd)
385
+ _destroyFakeDoc(doc._c_doc, c_doc)
386
+ finally:
387
+ dtdvalid.xmlFreeValidCtxt(valid_ctxt)
388
+
389
+ if ret == -1:
390
+ raise DTDValidateError("Internal error in DTD validation",
391
+ self._error_log)
392
+ return ret == 1
393
+
394
+
395
+ cdef tree.xmlDtd* _parseDtdFromFilelike(file) except NULL:
396
+ cdef _ExceptionContext exc_context
397
+ cdef _FileReaderContext dtd_parser
398
+ cdef _ErrorLog error_log
399
+ cdef tree.xmlDtd* c_dtd = NULL
400
+ exc_context = _ExceptionContext()
401
+ dtd_parser = _FileReaderContext(file, exc_context, None)
402
+ error_log = _ErrorLog()
403
+
404
+ with error_log:
405
+ c_dtd = dtd_parser._readDtd()
406
+
407
+ exc_context._raise_if_stored()
408
+ if c_dtd is NULL:
409
+ raise DTDParseError("error parsing DTD", error_log)
410
+ return c_dtd
411
+
412
+ cdef DTD _dtdFactory(tree.xmlDtd* c_dtd):
413
+ # do not run through DTD.__init__()!
414
+ cdef DTD dtd
415
+ if c_dtd is NULL:
416
+ return None
417
+ dtd = DTD.__new__(DTD)
418
+ dtd._c_dtd = _copyDtd(c_dtd)
419
+ _Validator.__init__(dtd)
420
+ return dtd
421
+
422
+
423
+ cdef tree.xmlDtd* _copyDtd(tree.xmlDtd* c_orig_dtd) except NULL:
424
+ """
425
+ Copy a DTD. libxml2 (currently) fails to set up the element->attributes
426
+ links when copying DTDs, so we have to rebuild them here.
427
+ """
428
+ c_dtd = tree.xmlCopyDtd(c_orig_dtd)
429
+ if not c_dtd:
430
+ raise MemoryError
431
+ cdef tree.xmlNode* c_node = c_dtd.children
432
+ while c_node:
433
+ if c_node.type == tree.XML_ATTRIBUTE_DECL:
434
+ _linkDtdAttribute(c_dtd, <tree.xmlAttribute*>c_node)
435
+ c_node = c_node.next
436
+ return c_dtd
437
+
438
+
439
+ cdef void _linkDtdAttribute(tree.xmlDtd* c_dtd, tree.xmlAttribute* c_attr) noexcept:
440
+ """
441
+ Create the link to the DTD attribute declaration from the corresponding
442
+ element declaration.
443
+ """
444
+ c_elem = dtdvalid.xmlGetDtdElementDesc(c_dtd, c_attr.elem)
445
+ if not c_elem:
446
+ # no such element? something is wrong with the DTD ...
447
+ return
448
+ c_pos = c_elem.attributes
449
+ if not c_pos:
450
+ c_elem.attributes = c_attr
451
+ c_attr.nexth = NULL
452
+ return
453
+ # libxml2 keeps namespace declarations first, and we need to make
454
+ # sure we don't re-insert attributes that are already there
455
+ if _isDtdNsDecl(c_attr):
456
+ if not _isDtdNsDecl(c_pos):
457
+ c_elem.attributes = c_attr
458
+ c_attr.nexth = c_pos
459
+ return
460
+ while c_pos != c_attr and c_pos.nexth and _isDtdNsDecl(c_pos.nexth):
461
+ c_pos = c_pos.nexth
462
+ else:
463
+ # append at end
464
+ while c_pos != c_attr and c_pos.nexth:
465
+ c_pos = c_pos.nexth
466
+ if c_pos == c_attr:
467
+ return
468
+ c_attr.nexth = c_pos.nexth
469
+ c_pos.nexth = c_attr
470
+
471
+
472
+ cdef bint _isDtdNsDecl(tree.xmlAttribute* c_attr) noexcept:
473
+ if cstring_h.strcmp(<const_char*>c_attr.name, "xmlns") == 0:
474
+ return True
475
+ if (c_attr.prefix is not NULL and
476
+ cstring_h.strcmp(<const_char*>c_attr.prefix, "xmlns") == 0):
477
+ return True
478
+ return False
venv/lib/python3.10/site-packages/lxml/etree.h ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Generated by Cython 3.0.10 */
2
+
3
+ #ifndef __PYX_HAVE__lxml__etree
4
+ #define __PYX_HAVE__lxml__etree
5
+
6
+ #include "Python.h"
7
+ struct LxmlDocument;
8
+ struct LxmlElement;
9
+ struct LxmlElementTree;
10
+ struct LxmlElementTagMatcher;
11
+ struct LxmlElementIterator;
12
+ struct LxmlElementBase;
13
+ struct LxmlElementClassLookup;
14
+ struct LxmlFallbackElementClassLookup;
15
+
16
+ /* "lxml/etree.pyx":333
17
+ *
18
+ * # type of a function that steps from node to node
19
+ * ctypedef public xmlNode* (*_node_to_node_function)(xmlNode*) # <<<<<<<<<<<<<<
20
+ *
21
+ *
22
+ */
23
+ typedef xmlNode *(*_node_to_node_function)(xmlNode *);
24
+
25
+ /* "lxml/etree.pyx":349
26
+ * @cython.final
27
+ * @cython.freelist(8)
28
+ * cdef public class _Document [ type LxmlDocumentType, object LxmlDocument ]: # <<<<<<<<<<<<<<
29
+ * """Internal base class to reference a libxml document.
30
+ *
31
+ */
32
+ struct LxmlDocument {
33
+ PyObject_HEAD
34
+ struct __pyx_vtabstruct_4lxml_5etree__Document *__pyx_vtab;
35
+ int _ns_counter;
36
+ PyObject *_prefix_tail;
37
+ xmlDoc *_c_doc;
38
+ struct __pyx_obj_4lxml_5etree__BaseParser *_parser;
39
+ };
40
+
41
+ /* "lxml/etree.pyx":698
42
+ *
43
+ * @cython.no_gc_clear
44
+ * cdef public class _Element [ type LxmlElementType, object LxmlElement ]: # <<<<<<<<<<<<<<
45
+ * """Element class.
46
+ *
47
+ */
48
+ struct LxmlElement {
49
+ PyObject_HEAD
50
+ struct LxmlDocument *_doc;
51
+ xmlNode *_c_node;
52
+ PyObject *_tag;
53
+ };
54
+
55
+ /* "lxml/etree.pyx":1872
56
+ *
57
+ *
58
+ * cdef public class _ElementTree [ type LxmlElementTreeType, # <<<<<<<<<<<<<<
59
+ * object LxmlElementTree ]:
60
+ * cdef _Document _doc
61
+ */
62
+ struct LxmlElementTree {
63
+ PyObject_HEAD
64
+ struct __pyx_vtabstruct_4lxml_5etree__ElementTree *__pyx_vtab;
65
+ struct LxmlDocument *_doc;
66
+ struct LxmlElement *_context_node;
67
+ };
68
+
69
+ /* "lxml/etree.pyx":2646
70
+ *
71
+ *
72
+ * cdef public class _ElementTagMatcher [ object LxmlElementTagMatcher, # <<<<<<<<<<<<<<
73
+ * type LxmlElementTagMatcherType ]:
74
+ * """
75
+ */
76
+ struct LxmlElementTagMatcher {
77
+ PyObject_HEAD
78
+ struct __pyx_vtabstruct_4lxml_5etree__ElementTagMatcher *__pyx_vtab;
79
+ PyObject *_pystrings;
80
+ int _node_type;
81
+ char *_href;
82
+ char *_name;
83
+ };
84
+
85
+ /* "lxml/etree.pyx":2677
86
+ * self._name = NULL
87
+ *
88
+ * cdef public class _ElementIterator(_ElementTagMatcher) [ # <<<<<<<<<<<<<<
89
+ * object LxmlElementIterator, type LxmlElementIteratorType ]:
90
+ * """
91
+ */
92
+ struct LxmlElementIterator {
93
+ struct LxmlElementTagMatcher __pyx_base;
94
+ struct LxmlElement *_node;
95
+ _node_to_node_function _next_element;
96
+ };
97
+
98
+ /* "src/lxml/classlookup.pxi":6
99
+ * # Custom Element classes
100
+ *
101
+ * cdef public class ElementBase(_Element) [ type LxmlElementBaseType, # <<<<<<<<<<<<<<
102
+ * object LxmlElementBase ]:
103
+ * """ElementBase(*children, attrib=None, nsmap=None, **_extra)
104
+ */
105
+ struct LxmlElementBase {
106
+ struct LxmlElement __pyx_base;
107
+ };
108
+
109
+ /* "src/lxml/classlookup.pxi":210
110
+ * # Element class lookup
111
+ *
112
+ * ctypedef public object (*_element_class_lookup_function)(object, _Document, xmlNode*) # <<<<<<<<<<<<<<
113
+ *
114
+ * # class to store element class lookup functions
115
+ */
116
+ typedef PyObject *(*_element_class_lookup_function)(PyObject *, struct LxmlDocument *, xmlNode *);
117
+
118
+ /* "src/lxml/classlookup.pxi":213
119
+ *
120
+ * # class to store element class lookup functions
121
+ * cdef public class ElementClassLookup [ type LxmlElementClassLookupType, # <<<<<<<<<<<<<<
122
+ * object LxmlElementClassLookup ]:
123
+ * """ElementClassLookup(self)
124
+ */
125
+ struct LxmlElementClassLookup {
126
+ PyObject_HEAD
127
+ _element_class_lookup_function _lookup_function;
128
+ };
129
+
130
+ /* "src/lxml/classlookup.pxi":221
131
+ *
132
+ *
133
+ * cdef public class FallbackElementClassLookup(ElementClassLookup) \ # <<<<<<<<<<<<<<
134
+ * [ type LxmlFallbackElementClassLookupType,
135
+ * object LxmlFallbackElementClassLookup ]:
136
+ */
137
+ struct LxmlFallbackElementClassLookup {
138
+ struct LxmlElementClassLookup __pyx_base;
139
+ struct __pyx_vtabstruct_4lxml_5etree_FallbackElementClassLookup *__pyx_vtab;
140
+ struct LxmlElementClassLookup *fallback;
141
+ _element_class_lookup_function _fallback_function;
142
+ };
143
+
144
+ #ifndef __PYX_HAVE_API__lxml__etree
145
+
146
+ #ifdef CYTHON_EXTERN_C
147
+ #undef __PYX_EXTERN_C
148
+ #define __PYX_EXTERN_C CYTHON_EXTERN_C
149
+ #elif defined(__PYX_EXTERN_C)
150
+ #ifdef _MSC_VER
151
+ #pragma message ("Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.")
152
+ #else
153
+ #warning Please do not define the '__PYX_EXTERN_C' macro externally. Use 'CYTHON_EXTERN_C' instead.
154
+ #endif
155
+ #else
156
+ #ifdef __cplusplus
157
+ #define __PYX_EXTERN_C extern "C"
158
+ #else
159
+ #define __PYX_EXTERN_C extern
160
+ #endif
161
+ #endif
162
+
163
+ #ifndef DL_IMPORT
164
+ #define DL_IMPORT(_T) _T
165
+ #endif
166
+
167
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlDocumentType;
168
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementType;
169
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTreeType;
170
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementTagMatcherType;
171
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementIteratorType;
172
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementBaseType;
173
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlElementClassLookupType;
174
+ __PYX_EXTERN_C DL_IMPORT(PyTypeObject) LxmlFallbackElementClassLookupType;
175
+
176
+ __PYX_EXTERN_C struct LxmlElement *deepcopyNodeToDocument(struct LxmlDocument *, xmlNode *);
177
+ __PYX_EXTERN_C struct LxmlElementTree *elementTreeFactory(struct LxmlElement *);
178
+ __PYX_EXTERN_C struct LxmlElementTree *newElementTree(struct LxmlElement *, PyObject *);
179
+ __PYX_EXTERN_C struct LxmlElementTree *adoptExternalDocument(xmlDoc *, PyObject *, int);
180
+ __PYX_EXTERN_C struct LxmlElement *elementFactory(struct LxmlDocument *, xmlNode *);
181
+ __PYX_EXTERN_C struct LxmlElement *makeElement(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
182
+ __PYX_EXTERN_C struct LxmlElement *makeSubElement(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *);
183
+ __PYX_EXTERN_C void setElementClassLookupFunction(_element_class_lookup_function, PyObject *);
184
+ __PYX_EXTERN_C PyObject *lookupDefaultElementClass(PyObject *, PyObject *, xmlNode *);
185
+ __PYX_EXTERN_C PyObject *lookupNamespaceElementClass(PyObject *, PyObject *, xmlNode *);
186
+ __PYX_EXTERN_C PyObject *callLookupFallback(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *);
187
+ __PYX_EXTERN_C int tagMatches(xmlNode *, const xmlChar *, const xmlChar *);
188
+ __PYX_EXTERN_C struct LxmlDocument *documentOrRaise(PyObject *);
189
+ __PYX_EXTERN_C struct LxmlElement *rootNodeOrRaise(PyObject *);
190
+ __PYX_EXTERN_C int hasText(xmlNode *);
191
+ __PYX_EXTERN_C int hasTail(xmlNode *);
192
+ __PYX_EXTERN_C PyObject *textOf(xmlNode *);
193
+ __PYX_EXTERN_C PyObject *tailOf(xmlNode *);
194
+ __PYX_EXTERN_C int setNodeText(xmlNode *, PyObject *);
195
+ __PYX_EXTERN_C int setTailText(xmlNode *, PyObject *);
196
+ __PYX_EXTERN_C PyObject *attributeValue(xmlNode *, xmlAttr *);
197
+ __PYX_EXTERN_C PyObject *attributeValueFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
198
+ __PYX_EXTERN_C PyObject *getAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
199
+ __PYX_EXTERN_C PyObject *iterattributes(struct LxmlElement *, int);
200
+ __PYX_EXTERN_C PyObject *collectAttributes(xmlNode *, int);
201
+ __PYX_EXTERN_C int setAttributeValue(struct LxmlElement *, PyObject *, PyObject *);
202
+ __PYX_EXTERN_C int delAttribute(struct LxmlElement *, PyObject *);
203
+ __PYX_EXTERN_C int delAttributeFromNsName(xmlNode *, const xmlChar *, const xmlChar *);
204
+ __PYX_EXTERN_C int hasChild(xmlNode *);
205
+ __PYX_EXTERN_C xmlNode *findChild(xmlNode *, Py_ssize_t);
206
+ __PYX_EXTERN_C xmlNode *findChildForwards(xmlNode *, Py_ssize_t);
207
+ __PYX_EXTERN_C xmlNode *findChildBackwards(xmlNode *, Py_ssize_t);
208
+ __PYX_EXTERN_C xmlNode *nextElement(xmlNode *);
209
+ __PYX_EXTERN_C xmlNode *previousElement(xmlNode *);
210
+ __PYX_EXTERN_C void appendChild(struct LxmlElement *, struct LxmlElement *);
211
+ __PYX_EXTERN_C int appendChildToElement(struct LxmlElement *, struct LxmlElement *);
212
+ __PYX_EXTERN_C PyObject *pyunicode(const xmlChar *);
213
+ __PYX_EXTERN_C PyObject *utf8(PyObject *);
214
+ __PYX_EXTERN_C PyObject *getNsTag(PyObject *);
215
+ __PYX_EXTERN_C PyObject *getNsTagWithEmptyNs(PyObject *);
216
+ __PYX_EXTERN_C PyObject *namespacedName(xmlNode *);
217
+ __PYX_EXTERN_C PyObject *namespacedNameFromNsName(const xmlChar *, const xmlChar *);
218
+ __PYX_EXTERN_C void iteratorStoreNext(struct LxmlElementIterator *, struct LxmlElement *);
219
+ __PYX_EXTERN_C void initTagMatch(struct LxmlElementTagMatcher *, PyObject *);
220
+ __PYX_EXTERN_C xmlNs *findOrBuildNodeNsPrefix(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *);
221
+
222
+ #endif /* !__PYX_HAVE_API__lxml__etree */
223
+
224
+ /* WARNING: the interface of the module init function changed in CPython 3.5. */
225
+ /* It now returns a PyModuleDef instance instead of a PyModule instance. */
226
+
227
+ #if PY_MAJOR_VERSION < 3
228
+ PyMODINIT_FUNC initetree(void);
229
+ #else
230
+ /* WARNING: Use PyImport_AppendInittab("etree", PyInit_etree) instead of calling PyInit_etree directly from Python 3.5 */
231
+ PyMODINIT_FUNC PyInit_etree(void);
232
+
233
+ #if PY_VERSION_HEX >= 0x03050000 && (defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER) || (defined(__cplusplus) && __cplusplus >= 201402L))
234
+ #if defined(__cplusplus) && __cplusplus >= 201402L
235
+ [[deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")]] inline
236
+ #elif defined(__GNUC__) || defined(__clang__)
237
+ __attribute__ ((__deprecated__("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly."), __unused__)) __inline__
238
+ #elif defined(_MSC_VER)
239
+ __declspec(deprecated("Use PyImport_AppendInittab(\"etree\", PyInit_etree) instead of calling PyInit_etree directly.")) __inline
240
+ #endif
241
+ static PyObject* __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyObject* res) {
242
+ return res;
243
+ }
244
+ #define PyInit_etree() __PYX_WARN_IF_PyInit_etree_INIT_CALLED(PyInit_etree())
245
+ #endif
246
+ #endif
247
+
248
+ #endif /* !__PYX_HAVE__lxml__etree */
venv/lib/python3.10/site-packages/lxml/etree.pyx ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/lxml/etree_api.h ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Generated by Cython 3.0.10 */
2
+
3
+ #ifndef __PYX_HAVE_API__lxml__etree
4
+ #define __PYX_HAVE_API__lxml__etree
5
+ #ifdef __MINGW64__
6
+ #define MS_WIN64
7
+ #endif
8
+ #include "Python.h"
9
+ #include "etree.h"
10
+
11
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument)(struct LxmlDocument *, xmlNode *) = 0;
12
+ #define deepcopyNodeToDocument __pyx_api_f_4lxml_5etree_deepcopyNodeToDocument
13
+ static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_elementTreeFactory)(struct LxmlElement *) = 0;
14
+ #define elementTreeFactory __pyx_api_f_4lxml_5etree_elementTreeFactory
15
+ static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_newElementTree)(struct LxmlElement *, PyObject *) = 0;
16
+ #define newElementTree __pyx_api_f_4lxml_5etree_newElementTree
17
+ static struct LxmlElementTree *(*__pyx_api_f_4lxml_5etree_adoptExternalDocument)(xmlDoc *, PyObject *, int) = 0;
18
+ #define adoptExternalDocument __pyx_api_f_4lxml_5etree_adoptExternalDocument
19
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_elementFactory)(struct LxmlDocument *, xmlNode *) = 0;
20
+ #define elementFactory __pyx_api_f_4lxml_5etree_elementFactory
21
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeElement)(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
22
+ #define makeElement __pyx_api_f_4lxml_5etree_makeElement
23
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_makeSubElement)(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *) = 0;
24
+ #define makeSubElement __pyx_api_f_4lxml_5etree_makeSubElement
25
+ static void (*__pyx_api_f_4lxml_5etree_setElementClassLookupFunction)(_element_class_lookup_function, PyObject *) = 0;
26
+ #define setElementClassLookupFunction __pyx_api_f_4lxml_5etree_setElementClassLookupFunction
27
+ static PyObject *(*__pyx_api_f_4lxml_5etree_lookupDefaultElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
28
+ #define lookupDefaultElementClass __pyx_api_f_4lxml_5etree_lookupDefaultElementClass
29
+ static PyObject *(*__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass)(PyObject *, PyObject *, xmlNode *) = 0;
30
+ #define lookupNamespaceElementClass __pyx_api_f_4lxml_5etree_lookupNamespaceElementClass
31
+ static PyObject *(*__pyx_api_f_4lxml_5etree_callLookupFallback)(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *) = 0;
32
+ #define callLookupFallback __pyx_api_f_4lxml_5etree_callLookupFallback
33
+ static int (*__pyx_api_f_4lxml_5etree_tagMatches)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
34
+ #define tagMatches __pyx_api_f_4lxml_5etree_tagMatches
35
+ static struct LxmlDocument *(*__pyx_api_f_4lxml_5etree_documentOrRaise)(PyObject *) = 0;
36
+ #define documentOrRaise __pyx_api_f_4lxml_5etree_documentOrRaise
37
+ static struct LxmlElement *(*__pyx_api_f_4lxml_5etree_rootNodeOrRaise)(PyObject *) = 0;
38
+ #define rootNodeOrRaise __pyx_api_f_4lxml_5etree_rootNodeOrRaise
39
+ static int (*__pyx_api_f_4lxml_5etree_hasText)(xmlNode *) = 0;
40
+ #define hasText __pyx_api_f_4lxml_5etree_hasText
41
+ static int (*__pyx_api_f_4lxml_5etree_hasTail)(xmlNode *) = 0;
42
+ #define hasTail __pyx_api_f_4lxml_5etree_hasTail
43
+ static PyObject *(*__pyx_api_f_4lxml_5etree_textOf)(xmlNode *) = 0;
44
+ #define textOf __pyx_api_f_4lxml_5etree_textOf
45
+ static PyObject *(*__pyx_api_f_4lxml_5etree_tailOf)(xmlNode *) = 0;
46
+ #define tailOf __pyx_api_f_4lxml_5etree_tailOf
47
+ static int (*__pyx_api_f_4lxml_5etree_setNodeText)(xmlNode *, PyObject *) = 0;
48
+ #define setNodeText __pyx_api_f_4lxml_5etree_setNodeText
49
+ static int (*__pyx_api_f_4lxml_5etree_setTailText)(xmlNode *, PyObject *) = 0;
50
+ #define setTailText __pyx_api_f_4lxml_5etree_setTailText
51
+ static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValue)(xmlNode *, xmlAttr *) = 0;
52
+ #define attributeValue __pyx_api_f_4lxml_5etree_attributeValue
53
+ static PyObject *(*__pyx_api_f_4lxml_5etree_attributeValueFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
54
+ #define attributeValueFromNsName __pyx_api_f_4lxml_5etree_attributeValueFromNsName
55
+ static PyObject *(*__pyx_api_f_4lxml_5etree_getAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
56
+ #define getAttributeValue __pyx_api_f_4lxml_5etree_getAttributeValue
57
+ static PyObject *(*__pyx_api_f_4lxml_5etree_iterattributes)(struct LxmlElement *, int) = 0;
58
+ #define iterattributes __pyx_api_f_4lxml_5etree_iterattributes
59
+ static PyObject *(*__pyx_api_f_4lxml_5etree_collectAttributes)(xmlNode *, int) = 0;
60
+ #define collectAttributes __pyx_api_f_4lxml_5etree_collectAttributes
61
+ static int (*__pyx_api_f_4lxml_5etree_setAttributeValue)(struct LxmlElement *, PyObject *, PyObject *) = 0;
62
+ #define setAttributeValue __pyx_api_f_4lxml_5etree_setAttributeValue
63
+ static int (*__pyx_api_f_4lxml_5etree_delAttribute)(struct LxmlElement *, PyObject *) = 0;
64
+ #define delAttribute __pyx_api_f_4lxml_5etree_delAttribute
65
+ static int (*__pyx_api_f_4lxml_5etree_delAttributeFromNsName)(xmlNode *, const xmlChar *, const xmlChar *) = 0;
66
+ #define delAttributeFromNsName __pyx_api_f_4lxml_5etree_delAttributeFromNsName
67
+ static int (*__pyx_api_f_4lxml_5etree_hasChild)(xmlNode *) = 0;
68
+ #define hasChild __pyx_api_f_4lxml_5etree_hasChild
69
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_findChild)(xmlNode *, Py_ssize_t) = 0;
70
+ #define findChild __pyx_api_f_4lxml_5etree_findChild
71
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildForwards)(xmlNode *, Py_ssize_t) = 0;
72
+ #define findChildForwards __pyx_api_f_4lxml_5etree_findChildForwards
73
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_findChildBackwards)(xmlNode *, Py_ssize_t) = 0;
74
+ #define findChildBackwards __pyx_api_f_4lxml_5etree_findChildBackwards
75
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_nextElement)(xmlNode *) = 0;
76
+ #define nextElement __pyx_api_f_4lxml_5etree_nextElement
77
+ static xmlNode *(*__pyx_api_f_4lxml_5etree_previousElement)(xmlNode *) = 0;
78
+ #define previousElement __pyx_api_f_4lxml_5etree_previousElement
79
+ static void (*__pyx_api_f_4lxml_5etree_appendChild)(struct LxmlElement *, struct LxmlElement *) = 0;
80
+ #define appendChild __pyx_api_f_4lxml_5etree_appendChild
81
+ static int (*__pyx_api_f_4lxml_5etree_appendChildToElement)(struct LxmlElement *, struct LxmlElement *) = 0;
82
+ #define appendChildToElement __pyx_api_f_4lxml_5etree_appendChildToElement
83
+ static PyObject *(*__pyx_api_f_4lxml_5etree_pyunicode)(const xmlChar *) = 0;
84
+ #define pyunicode __pyx_api_f_4lxml_5etree_pyunicode
85
+ static PyObject *(*__pyx_api_f_4lxml_5etree_utf8)(PyObject *) = 0;
86
+ #define utf8 __pyx_api_f_4lxml_5etree_utf8
87
+ static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTag)(PyObject *) = 0;
88
+ #define getNsTag __pyx_api_f_4lxml_5etree_getNsTag
89
+ static PyObject *(*__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs)(PyObject *) = 0;
90
+ #define getNsTagWithEmptyNs __pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs
91
+ static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedName)(xmlNode *) = 0;
92
+ #define namespacedName __pyx_api_f_4lxml_5etree_namespacedName
93
+ static PyObject *(*__pyx_api_f_4lxml_5etree_namespacedNameFromNsName)(const xmlChar *, const xmlChar *) = 0;
94
+ #define namespacedNameFromNsName __pyx_api_f_4lxml_5etree_namespacedNameFromNsName
95
+ static void (*__pyx_api_f_4lxml_5etree_iteratorStoreNext)(struct LxmlElementIterator *, struct LxmlElement *) = 0;
96
+ #define iteratorStoreNext __pyx_api_f_4lxml_5etree_iteratorStoreNext
97
+ static void (*__pyx_api_f_4lxml_5etree_initTagMatch)(struct LxmlElementTagMatcher *, PyObject *) = 0;
98
+ #define initTagMatch __pyx_api_f_4lxml_5etree_initTagMatch
99
+ static xmlNs *(*__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix)(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *) = 0;
100
+ #define findOrBuildNodeNsPrefix __pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix
101
+ #ifndef __PYX_HAVE_RT_ImportFunction_3_0_10
102
+ #define __PYX_HAVE_RT_ImportFunction_3_0_10
103
+ static int __Pyx_ImportFunction_3_0_10(PyObject *module, const char *funcname, void (**f)(void), const char *sig) {
104
+ PyObject *d = 0;
105
+ PyObject *cobj = 0;
106
+ union {
107
+ void (*fp)(void);
108
+ void *p;
109
+ } tmp;
110
+ d = PyObject_GetAttrString(module, (char *)"__pyx_capi__");
111
+ if (!d)
112
+ goto bad;
113
+ cobj = PyDict_GetItemString(d, funcname);
114
+ if (!cobj) {
115
+ PyErr_Format(PyExc_ImportError,
116
+ "%.200s does not export expected C function %.200s",
117
+ PyModule_GetName(module), funcname);
118
+ goto bad;
119
+ }
120
+ if (!PyCapsule_IsValid(cobj, sig)) {
121
+ PyErr_Format(PyExc_TypeError,
122
+ "C function %.200s.%.200s has wrong signature (expected %.500s, got %.500s)",
123
+ PyModule_GetName(module), funcname, sig, PyCapsule_GetName(cobj));
124
+ goto bad;
125
+ }
126
+ tmp.p = PyCapsule_GetPointer(cobj, sig);
127
+ *f = tmp.fp;
128
+ if (!(*f))
129
+ goto bad;
130
+ Py_DECREF(d);
131
+ return 0;
132
+ bad:
133
+ Py_XDECREF(d);
134
+ return -1;
135
+ }
136
+ #endif
137
+
138
+
139
+ static int import_lxml__etree(void) {
140
+ PyObject *module = 0;
141
+ module = PyImport_ImportModule("lxml.etree");
142
+ if (!module) goto bad;
143
+ if (__Pyx_ImportFunction_3_0_10(module, "deepcopyNodeToDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_deepcopyNodeToDocument, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
144
+ if (__Pyx_ImportFunction_3_0_10(module, "elementTreeFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementTreeFactory, "struct LxmlElementTree *(struct LxmlElement *)") < 0) goto bad;
145
+ if (__Pyx_ImportFunction_3_0_10(module, "newElementTree", (void (**)(void))&__pyx_api_f_4lxml_5etree_newElementTree, "struct LxmlElementTree *(struct LxmlElement *, PyObject *)") < 0) goto bad;
146
+ if (__Pyx_ImportFunction_3_0_10(module, "adoptExternalDocument", (void (**)(void))&__pyx_api_f_4lxml_5etree_adoptExternalDocument, "struct LxmlElementTree *(xmlDoc *, PyObject *, int)") < 0) goto bad;
147
+ if (__Pyx_ImportFunction_3_0_10(module, "elementFactory", (void (**)(void))&__pyx_api_f_4lxml_5etree_elementFactory, "struct LxmlElement *(struct LxmlDocument *, xmlNode *)") < 0) goto bad;
148
+ if (__Pyx_ImportFunction_3_0_10(module, "makeElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeElement, "struct LxmlElement *(PyObject *, struct LxmlDocument *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
149
+ if (__Pyx_ImportFunction_3_0_10(module, "makeSubElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_makeSubElement, "struct LxmlElement *(struct LxmlElement *, PyObject *, PyObject *, PyObject *, PyObject *, PyObject *)") < 0) goto bad;
150
+ if (__Pyx_ImportFunction_3_0_10(module, "setElementClassLookupFunction", (void (**)(void))&__pyx_api_f_4lxml_5etree_setElementClassLookupFunction, "void (_element_class_lookup_function, PyObject *)") < 0) goto bad;
151
+ if (__Pyx_ImportFunction_3_0_10(module, "lookupDefaultElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupDefaultElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
152
+ if (__Pyx_ImportFunction_3_0_10(module, "lookupNamespaceElementClass", (void (**)(void))&__pyx_api_f_4lxml_5etree_lookupNamespaceElementClass, "PyObject *(PyObject *, PyObject *, xmlNode *)") < 0) goto bad;
153
+ if (__Pyx_ImportFunction_3_0_10(module, "callLookupFallback", (void (**)(void))&__pyx_api_f_4lxml_5etree_callLookupFallback, "PyObject *(struct LxmlFallbackElementClassLookup *, struct LxmlDocument *, xmlNode *)") < 0) goto bad;
154
+ if (__Pyx_ImportFunction_3_0_10(module, "tagMatches", (void (**)(void))&__pyx_api_f_4lxml_5etree_tagMatches, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
155
+ if (__Pyx_ImportFunction_3_0_10(module, "documentOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_documentOrRaise, "struct LxmlDocument *(PyObject *)") < 0) goto bad;
156
+ if (__Pyx_ImportFunction_3_0_10(module, "rootNodeOrRaise", (void (**)(void))&__pyx_api_f_4lxml_5etree_rootNodeOrRaise, "struct LxmlElement *(PyObject *)") < 0) goto bad;
157
+ if (__Pyx_ImportFunction_3_0_10(module, "hasText", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasText, "int (xmlNode *)") < 0) goto bad;
158
+ if (__Pyx_ImportFunction_3_0_10(module, "hasTail", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasTail, "int (xmlNode *)") < 0) goto bad;
159
+ if (__Pyx_ImportFunction_3_0_10(module, "textOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_textOf, "PyObject *(xmlNode *)") < 0) goto bad;
160
+ if (__Pyx_ImportFunction_3_0_10(module, "tailOf", (void (**)(void))&__pyx_api_f_4lxml_5etree_tailOf, "PyObject *(xmlNode *)") < 0) goto bad;
161
+ if (__Pyx_ImportFunction_3_0_10(module, "setNodeText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setNodeText, "int (xmlNode *, PyObject *)") < 0) goto bad;
162
+ if (__Pyx_ImportFunction_3_0_10(module, "setTailText", (void (**)(void))&__pyx_api_f_4lxml_5etree_setTailText, "int (xmlNode *, PyObject *)") < 0) goto bad;
163
+ if (__Pyx_ImportFunction_3_0_10(module, "attributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValue, "PyObject *(xmlNode *, xmlAttr *)") < 0) goto bad;
164
+ if (__Pyx_ImportFunction_3_0_10(module, "attributeValueFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_attributeValueFromNsName, "PyObject *(xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
165
+ if (__Pyx_ImportFunction_3_0_10(module, "getAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_getAttributeValue, "PyObject *(struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
166
+ if (__Pyx_ImportFunction_3_0_10(module, "iterattributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_iterattributes, "PyObject *(struct LxmlElement *, int)") < 0) goto bad;
167
+ if (__Pyx_ImportFunction_3_0_10(module, "collectAttributes", (void (**)(void))&__pyx_api_f_4lxml_5etree_collectAttributes, "PyObject *(xmlNode *, int)") < 0) goto bad;
168
+ if (__Pyx_ImportFunction_3_0_10(module, "setAttributeValue", (void (**)(void))&__pyx_api_f_4lxml_5etree_setAttributeValue, "int (struct LxmlElement *, PyObject *, PyObject *)") < 0) goto bad;
169
+ if (__Pyx_ImportFunction_3_0_10(module, "delAttribute", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttribute, "int (struct LxmlElement *, PyObject *)") < 0) goto bad;
170
+ if (__Pyx_ImportFunction_3_0_10(module, "delAttributeFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_delAttributeFromNsName, "int (xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
171
+ if (__Pyx_ImportFunction_3_0_10(module, "hasChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_hasChild, "int (xmlNode *)") < 0) goto bad;
172
+ if (__Pyx_ImportFunction_3_0_10(module, "findChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChild, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
173
+ if (__Pyx_ImportFunction_3_0_10(module, "findChildForwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildForwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
174
+ if (__Pyx_ImportFunction_3_0_10(module, "findChildBackwards", (void (**)(void))&__pyx_api_f_4lxml_5etree_findChildBackwards, "xmlNode *(xmlNode *, Py_ssize_t)") < 0) goto bad;
175
+ if (__Pyx_ImportFunction_3_0_10(module, "nextElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_nextElement, "xmlNode *(xmlNode *)") < 0) goto bad;
176
+ if (__Pyx_ImportFunction_3_0_10(module, "previousElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_previousElement, "xmlNode *(xmlNode *)") < 0) goto bad;
177
+ if (__Pyx_ImportFunction_3_0_10(module, "appendChild", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChild, "void (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
178
+ if (__Pyx_ImportFunction_3_0_10(module, "appendChildToElement", (void (**)(void))&__pyx_api_f_4lxml_5etree_appendChildToElement, "int (struct LxmlElement *, struct LxmlElement *)") < 0) goto bad;
179
+ if (__Pyx_ImportFunction_3_0_10(module, "pyunicode", (void (**)(void))&__pyx_api_f_4lxml_5etree_pyunicode, "PyObject *(const xmlChar *)") < 0) goto bad;
180
+ if (__Pyx_ImportFunction_3_0_10(module, "utf8", (void (**)(void))&__pyx_api_f_4lxml_5etree_utf8, "PyObject *(PyObject *)") < 0) goto bad;
181
+ if (__Pyx_ImportFunction_3_0_10(module, "getNsTag", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTag, "PyObject *(PyObject *)") < 0) goto bad;
182
+ if (__Pyx_ImportFunction_3_0_10(module, "getNsTagWithEmptyNs", (void (**)(void))&__pyx_api_f_4lxml_5etree_getNsTagWithEmptyNs, "PyObject *(PyObject *)") < 0) goto bad;
183
+ if (__Pyx_ImportFunction_3_0_10(module, "namespacedName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedName, "PyObject *(xmlNode *)") < 0) goto bad;
184
+ if (__Pyx_ImportFunction_3_0_10(module, "namespacedNameFromNsName", (void (**)(void))&__pyx_api_f_4lxml_5etree_namespacedNameFromNsName, "PyObject *(const xmlChar *, const xmlChar *)") < 0) goto bad;
185
+ if (__Pyx_ImportFunction_3_0_10(module, "iteratorStoreNext", (void (**)(void))&__pyx_api_f_4lxml_5etree_iteratorStoreNext, "void (struct LxmlElementIterator *, struct LxmlElement *)") < 0) goto bad;
186
+ if (__Pyx_ImportFunction_3_0_10(module, "initTagMatch", (void (**)(void))&__pyx_api_f_4lxml_5etree_initTagMatch, "void (struct LxmlElementTagMatcher *, PyObject *)") < 0) goto bad;
187
+ if (__Pyx_ImportFunction_3_0_10(module, "findOrBuildNodeNsPrefix", (void (**)(void))&__pyx_api_f_4lxml_5etree_findOrBuildNodeNsPrefix, "xmlNs *(struct LxmlDocument *, xmlNode *, const xmlChar *, const xmlChar *)") < 0) goto bad;
188
+ Py_DECREF(module); module = 0;
189
+ return 0;
190
+ bad:
191
+ Py_XDECREF(module);
192
+ return -1;
193
+ }
194
+
195
+ #endif /* !__PYX_HAVE_API__lxml__etree */
venv/lib/python3.10/site-packages/lxml/extensions.pxi ADDED
@@ -0,0 +1,833 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # support for extension functions in XPath and XSLT
2
+
3
+ cdef class XPathError(LxmlError):
4
+ """Base class of all XPath errors.
5
+ """
6
+
7
+ cdef class XPathEvalError(XPathError):
8
+ """Error during XPath evaluation.
9
+ """
10
+
11
+ cdef class XPathFunctionError(XPathEvalError):
12
+ """Internal error looking up an XPath extension function.
13
+ """
14
+
15
+ cdef class XPathResultError(XPathEvalError):
16
+ """Error handling an XPath result.
17
+ """
18
+
19
+
20
+ # forward declarations
21
+
22
+ ctypedef int (*_register_function)(void* ctxt, name_utf, ns_uri_utf)
23
+ cdef class _ExsltRegExp
24
+
25
+ ################################################################################
26
+ # Base class for XSLT and XPath evaluation contexts: functions, namespaces, ...
27
+
28
+ @cython.internal
29
+ cdef class _BaseContext:
30
+ cdef xpath.xmlXPathContext* _xpathCtxt
31
+ cdef _Document _doc
32
+ cdef dict _extensions
33
+ cdef list _namespaces
34
+ cdef list _global_namespaces
35
+ cdef dict _utf_refs
36
+ cdef dict _function_cache
37
+ cdef dict _eval_context_dict
38
+ cdef bint _build_smart_strings
39
+ # for exception handling and temporary reference keeping:
40
+ cdef _TempStore _temp_refs
41
+ cdef set _temp_documents
42
+ cdef _ExceptionContext _exc
43
+ cdef _ErrorLog _error_log
44
+
45
+ def __cinit__(self):
46
+ self._xpathCtxt = NULL
47
+
48
+ def __init__(self, namespaces, extensions, error_log, enable_regexp,
49
+ build_smart_strings):
50
+ cdef _ExsltRegExp _regexp
51
+ cdef dict new_extensions
52
+ cdef list ns
53
+ self._utf_refs = {}
54
+ self._global_namespaces = []
55
+ self._function_cache = {}
56
+ self._eval_context_dict = None
57
+ self._error_log = error_log
58
+
59
+ if extensions is not None:
60
+ # convert extensions to UTF-8
61
+ if isinstance(extensions, dict):
62
+ extensions = (extensions,)
63
+ # format: [ {(ns, name):function} ] -> {(ns_utf, name_utf):function}
64
+ new_extensions = {}
65
+ for extension in extensions:
66
+ for (ns_uri, name), function in extension.items():
67
+ if name is None:
68
+ raise ValueError, "extensions must have non empty names"
69
+ ns_utf = self._to_utf(ns_uri)
70
+ name_utf = self._to_utf(name)
71
+ new_extensions[(ns_utf, name_utf)] = function
72
+ extensions = new_extensions or None
73
+
74
+ if namespaces is not None:
75
+ if isinstance(namespaces, dict):
76
+ namespaces = namespaces.items()
77
+ if namespaces:
78
+ ns = []
79
+ for prefix, ns_uri in namespaces:
80
+ if prefix is None or not prefix:
81
+ raise TypeError, \
82
+ "empty namespace prefix is not supported in XPath"
83
+ if ns_uri is None or not ns_uri:
84
+ raise TypeError, \
85
+ "setting default namespace is not supported in XPath"
86
+ prefix_utf = self._to_utf(prefix)
87
+ ns_uri_utf = self._to_utf(ns_uri)
88
+ ns.append( (prefix_utf, ns_uri_utf) )
89
+ namespaces = ns
90
+ else:
91
+ namespaces = None
92
+
93
+ self._doc = None
94
+ self._exc = _ExceptionContext()
95
+ self._extensions = extensions
96
+ self._namespaces = namespaces
97
+ self._temp_refs = _TempStore()
98
+ self._temp_documents = set()
99
+ self._build_smart_strings = build_smart_strings
100
+
101
+ if enable_regexp:
102
+ _regexp = _ExsltRegExp()
103
+ _regexp._register_in_context(self)
104
+
105
+ cdef _BaseContext _copy(self):
106
+ cdef _BaseContext context
107
+ if self._namespaces is not None:
108
+ namespaces = self._namespaces[:]
109
+ else:
110
+ namespaces = None
111
+ context = self.__class__(namespaces, None, self._error_log, False,
112
+ self._build_smart_strings)
113
+ if self._extensions is not None:
114
+ context._extensions = self._extensions.copy()
115
+ return context
116
+
117
+ cdef bytes _to_utf(self, s):
118
+ "Convert to UTF-8 and keep a reference to the encoded string"
119
+ cdef python.PyObject* dict_result
120
+ if s is None:
121
+ return None
122
+ dict_result = python.PyDict_GetItem(self._utf_refs, s)
123
+ if dict_result is not NULL:
124
+ return <bytes>dict_result
125
+ utf = _utf8(s)
126
+ self._utf_refs[s] = utf
127
+ if python.IS_PYPY:
128
+ # use C level refs, PyPy refs are not enough!
129
+ python.Py_INCREF(utf)
130
+ return utf
131
+
132
+ cdef void _set_xpath_context(self, xpath.xmlXPathContext* xpathCtxt) noexcept:
133
+ self._xpathCtxt = xpathCtxt
134
+ xpathCtxt.userData = <void*>self
135
+ # Need a cast here because older libxml2 releases do not use 'const' in the functype.
136
+ xpathCtxt.error = <xmlerror.xmlStructuredErrorFunc> _receiveXPathError
137
+
138
+ @cython.final
139
+ cdef _register_context(self, _Document doc):
140
+ self._doc = doc
141
+ self._exc.clear()
142
+
143
+ @cython.final
144
+ cdef _cleanup_context(self):
145
+ #xpath.xmlXPathRegisteredNsCleanup(self._xpathCtxt)
146
+ #self.unregisterGlobalNamespaces()
147
+ if python.IS_PYPY:
148
+ # clean up double refs in PyPy (see "_to_utf()" method)
149
+ for ref in self._utf_refs.itervalues():
150
+ python.Py_DECREF(ref)
151
+ self._utf_refs.clear()
152
+ self._eval_context_dict = None
153
+ self._doc = None
154
+
155
+ @cython.final
156
+ cdef _release_context(self):
157
+ if self._xpathCtxt is not NULL:
158
+ self._xpathCtxt.userData = NULL
159
+ self._xpathCtxt = NULL
160
+
161
+ # namespaces (internal UTF-8 methods with leading '_')
162
+
163
+ cdef addNamespace(self, prefix, ns_uri):
164
+ cdef list namespaces
165
+ if prefix is None:
166
+ raise TypeError, "empty prefix is not supported in XPath"
167
+ prefix_utf = self._to_utf(prefix)
168
+ ns_uri_utf = self._to_utf(ns_uri)
169
+ new_item = (prefix_utf, ns_uri_utf)
170
+ if self._namespaces is None:
171
+ self._namespaces = [new_item]
172
+ else:
173
+ namespaces = []
174
+ for item in self._namespaces:
175
+ if item[0] == prefix_utf:
176
+ item = new_item
177
+ new_item = None
178
+ namespaces.append(item)
179
+ if new_item is not None:
180
+ namespaces.append(new_item)
181
+ self._namespaces = namespaces
182
+ if self._xpathCtxt is not NULL:
183
+ xpath.xmlXPathRegisterNs(
184
+ self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf))
185
+
186
+ cdef registerNamespace(self, prefix, ns_uri):
187
+ if prefix is None:
188
+ raise TypeError, "empty prefix is not supported in XPath"
189
+ prefix_utf = self._to_utf(prefix)
190
+ ns_uri_utf = self._to_utf(ns_uri)
191
+ self._global_namespaces.append(prefix_utf)
192
+ xpath.xmlXPathRegisterNs(self._xpathCtxt,
193
+ _xcstr(prefix_utf), _xcstr(ns_uri_utf))
194
+
195
+ cdef registerLocalNamespaces(self):
196
+ if self._namespaces is None:
197
+ return
198
+ for prefix_utf, ns_uri_utf in self._namespaces:
199
+ xpath.xmlXPathRegisterNs(
200
+ self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf))
201
+
202
+ cdef registerGlobalNamespaces(self):
203
+ cdef list ns_prefixes = _find_all_extension_prefixes()
204
+ if python.PyList_GET_SIZE(ns_prefixes) > 0:
205
+ for prefix_utf, ns_uri_utf in ns_prefixes:
206
+ self._global_namespaces.append(prefix_utf)
207
+ xpath.xmlXPathRegisterNs(
208
+ self._xpathCtxt, _xcstr(prefix_utf), _xcstr(ns_uri_utf))
209
+
210
+ cdef unregisterGlobalNamespaces(self):
211
+ if python.PyList_GET_SIZE(self._global_namespaces) > 0:
212
+ for prefix_utf in self._global_namespaces:
213
+ xpath.xmlXPathRegisterNs(self._xpathCtxt,
214
+ _xcstr(prefix_utf), NULL)
215
+ del self._global_namespaces[:]
216
+
217
+ cdef void _unregisterNamespace(self, prefix_utf) noexcept:
218
+ xpath.xmlXPathRegisterNs(self._xpathCtxt,
219
+ _xcstr(prefix_utf), NULL)
220
+
221
+ # extension functions
222
+
223
+ cdef int _addLocalExtensionFunction(self, ns_utf, name_utf, function) except -1:
224
+ if self._extensions is None:
225
+ self._extensions = {}
226
+ self._extensions[(ns_utf, name_utf)] = function
227
+ return 0
228
+
229
+ cdef registerGlobalFunctions(self, void* ctxt,
230
+ _register_function reg_func):
231
+ cdef python.PyObject* dict_result
232
+ cdef dict d
233
+ for ns_utf, ns_functions in __FUNCTION_NAMESPACE_REGISTRIES.iteritems():
234
+ dict_result = python.PyDict_GetItem(
235
+ self._function_cache, ns_utf)
236
+ if dict_result is not NULL:
237
+ d = <dict>dict_result
238
+ else:
239
+ d = {}
240
+ self._function_cache[ns_utf] = d
241
+ for name_utf, function in ns_functions.iteritems():
242
+ d[name_utf] = function
243
+ reg_func(ctxt, name_utf, ns_utf)
244
+
245
+ cdef registerLocalFunctions(self, void* ctxt,
246
+ _register_function reg_func):
247
+ cdef python.PyObject* dict_result
248
+ cdef dict d
249
+ if self._extensions is None:
250
+ return # done
251
+ last_ns = None
252
+ d = None
253
+ for (ns_utf, name_utf), function in self._extensions.iteritems():
254
+ if ns_utf is not last_ns or d is None:
255
+ last_ns = ns_utf
256
+ dict_result = python.PyDict_GetItem(
257
+ self._function_cache, ns_utf)
258
+ if dict_result is not NULL:
259
+ d = <dict>dict_result
260
+ else:
261
+ d = {}
262
+ self._function_cache[ns_utf] = d
263
+ d[name_utf] = function
264
+ reg_func(ctxt, name_utf, ns_utf)
265
+
266
+ cdef unregisterAllFunctions(self, void* ctxt,
267
+ _register_function unreg_func):
268
+ for ns_utf, functions in self._function_cache.iteritems():
269
+ for name_utf in functions:
270
+ unreg_func(ctxt, name_utf, ns_utf)
271
+
272
+ cdef unregisterGlobalFunctions(self, void* ctxt,
273
+ _register_function unreg_func):
274
+ for ns_utf, functions in self._function_cache.items():
275
+ for name_utf in functions:
276
+ if self._extensions is None or \
277
+ (ns_utf, name_utf) not in self._extensions:
278
+ unreg_func(ctxt, name_utf, ns_utf)
279
+
280
+ @cython.final
281
+ cdef _find_cached_function(self, const_xmlChar* c_ns_uri, const_xmlChar* c_name):
282
+ """Lookup an extension function in the cache and return it.
283
+
284
+ Parameters: c_ns_uri may be NULL, c_name must not be NULL
285
+ """
286
+ cdef python.PyObject* c_dict
287
+ cdef python.PyObject* dict_result
288
+ c_dict = python.PyDict_GetItem(
289
+ self._function_cache, None if c_ns_uri is NULL else c_ns_uri)
290
+ if c_dict is not NULL:
291
+ dict_result = python.PyDict_GetItem(
292
+ <object>c_dict, <unsigned char*>c_name)
293
+ if dict_result is not NULL:
294
+ return <object>dict_result
295
+ return None
296
+
297
+ # Python access to the XPath context for extension functions
298
+
299
+ @property
300
+ def context_node(self):
301
+ cdef xmlNode* c_node
302
+ if self._xpathCtxt is NULL:
303
+ raise XPathError, \
304
+ "XPath context is only usable during the evaluation"
305
+ c_node = self._xpathCtxt.node
306
+ if c_node is NULL:
307
+ raise XPathError, "no context node"
308
+ if c_node.doc != self._xpathCtxt.doc:
309
+ raise XPathError, \
310
+ "document-external context nodes are not supported"
311
+ if self._doc is None:
312
+ raise XPathError, "document context is missing"
313
+ return _elementFactory(self._doc, c_node)
314
+
315
+ @property
316
+ def eval_context(self):
317
+ if self._eval_context_dict is None:
318
+ self._eval_context_dict = {}
319
+ return self._eval_context_dict
320
+
321
+ # Python reference keeping during XPath function evaluation
322
+
323
+ @cython.final
324
+ cdef _release_temp_refs(self):
325
+ "Free temporarily referenced objects from this context."
326
+ self._temp_refs.clear()
327
+ self._temp_documents.clear()
328
+
329
+ @cython.final
330
+ cdef _hold(self, obj):
331
+ """A way to temporarily hold references to nodes in the evaluator.
332
+
333
+ This is needed because otherwise nodes created in XPath extension
334
+ functions would be reference counted too soon, during the XPath
335
+ evaluation. This is most important in the case of exceptions.
336
+ """
337
+ cdef _Element element
338
+ if isinstance(obj, _Element):
339
+ self._temp_refs.add(obj)
340
+ self._temp_documents.add((<_Element>obj)._doc)
341
+ return
342
+ elif _isString(obj) or not python.PySequence_Check(obj):
343
+ return
344
+ for o in obj:
345
+ if isinstance(o, _Element):
346
+ #print "Holding element:", <int>element._c_node
347
+ self._temp_refs.add(o)
348
+ #print "Holding document:", <int>element._doc._c_doc
349
+ self._temp_documents.add((<_Element>o)._doc)
350
+
351
+ @cython.final
352
+ cdef _Document _findDocumentForNode(self, xmlNode* c_node):
353
+ """If an XPath expression returns an element from a different
354
+ document than the current context document, we call this to
355
+ see if it was possibly created by an extension and is a known
356
+ document instance.
357
+ """
358
+ cdef _Document doc
359
+ for doc in self._temp_documents:
360
+ if doc is not None and doc._c_doc is c_node.doc:
361
+ return doc
362
+ return None
363
+
364
+
365
+ # libxml2 keeps these error messages in a static array in its code
366
+ # and doesn't give us access to them ...
367
+
368
+ cdef tuple LIBXML2_XPATH_ERROR_MESSAGES = (
369
+ b"Ok",
370
+ b"Number encoding",
371
+ b"Unfinished literal",
372
+ b"Start of literal",
373
+ b"Expected $ for variable reference",
374
+ b"Undefined variable",
375
+ b"Invalid predicate",
376
+ b"Invalid expression",
377
+ b"Missing closing curly brace",
378
+ b"Unregistered function",
379
+ b"Invalid operand",
380
+ b"Invalid type",
381
+ b"Invalid number of arguments",
382
+ b"Invalid context size",
383
+ b"Invalid context position",
384
+ b"Memory allocation error",
385
+ b"Syntax error",
386
+ b"Resource error",
387
+ b"Sub resource error",
388
+ b"Undefined namespace prefix",
389
+ b"Encoding error",
390
+ b"Char out of XML range",
391
+ b"Invalid or incomplete context",
392
+ b"Stack usage error",
393
+ b"Forbidden variable\n",
394
+ b"?? Unknown error ??\n",
395
+ )
396
+
397
+ cdef void _forwardXPathError(void* c_ctxt, const xmlerror.xmlError* c_error) noexcept with gil:
398
+ cdef xmlerror.xmlError error
399
+ cdef int xpath_code
400
+ if c_error.message is not NULL:
401
+ error.message = c_error.message
402
+ else:
403
+ xpath_code = c_error.code - xmlerror.XML_XPATH_EXPRESSION_OK
404
+ if 0 <= xpath_code < len(LIBXML2_XPATH_ERROR_MESSAGES):
405
+ error.message = _cstr(LIBXML2_XPATH_ERROR_MESSAGES[xpath_code])
406
+ else:
407
+ error.message = b"unknown error"
408
+ error.domain = c_error.domain
409
+ error.code = c_error.code
410
+ error.level = c_error.level
411
+ error.line = c_error.line
412
+ error.int2 = c_error.int1 # column
413
+ error.file = c_error.file
414
+ error.node = NULL
415
+
416
+ (<_BaseContext>c_ctxt)._error_log._receive(&error)
417
+
418
+ cdef void _receiveXPathError(void* c_context, const xmlerror.xmlError* error) noexcept nogil:
419
+ if not __DEBUG:
420
+ return
421
+ if c_context is NULL:
422
+ _forwardError(NULL, error)
423
+ else:
424
+ _forwardXPathError(c_context, error)
425
+
426
+
427
+ def Extension(module, function_mapping=None, *, ns=None):
428
+ """Extension(module, function_mapping=None, ns=None)
429
+
430
+ Build a dictionary of extension functions from the functions
431
+ defined in a module or the methods of an object.
432
+
433
+ As second argument, you can pass an additional mapping of
434
+ attribute names to XPath function names, or a list of function
435
+ names that should be taken.
436
+
437
+ The ``ns`` keyword argument accepts a namespace URI for the XPath
438
+ functions.
439
+ """
440
+ cdef dict functions = {}
441
+ if isinstance(function_mapping, dict):
442
+ for function_name, xpath_name in function_mapping.items():
443
+ functions[(ns, xpath_name)] = getattr(module, function_name)
444
+ else:
445
+ if function_mapping is None:
446
+ function_mapping = [ name for name in dir(module)
447
+ if not name.startswith('_') ]
448
+ for function_name in function_mapping:
449
+ functions[(ns, function_name)] = getattr(module, function_name)
450
+ return functions
451
+
452
+ ################################################################################
453
+ # EXSLT regexp implementation
454
+
455
+ @cython.final
456
+ @cython.internal
457
+ cdef class _ExsltRegExp:
458
+ cdef dict _compile_map
459
+ def __cinit__(self):
460
+ self._compile_map = {}
461
+
462
+ cdef _make_string(self, value):
463
+ if _isString(value):
464
+ return value
465
+ elif isinstance(value, list):
466
+ # node set: take recursive text concatenation of first element
467
+ if python.PyList_GET_SIZE(value) == 0:
468
+ return ''
469
+ firstnode = value[0]
470
+ if _isString(firstnode):
471
+ return firstnode
472
+ elif isinstance(firstnode, _Element):
473
+ c_text = tree.xmlNodeGetContent((<_Element>firstnode)._c_node)
474
+ if c_text is NULL:
475
+ raise MemoryError()
476
+ try:
477
+ return funicode(c_text)
478
+ finally:
479
+ tree.xmlFree(c_text)
480
+ else:
481
+ return unicode(firstnode)
482
+ else:
483
+ return unicode(value)
484
+
485
+ cdef _compile(self, rexp, ignore_case):
486
+ cdef python.PyObject* c_result
487
+ rexp = self._make_string(rexp)
488
+ key = (rexp, ignore_case)
489
+ c_result = python.PyDict_GetItem(self._compile_map, key)
490
+ if c_result is not NULL:
491
+ return <object>c_result
492
+ py_flags = re.UNICODE
493
+ if ignore_case:
494
+ py_flags = py_flags | re.IGNORECASE
495
+ rexp_compiled = re.compile(rexp, py_flags)
496
+ self._compile_map[key] = rexp_compiled
497
+ return rexp_compiled
498
+
499
+ def test(self, ctxt, s, rexp, flags=''):
500
+ flags = self._make_string(flags)
501
+ s = self._make_string(s)
502
+ rexpc = self._compile(rexp, 'i' in flags)
503
+ if rexpc.search(s) is None:
504
+ return False
505
+ else:
506
+ return True
507
+
508
+ def match(self, ctxt, s, rexp, flags=''):
509
+ cdef list result_list
510
+ flags = self._make_string(flags)
511
+ s = self._make_string(s)
512
+ rexpc = self._compile(rexp, 'i' in flags)
513
+ if 'g' in flags:
514
+ results = rexpc.findall(s)
515
+ if not results:
516
+ return ()
517
+ else:
518
+ result = rexpc.search(s)
519
+ if not result:
520
+ return ()
521
+ results = [ result.group() ]
522
+ results.extend( result.groups('') )
523
+ result_list = []
524
+ root = Element('matches')
525
+ for s_match in results:
526
+ if python.PyTuple_CheckExact(s_match):
527
+ s_match = ''.join(s_match)
528
+ elem = SubElement(root, 'match')
529
+ elem.text = s_match
530
+ result_list.append(elem)
531
+ return result_list
532
+
533
+ def replace(self, ctxt, s, rexp, flags, replacement):
534
+ replacement = self._make_string(replacement)
535
+ flags = self._make_string(flags)
536
+ s = self._make_string(s)
537
+ rexpc = self._compile(rexp, 'i' in flags)
538
+ count: object = 0 if 'g' in flags else 1
539
+ return rexpc.sub(replacement, s, count)
540
+
541
+ cdef _register_in_context(self, _BaseContext context):
542
+ ns = b"http://exslt.org/regular-expressions"
543
+ context._addLocalExtensionFunction(ns, b"test", self.test)
544
+ context._addLocalExtensionFunction(ns, b"match", self.match)
545
+ context._addLocalExtensionFunction(ns, b"replace", self.replace)
546
+
547
+
548
+ ################################################################################
549
+ # helper functions
550
+
551
+ cdef xpath.xmlXPathObject* _wrapXPathObject(object obj, _Document doc,
552
+ _BaseContext context) except NULL:
553
+ cdef xpath.xmlNodeSet* resultSet
554
+ cdef _Element fake_node = None
555
+ cdef xmlNode* c_node
556
+
557
+ if isinstance(obj, unicode):
558
+ obj = _utf8(obj)
559
+ if isinstance(obj, bytes):
560
+ # libxml2 copies the string value
561
+ return xpath.xmlXPathNewCString(_cstr(obj))
562
+ if isinstance(obj, bool):
563
+ return xpath.xmlXPathNewBoolean(obj)
564
+ if python.PyNumber_Check(obj):
565
+ return xpath.xmlXPathNewFloat(obj)
566
+ if obj is None:
567
+ resultSet = xpath.xmlXPathNodeSetCreate(NULL)
568
+ elif isinstance(obj, _Element):
569
+ resultSet = xpath.xmlXPathNodeSetCreate((<_Element>obj)._c_node)
570
+ elif python.PySequence_Check(obj):
571
+ resultSet = xpath.xmlXPathNodeSetCreate(NULL)
572
+ try:
573
+ for value in obj:
574
+ if isinstance(value, _Element):
575
+ if context is not None:
576
+ context._hold(value)
577
+ xpath.xmlXPathNodeSetAdd(resultSet, (<_Element>value)._c_node)
578
+ else:
579
+ if context is None or doc is None:
580
+ raise XPathResultError, \
581
+ f"Non-Element values not supported at this point - got {value!r}"
582
+ # support strings by appending text nodes to an Element
583
+ if isinstance(value, unicode):
584
+ value = _utf8(value)
585
+ if isinstance(value, bytes):
586
+ if fake_node is None:
587
+ fake_node = _makeElement("text-root", NULL, doc, None,
588
+ None, None, None, None, None)
589
+ context._hold(fake_node)
590
+ else:
591
+ # append a comment node to keep the text nodes separate
592
+ c_node = tree.xmlNewDocComment(doc._c_doc, <unsigned char*>"")
593
+ if c_node is NULL:
594
+ raise MemoryError()
595
+ tree.xmlAddChild(fake_node._c_node, c_node)
596
+ context._hold(value)
597
+ c_node = tree.xmlNewDocText(doc._c_doc, _xcstr(value))
598
+ if c_node is NULL:
599
+ raise MemoryError()
600
+ tree.xmlAddChild(fake_node._c_node, c_node)
601
+ xpath.xmlXPathNodeSetAdd(resultSet, c_node)
602
+ else:
603
+ raise XPathResultError, \
604
+ f"This is not a supported node-set result: {value!r}"
605
+ except:
606
+ xpath.xmlXPathFreeNodeSet(resultSet)
607
+ raise
608
+ else:
609
+ raise XPathResultError, f"Unknown return type: {python._fqtypename(obj).decode('utf8')}"
610
+ return xpath.xmlXPathWrapNodeSet(resultSet)
611
+
612
+ cdef object _unwrapXPathObject(xpath.xmlXPathObject* xpathObj,
613
+ _Document doc, _BaseContext context):
614
+ if xpathObj.type == xpath.XPATH_UNDEFINED:
615
+ raise XPathResultError, "Undefined xpath result"
616
+ elif xpathObj.type == xpath.XPATH_NODESET:
617
+ return _createNodeSetResult(xpathObj, doc, context)
618
+ elif xpathObj.type == xpath.XPATH_BOOLEAN:
619
+ return xpathObj.boolval
620
+ elif xpathObj.type == xpath.XPATH_NUMBER:
621
+ return xpathObj.floatval
622
+ elif xpathObj.type == xpath.XPATH_STRING:
623
+ stringval = funicode(xpathObj.stringval)
624
+ if context._build_smart_strings:
625
+ stringval = _elementStringResultFactory(
626
+ stringval, None, None, False)
627
+ return stringval
628
+ elif xpathObj.type == xpath.XPATH_POINT:
629
+ raise NotImplementedError, "XPATH_POINT"
630
+ elif xpathObj.type == xpath.XPATH_RANGE:
631
+ raise NotImplementedError, "XPATH_RANGE"
632
+ elif xpathObj.type == xpath.XPATH_LOCATIONSET:
633
+ raise NotImplementedError, "XPATH_LOCATIONSET"
634
+ elif xpathObj.type == xpath.XPATH_USERS:
635
+ raise NotImplementedError, "XPATH_USERS"
636
+ elif xpathObj.type == xpath.XPATH_XSLT_TREE:
637
+ return _createNodeSetResult(xpathObj, doc, context)
638
+ else:
639
+ raise XPathResultError, f"Unknown xpath result {xpathObj.type}"
640
+
641
+ cdef object _createNodeSetResult(xpath.xmlXPathObject* xpathObj, _Document doc,
642
+ _BaseContext context):
643
+ cdef xmlNode* c_node
644
+ cdef int i
645
+ cdef list result
646
+ result = []
647
+ if xpathObj.nodesetval is NULL:
648
+ return result
649
+ for i in range(xpathObj.nodesetval.nodeNr):
650
+ c_node = xpathObj.nodesetval.nodeTab[i]
651
+ _unpackNodeSetEntry(result, c_node, doc, context,
652
+ xpathObj.type == xpath.XPATH_XSLT_TREE)
653
+ return result
654
+
655
+ cdef _unpackNodeSetEntry(list results, xmlNode* c_node, _Document doc,
656
+ _BaseContext context, bint is_fragment):
657
+ cdef xmlNode* c_child
658
+ if _isElement(c_node):
659
+ if c_node.doc != doc._c_doc and c_node.doc._private is NULL:
660
+ # XXX: works, but maybe not always the right thing to do?
661
+ # XPath: only runs when extensions create or copy trees
662
+ # -> we store Python refs to these, so that is OK
663
+ # XSLT: can it leak when merging trees from multiple sources?
664
+ c_node = tree.xmlDocCopyNode(c_node, doc._c_doc, 1)
665
+ # FIXME: call _instantiateElementFromXPath() instead?
666
+ results.append(
667
+ _fakeDocElementFactory(doc, c_node))
668
+ elif c_node.type == tree.XML_TEXT_NODE or \
669
+ c_node.type == tree.XML_CDATA_SECTION_NODE or \
670
+ c_node.type == tree.XML_ATTRIBUTE_NODE:
671
+ results.append(
672
+ _buildElementStringResult(doc, c_node, context))
673
+ elif c_node.type == tree.XML_NAMESPACE_DECL:
674
+ results.append( (funicodeOrNone((<xmlNs*>c_node).prefix),
675
+ funicodeOrNone((<xmlNs*>c_node).href)) )
676
+ elif c_node.type == tree.XML_DOCUMENT_NODE or \
677
+ c_node.type == tree.XML_HTML_DOCUMENT_NODE:
678
+ # ignored for everything but result tree fragments
679
+ if is_fragment:
680
+ c_child = c_node.children
681
+ while c_child is not NULL:
682
+ _unpackNodeSetEntry(results, c_child, doc, context, 0)
683
+ c_child = c_child.next
684
+ elif c_node.type == tree.XML_XINCLUDE_START or \
685
+ c_node.type == tree.XML_XINCLUDE_END:
686
+ pass
687
+ else:
688
+ raise NotImplementedError, \
689
+ f"Not yet implemented result node type: {c_node.type}"
690
+
691
+ cdef void _freeXPathObject(xpath.xmlXPathObject* xpathObj) noexcept:
692
+ """Free the XPath object, but *never* free the *content* of node sets.
693
+ Python dealloc will do that for us.
694
+ """
695
+ if xpathObj.nodesetval is not NULL:
696
+ xpath.xmlXPathFreeNodeSet(xpathObj.nodesetval)
697
+ xpathObj.nodesetval = NULL
698
+ xpath.xmlXPathFreeObject(xpathObj)
699
+
700
+ cdef _Element _instantiateElementFromXPath(xmlNode* c_node, _Document doc,
701
+ _BaseContext context):
702
+ # NOTE: this may copy the element - only call this when it can't leak
703
+ if c_node.doc != doc._c_doc and c_node.doc._private is NULL:
704
+ # not from the context document and not from a fake document
705
+ # either => may still be from a known document, e.g. one
706
+ # created by an extension function
707
+ node_doc = context._findDocumentForNode(c_node)
708
+ if node_doc is None:
709
+ # not from a known document at all! => can only make a
710
+ # safety copy here
711
+ c_node = tree.xmlDocCopyNode(c_node, doc._c_doc, 1)
712
+ else:
713
+ doc = node_doc
714
+ return _fakeDocElementFactory(doc, c_node)
715
+
716
+ ################################################################################
717
+ # special str/unicode subclasses
718
+
719
+ @cython.final
720
+ cdef class _ElementUnicodeResult(unicode):
721
+ cdef _Element _parent
722
+ cdef readonly object attrname
723
+ cdef readonly bint is_tail
724
+
725
+ def getparent(self):
726
+ return self._parent
727
+
728
+ @property
729
+ def is_text(self):
730
+ return self._parent is not None and not (self.is_tail or self.attrname is not None)
731
+
732
+ @property
733
+ def is_attribute(self):
734
+ return self.attrname is not None
735
+
736
+ cdef object _elementStringResultFactory(string_value, _Element parent,
737
+ attrname, bint is_tail):
738
+ result = _ElementUnicodeResult(string_value)
739
+ result._parent = parent
740
+ result.is_tail = is_tail
741
+ result.attrname = attrname
742
+ return result
743
+
744
+ cdef object _buildElementStringResult(_Document doc, xmlNode* c_node,
745
+ _BaseContext context):
746
+ cdef _Element parent = None
747
+ cdef object attrname = None
748
+ cdef xmlNode* c_element
749
+ cdef bint is_tail
750
+
751
+ if c_node.type == tree.XML_ATTRIBUTE_NODE:
752
+ attrname = _namespacedName(c_node)
753
+ is_tail = 0
754
+ s = tree.xmlNodeGetContent(c_node)
755
+ try:
756
+ value = funicode(s)
757
+ finally:
758
+ tree.xmlFree(s)
759
+ c_element = NULL
760
+ else:
761
+ #assert c_node.type == tree.XML_TEXT_NODE or c_node.type == tree.XML_CDATA_SECTION_NODE, "invalid node type"
762
+ # may be tail text or normal text
763
+ value = funicode(c_node.content)
764
+ c_element = _previousElement(c_node)
765
+ is_tail = c_element is not NULL
766
+
767
+ if not context._build_smart_strings:
768
+ return value
769
+
770
+ if c_element is NULL:
771
+ # non-tail text or attribute text
772
+ c_element = c_node.parent
773
+ while c_element is not NULL and not _isElement(c_element):
774
+ c_element = c_element.parent
775
+
776
+ if c_element is not NULL:
777
+ parent = _instantiateElementFromXPath(c_element, doc, context)
778
+
779
+ return _elementStringResultFactory(
780
+ value, parent, attrname, is_tail)
781
+
782
+ ################################################################################
783
+ # callbacks for XPath/XSLT extension functions
784
+
785
+ cdef void _extension_function_call(_BaseContext context, function,
786
+ xpath.xmlXPathParserContext* ctxt, int nargs) noexcept:
787
+ cdef _Document doc
788
+ cdef xpath.xmlXPathObject* obj
789
+ cdef list args
790
+ cdef int i
791
+ doc = context._doc
792
+ try:
793
+ args = []
794
+ for i in range(nargs):
795
+ obj = xpath.valuePop(ctxt)
796
+ o = _unwrapXPathObject(obj, doc, context)
797
+ _freeXPathObject(obj)
798
+ args.append(o)
799
+ args.reverse()
800
+
801
+ res = function(context, *args)
802
+ # wrap result for XPath consumption
803
+ obj = _wrapXPathObject(res, doc, context)
804
+ # prevent Python from deallocating elements handed to libxml2
805
+ context._hold(res)
806
+ xpath.valuePush(ctxt, obj)
807
+ except:
808
+ xpath.xmlXPathErr(ctxt, xpath.XPATH_EXPR_ERROR)
809
+ context._exc._store_raised()
810
+ finally:
811
+ return # swallow any further exceptions
812
+
813
+ # lookup the function by name and call it
814
+
815
+ cdef void _xpath_function_call(xpath.xmlXPathParserContext* ctxt,
816
+ int nargs) noexcept with gil:
817
+ cdef _BaseContext context
818
+ cdef xpath.xmlXPathContext* rctxt = ctxt.context
819
+ context = <_BaseContext> rctxt.userData
820
+ try:
821
+ function = context._find_cached_function(rctxt.functionURI, rctxt.function)
822
+ if function is not None:
823
+ _extension_function_call(context, function, ctxt, nargs)
824
+ else:
825
+ xpath.xmlXPathErr(ctxt, xpath.XPATH_UNKNOWN_FUNC_ERROR)
826
+ context._exc._store_exception(XPathFunctionError(
827
+ f"XPath function '{_namespacedNameFromNsName(rctxt.functionURI, rctxt.function)}' not found"))
828
+ except:
829
+ # may not be the right error, but we need to tell libxml2 *something*
830
+ xpath.xmlXPathErr(ctxt, xpath.XPATH_UNKNOWN_FUNC_ERROR)
831
+ context._exc._store_raised()
832
+ finally:
833
+ return # swallow any further exceptions
venv/lib/python3.10/site-packages/lxml/includes/htmlparser.pxd ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libc.string cimport const_char
2
+
3
+ from lxml.includes.tree cimport xmlDoc
4
+ from lxml.includes.tree cimport xmlInputReadCallback, xmlInputCloseCallback
5
+ from lxml.includes.xmlparser cimport xmlParserCtxt, xmlSAXHandler, xmlSAXHandlerV1
6
+
7
+ cdef extern from "libxml/HTMLparser.h" nogil:
8
+ ctypedef enum htmlParserOption:
9
+ HTML_PARSE_NOERROR # suppress error reports
10
+ HTML_PARSE_NOWARNING # suppress warning reports
11
+ HTML_PARSE_PEDANTIC # pedantic error reporting
12
+ HTML_PARSE_NOBLANKS # remove blank nodes
13
+ HTML_PARSE_NONET # Forbid network access
14
+ # libxml2 2.6.21+ only:
15
+ HTML_PARSE_RECOVER # Relaxed parsing
16
+ HTML_PARSE_COMPACT # compact small text nodes
17
+ # libxml2 2.7.7+ only:
18
+ HTML_PARSE_NOIMPLIED # Do not add implied html/body... elements
19
+ # libxml2 2.7.8+ only:
20
+ HTML_PARSE_NODEFDTD # do not default a doctype if not found
21
+ # libxml2 2.8.0+ only:
22
+ XML_PARSE_IGNORE_ENC # ignore internal document encoding hint
23
+
24
+ xmlSAXHandlerV1 htmlDefaultSAXHandler
25
+
26
+ cdef xmlParserCtxt* htmlCreateMemoryParserCtxt(
27
+ char* buffer, int size)
28
+ cdef xmlParserCtxt* htmlCreateFileParserCtxt(
29
+ char* filename, char* encoding)
30
+ cdef xmlParserCtxt* htmlCreatePushParserCtxt(xmlSAXHandler* sax,
31
+ void* user_data,
32
+ char* chunk, int size,
33
+ char* filename, int enc)
34
+ cdef void htmlFreeParserCtxt(xmlParserCtxt* ctxt)
35
+ cdef void htmlCtxtReset(xmlParserCtxt* ctxt)
36
+ cdef int htmlCtxtUseOptions(xmlParserCtxt* ctxt, int options)
37
+ cdef int htmlParseDocument(xmlParserCtxt* ctxt)
38
+ cdef int htmlParseChunk(xmlParserCtxt* ctxt,
39
+ char* chunk, int size, int terminate)
40
+
41
+ cdef xmlDoc* htmlCtxtReadFile(xmlParserCtxt* ctxt,
42
+ char* filename, const_char* encoding,
43
+ int options)
44
+ cdef xmlDoc* htmlCtxtReadDoc(xmlParserCtxt* ctxt,
45
+ char* buffer, char* URL, const_char* encoding,
46
+ int options)
47
+ cdef xmlDoc* htmlCtxtReadIO(xmlParserCtxt* ctxt,
48
+ xmlInputReadCallback ioread,
49
+ xmlInputCloseCallback ioclose,
50
+ void* ioctx,
51
+ char* URL, const_char* encoding,
52
+ int options)
53
+ cdef xmlDoc* htmlCtxtReadMemory(xmlParserCtxt* ctxt,
54
+ char* buffer, int size,
55
+ char* filename, const_char* encoding,
56
+ int options)
venv/lib/python3.10/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[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.10/site-packages/lxml/isoschematron/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
venv/lib/python3.10/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.10/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.10/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.10/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.10/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.10/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.10/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
+