/
parser.pxi
1881 lines (1642 loc) · 74.6 KB
/
parser.pxi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Parsers for XML and HTML
from lxml.includes cimport xmlparser
from lxml.includes cimport htmlparser
class ParseError(LxmlSyntaxError):
"""Syntax error while parsing an XML document.
For compatibility with ElementTree 1.3 and later.
"""
def __init__(self, message, code, line, column, filename=None):
super(_ParseError, self).__init__(message)
self.lineno, self.offset = (line, column - 1)
self.code = code
self.filename = filename
@property
def position(self):
return self.lineno, self.offset + 1
@position.setter
def position(self, new_pos):
self.lineno, column = new_pos
self.offset = column - 1
cdef object _ParseError = ParseError
class XMLSyntaxError(ParseError):
"""Syntax error while parsing an XML document.
"""
cdef class ParserError(LxmlError):
"""Internal lxml parser error.
"""
@cython.final
@cython.internal
cdef class _ParserDictionaryContext:
# Global parser context to share the string dictionary.
#
# This class is a delegate singleton!
#
# It creates _ParserDictionaryContext objects for each thread to keep thread state,
# but those must never be used directly. Always stick to using the static
# __GLOBAL_PARSER_CONTEXT as defined below the class.
#
cdef tree.xmlDict* _c_dict
cdef _BaseParser _default_parser
cdef list _implied_parser_contexts
def __cinit__(self):
self._c_dict = NULL
self._implied_parser_contexts = []
def __dealloc__(self):
if self._c_dict is not NULL:
xmlparser.xmlDictFree(self._c_dict)
cdef void initMainParserContext(self):
u"""Put the global context into the thread dictionary of the main
thread. To be called once and only in the main thread."""
thread_dict = python.PyThreadState_GetDict()
if thread_dict is not NULL:
(<dict>thread_dict)[u"_ParserDictionaryContext"] = self
cdef _ParserDictionaryContext _findThreadParserContext(self):
u"Find (or create) the _ParserDictionaryContext object for the current thread"
cdef _ParserDictionaryContext context
thread_dict = python.PyThreadState_GetDict()
if thread_dict is NULL:
return self
d = <dict>thread_dict
result = python.PyDict_GetItem(d, u"_ParserDictionaryContext")
if result is not NULL:
return <object>result
context = <_ParserDictionaryContext>_ParserDictionaryContext.__new__(_ParserDictionaryContext)
d[u"_ParserDictionaryContext"] = context
return context
cdef void setDefaultParser(self, _BaseParser parser):
u"Set the default parser for the current thread"
cdef _ParserDictionaryContext context
context = self._findThreadParserContext()
context._default_parser = parser
cdef _BaseParser getDefaultParser(self):
u"Return (or create) the default parser of the current thread"
cdef _ParserDictionaryContext context
context = self._findThreadParserContext()
if context._default_parser is None:
if self._default_parser is None:
self._default_parser = __DEFAULT_XML_PARSER._copy()
if context is not self:
context._default_parser = self._default_parser._copy()
return context._default_parser
cdef tree.xmlDict* _getThreadDict(self, tree.xmlDict* default):
u"Return the thread-local dict or create a new one if necessary."
cdef _ParserDictionaryContext context
context = self._findThreadParserContext()
if context._c_dict is NULL:
# thread dict not yet set up => use default or create a new one
if default is not NULL:
context._c_dict = default
xmlparser.xmlDictReference(default)
return default
if self._c_dict is NULL:
self._c_dict = xmlparser.xmlDictCreate()
if context is not self:
context._c_dict = xmlparser.xmlDictCreateSub(self._c_dict)
return context._c_dict
cdef void initThreadDictRef(self, tree.xmlDict** c_dict_ref):
c_dict = c_dict_ref[0]
c_thread_dict = self._getThreadDict(c_dict)
if c_dict is c_thread_dict:
return
if c_dict is not NULL:
xmlparser.xmlDictFree(c_dict)
c_dict_ref[0] = c_thread_dict
xmlparser.xmlDictReference(c_thread_dict)
cdef void initParserDict(self, xmlparser.xmlParserCtxt* pctxt):
u"Assure we always use the same string dictionary."
self.initThreadDictRef(&pctxt.dict)
pctxt.dictNames = 1
cdef void initXPathParserDict(self, xpath.xmlXPathContext* pctxt):
u"Assure we always use the same string dictionary."
self.initThreadDictRef(&pctxt.dict)
cdef void initDocDict(self, xmlDoc* result):
u"Store dict of last object parsed if no shared dict yet"
# XXX We also free the result dict here if there already was one.
# This case should only occur for new documents with empty dicts,
# otherwise we'd free data that's in use => segfault
self.initThreadDictRef(&result.dict)
cdef _ParserContext findImpliedContext(self):
u"""Return any current implied xml parser context for the current
thread. This is used when the resolver functions are called
with an xmlParserCtxt that was generated from within libxml2
(i.e. without a _ParserContext) - which happens when parsing
schema and xinclude external references."""
cdef _ParserDictionaryContext context
cdef _ParserContext implied_context
# see if we have a current implied parser
context = self._findThreadParserContext()
if context._implied_parser_contexts:
implied_context = context._implied_parser_contexts[-1]
return implied_context
return None
cdef void pushImpliedContextFromParser(self, _BaseParser parser):
u"Push a new implied context object taken from the parser."
if parser is not None:
self.pushImpliedContext(parser._getParserContext())
else:
self.pushImpliedContext(None)
cdef void pushImpliedContext(self, _ParserContext parser_context):
u"Push a new implied context object."
cdef _ParserDictionaryContext context
context = self._findThreadParserContext()
context._implied_parser_contexts.append(parser_context)
cdef void popImpliedContext(self):
u"Pop the current implied context object."
cdef _ParserDictionaryContext context
context = self._findThreadParserContext()
context._implied_parser_contexts.pop()
cdef _ParserDictionaryContext __GLOBAL_PARSER_CONTEXT = _ParserDictionaryContext()
__GLOBAL_PARSER_CONTEXT.initMainParserContext()
############################################################
## support for Python unicode I/O
############################################################
# name of Python unicode encoding as known to libxml2
cdef const_char* _UNICODE_ENCODING = NULL
cdef int _setupPythonUnicode() except -1:
u"""Sets _UNICODE_ENCODING to the internal encoding name of Python unicode
strings if libxml2 supports reading native Python unicode. This depends
on iconv and the local Python installation, so we simply check if we find
a matching encoding handler.
"""
cdef tree.xmlCharEncodingHandler* enchandler
cdef Py_ssize_t l
cdef const_char* enc
cdef Py_UNICODE *uchars = [c'<', c't', c'e', c's', c't', c'/', c'>']
cdef const_xmlChar* buffer = <const_xmlChar*>uchars
# apparently, libxml2 can't detect UTF-16 on some systems
if (buffer[0] == c'<' and buffer[1] == c'\0' and
buffer[2] == c't' and buffer[3] == c'\0'):
enc = "UTF-16LE"
elif (buffer[0] == c'\0' and buffer[1] == c'<' and
buffer[2] == c'\0' and buffer[3] == c't'):
enc = "UTF-16BE"
else:
# let libxml2 give it a try
enc = _findEncodingName(buffer, sizeof(Py_UNICODE) * 7)
if enc is NULL:
# not my fault, it's YOUR broken system :)
return 0
enchandler = tree.xmlFindCharEncodingHandler(enc)
if enchandler is not NULL:
global _UNICODE_ENCODING
tree.xmlCharEncCloseFunc(enchandler)
_UNICODE_ENCODING = enc
return 0
cdef const_char* _findEncodingName(const_xmlChar* buffer, int size):
u"Work around bug in libxml2: find iconv name of encoding on our own."
cdef tree.xmlCharEncoding enc
enc = tree.xmlDetectCharEncoding(buffer, size)
if enc == tree.XML_CHAR_ENCODING_UTF16LE:
if size >= 4 and (buffer[0] == <const_xmlChar>'\xFF' and
buffer[1] == <const_xmlChar>'\xFE' and
buffer[2] == 0 and buffer[3] == 0):
return "UTF-32LE" # according to BOM
else:
return "UTF-16LE"
elif enc == tree.XML_CHAR_ENCODING_UTF16BE:
return "UTF-16BE"
elif enc == tree.XML_CHAR_ENCODING_UCS4LE:
return "UCS-4LE"
elif enc == tree.XML_CHAR_ENCODING_UCS4BE:
return "UCS-4BE"
elif enc == tree.XML_CHAR_ENCODING_NONE:
return NULL
else:
# returns a constant char*, no need to free it
return tree.xmlGetCharEncodingName(enc)
_setupPythonUnicode()
############################################################
## support for file-like objects
############################################################
@cython.final
@cython.internal
cdef class _FileReaderContext:
cdef object _filelike
cdef object _encoding
cdef object _url
cdef object _bytes
cdef _ExceptionContext _exc_context
cdef Py_ssize_t _bytes_read
cdef char* _c_url
cdef bint _close_file_after_read
def __cinit__(self, filelike, exc_context not None, url, encoding=None, bint close_file=False):
self._exc_context = exc_context
self._filelike = filelike
self._close_file_after_read = close_file
self._encoding = encoding
if url is None:
self._c_url = NULL
else:
url = _encodeFilename(url)
self._c_url = _cstr(url)
self._url = url
self._bytes = b''
self._bytes_read = 0
cdef _close_file(self):
if self._filelike is None or not self._close_file_after_read:
return
try:
close = self._filelike.close
except AttributeError:
close = None
finally:
self._filelike = None
if close is not None:
close()
cdef xmlparser.xmlParserInputBuffer* _createParserInputBuffer(self):
cdef stdio.FILE* c_stream
cdef xmlparser.xmlParserInputBuffer* c_buffer
c_buffer = xmlparser.xmlAllocParserInputBuffer(0)
c_stream = python.PyFile_AsFile(self._filelike)
if c_stream is NULL:
c_buffer.readcallback = _readFilelikeParser
c_buffer.context = <python.PyObject*>self
else:
c_buffer.readcallback = _readFileParser
c_buffer.context = c_stream
return c_buffer
cdef xmlparser.xmlParserInput* _createParserInput(
self, xmlparser.xmlParserCtxt* ctxt):
cdef xmlparser.xmlParserInputBuffer* c_buffer
c_buffer = self._createParserInputBuffer()
return xmlparser.xmlNewIOInputStream(ctxt, c_buffer, 0)
cdef tree.xmlDtd* _readDtd(self):
cdef xmlparser.xmlParserInputBuffer* c_buffer
c_buffer = self._createParserInputBuffer()
with nogil:
return xmlparser.xmlIOParseDTD(NULL, c_buffer, 0)
cdef xmlDoc* _readDoc(self, xmlparser.xmlParserCtxt* ctxt, int options):
cdef xmlDoc* result
cdef char* c_encoding
cdef stdio.FILE* c_stream
cdef xmlparser.xmlInputReadCallback c_read_callback
cdef xmlparser.xmlInputCloseCallback c_close_callback
cdef void* c_callback_context
if self._encoding is None:
c_encoding = NULL
else:
c_encoding = _cstr(self._encoding)
c_stream = python.PyFile_AsFile(self._filelike)
if c_stream is NULL:
c_read_callback = _readFilelikeParser
c_callback_context = <python.PyObject*>self
else:
c_read_callback = _readFileParser
c_callback_context = c_stream
orig_options = ctxt.options
with nogil:
if ctxt.html:
result = htmlparser.htmlCtxtReadIO(
ctxt, c_read_callback, NULL, c_callback_context,
self._c_url, c_encoding, options)
if result is not NULL:
if _fixHtmlDictNames(ctxt.dict, result) < 0:
tree.xmlFreeDoc(result)
result = NULL
else:
result = xmlparser.xmlCtxtReadIO(
ctxt, c_read_callback, NULL, c_callback_context,
self._c_url, c_encoding, options)
ctxt.options = orig_options # work around libxml2 problem
try:
self._close_file()
except:
self._exc_context._store_raised()
finally:
return result # swallow any exceptions
cdef int copyToBuffer(self, char* c_buffer, int c_requested):
cdef int c_byte_count = 0
cdef char* c_start
cdef Py_ssize_t byte_count, remaining
if self._bytes_read < 0:
return 0
try:
byte_count = python.PyBytes_GET_SIZE(self._bytes)
remaining = byte_count - self._bytes_read
while c_requested > remaining:
c_start = _cstr(self._bytes) + self._bytes_read
cstring_h.memcpy(c_buffer, c_start, remaining)
c_byte_count += remaining
c_buffer += remaining
c_requested -= remaining
self._bytes = self._filelike.read(c_requested)
if not isinstance(self._bytes, bytes):
if isinstance(self._bytes, unicode):
if self._encoding is None:
self._bytes = (<unicode>self._bytes).encode('utf8')
else:
self._bytes = python.PyUnicode_AsEncodedString(
self._bytes, _cstr(self._encoding), NULL)
else:
self._close_file()
raise TypeError, \
u"reading from file-like objects must return byte strings or unicode strings"
remaining = python.PyBytes_GET_SIZE(self._bytes)
if remaining == 0:
self._bytes_read = -1
self._close_file()
return c_byte_count
self._bytes_read = 0
if c_requested > 0:
c_start = _cstr(self._bytes) + self._bytes_read
cstring_h.memcpy(c_buffer, c_start, c_requested)
c_byte_count += c_requested
self._bytes_read += c_requested
except:
c_byte_count = -1
self._exc_context._store_raised()
try:
self._close_file()
except:
self._exc_context._store_raised()
finally:
return c_byte_count # swallow any exceptions
cdef int _readFilelikeParser(void* ctxt, char* c_buffer, int c_size) with gil:
return (<_FileReaderContext>ctxt).copyToBuffer(c_buffer, c_size)
cdef int _readFileParser(void* ctxt, char* c_buffer, int c_size) nogil:
return stdio.fread(c_buffer, 1, c_size, <stdio.FILE*>ctxt)
############################################################
## support for custom document loaders
############################################################
cdef xmlparser.xmlParserInput* _local_resolver(const_char* c_url, const_char* c_pubid,
xmlparser.xmlParserCtxt* c_context) with gil:
cdef _ResolverContext context
cdef xmlparser.xmlParserInput* c_input
cdef _InputDocument doc_ref
cdef _FileReaderContext file_context
# if there is no _ParserContext associated with the xmlParserCtxt
# passed, check to see if the thread state object has an implied
# context.
if c_context._private is not NULL:
context = <_ResolverContext>c_context._private
else:
context = __GLOBAL_PARSER_CONTEXT.findImpliedContext()
if context is None:
if __DEFAULT_ENTITY_LOADER is NULL:
return NULL
with nogil:
# free the GIL as we might do serious I/O here (e.g. HTTP)
c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
return c_input
try:
if c_url is NULL:
url = None
else:
# parsing a related document (DTD etc.) => UTF-8 encoded URL?
url = _decodeFilename(<const_xmlChar*>c_url)
if c_pubid is NULL:
pubid = None
else:
pubid = funicode(<const_xmlChar*>c_pubid) # always UTF-8
doc_ref = context._resolvers.resolve(url, pubid, context)
except:
context._store_raised()
return NULL
if doc_ref is not None:
if doc_ref._type == PARSER_DATA_STRING:
data = doc_ref._data_bytes
filename = doc_ref._filename
if not filename:
filename = None
elif not isinstance(filename, bytes):
# most likely a text URL
filename = filename.encode('utf8')
if not isinstance(filename, bytes):
filename = None
c_input = xmlparser.xmlNewInputStream(c_context)
if c_input is not NULL:
if filename is not None:
c_input.filename = <char *>tree.xmlStrdup(_xcstr(filename))
c_input.base = _xcstr(data)
c_input.length = python.PyBytes_GET_SIZE(data)
c_input.cur = c_input.base
c_input.end = c_input.base + c_input.length
elif doc_ref._type == PARSER_DATA_FILENAME:
data = None
c_filename = _cstr(doc_ref._filename)
with nogil:
# free the GIL as we might do serious I/O here
c_input = xmlparser.xmlNewInputFromFile(
c_context, c_filename)
elif doc_ref._type == PARSER_DATA_FILE:
file_context = _FileReaderContext(doc_ref._file, context, url,
None, doc_ref._close_file)
c_input = file_context._createParserInput(c_context)
data = file_context
else:
data = None
c_input = NULL
if data is not None:
context._storage.add(data)
if c_input is not NULL:
return c_input
if __DEFAULT_ENTITY_LOADER is NULL:
return NULL
with nogil:
# free the GIL as we might do serious I/O here (e.g. HTTP)
c_input = __DEFAULT_ENTITY_LOADER(c_url, c_pubid, c_context)
return c_input
cdef xmlparser.xmlExternalEntityLoader __DEFAULT_ENTITY_LOADER
__DEFAULT_ENTITY_LOADER = xmlparser.xmlGetExternalEntityLoader()
xmlparser.xmlSetExternalEntityLoader(<xmlparser.xmlExternalEntityLoader>_local_resolver)
############################################################
## Parsers
############################################################
@cython.no_gc_clear # May have to call "self._validator.disconnect()" on dealloc.
@cython.internal
cdef class _ParserContext(_ResolverContext):
cdef _ErrorLog _error_log
cdef _ParserSchemaValidationContext _validator
cdef xmlparser.xmlParserCtxt* _c_ctxt
cdef python.PyThread_type_lock _lock
cdef _Document _doc
cdef bint _collect_ids
def __cinit__(self):
self._c_ctxt = NULL
self._collect_ids = True
if not config.ENABLE_THREADING:
self._lock = NULL
else:
self._lock = python.PyThread_allocate_lock()
self._error_log = _ErrorLog()
def __dealloc__(self):
if config.ENABLE_THREADING and self._lock is not NULL:
python.PyThread_free_lock(self._lock)
self._lock = NULL
if self._c_ctxt is not NULL:
if <void*>self._validator is not NULL and self._validator is not None:
# If the parser was not closed correctly (e.g. interrupted iterparse()),
# and the schema validator wasn't freed and cleaned up yet, the libxml2 SAX
# validator plug might still be in place, which will make xmlFreeParserCtxt()
# crash when trying to xmlFree() a static SAX handler.
# Thus, make sure we disconnect the handler interceptor here at the latest.
self._validator.disconnect()
xmlparser.xmlFreeParserCtxt(self._c_ctxt)
cdef _ParserContext _copy(self):
cdef _ParserContext context
context = self.__class__()
context._collect_ids = self._collect_ids
context._validator = self._validator.copy()
_initParserContext(context, self._resolvers._copy(), NULL)
return context
cdef void _initParserContext(self, xmlparser.xmlParserCtxt* c_ctxt):
self._c_ctxt = c_ctxt
c_ctxt._private = <void*>self
cdef void _resetParserContext(self):
if self._c_ctxt is not NULL:
if self._c_ctxt.html:
htmlparser.htmlCtxtReset(self._c_ctxt)
self._c_ctxt.disableSAX = 0 # work around bug in libxml2
else:
xmlparser.xmlClearParserCtxt(self._c_ctxt)
cdef int prepare(self) except -1:
cdef int result
if config.ENABLE_THREADING and self._lock is not NULL:
with nogil:
result = python.PyThread_acquire_lock(
self._lock, python.WAIT_LOCK)
if result == 0:
raise ParserError, u"parser locking failed"
self._error_log.clear()
self._doc = None
self._c_ctxt.sax.serror = _receiveParserError
if self._validator is not None:
self._validator.connect(self._c_ctxt, self._error_log)
return 0
cdef int cleanup(self) except -1:
if self._validator is not None:
self._validator.disconnect()
self._resetParserContext()
self.clear()
self._doc = None
self._c_ctxt.sax.serror = NULL
if config.ENABLE_THREADING and self._lock is not NULL:
python.PyThread_release_lock(self._lock)
return 0
cdef object _handleParseResult(self, _BaseParser parser,
xmlDoc* result, filename):
c_doc = self._handleParseResultDoc(parser, result, filename)
if self._doc is not None and self._doc._c_doc is c_doc:
return self._doc
else:
return _documentFactory(c_doc, parser)
cdef xmlDoc* _handleParseResultDoc(self, _BaseParser parser,
xmlDoc* result, filename) except NULL:
recover = parser._parse_options & xmlparser.XML_PARSE_RECOVER
return _handleParseResult(self, self._c_ctxt, result,
filename, recover,
free_doc=self._doc is None)
cdef _initParserContext(_ParserContext context,
_ResolverRegistry resolvers,
xmlparser.xmlParserCtxt* c_ctxt):
_initResolverContext(context, resolvers)
if c_ctxt is not NULL:
context._initParserContext(c_ctxt)
cdef void _forwardParserError(xmlparser.xmlParserCtxt* _parser_context, xmlerror.xmlError* error) with gil:
(<_ParserContext>_parser_context._private)._error_log._receive(error)
cdef void _receiveParserError(void* c_context, xmlerror.xmlError* error) nogil:
if __DEBUG:
if c_context is NULL or (<xmlparser.xmlParserCtxt*>c_context)._private is NULL:
_forwardError(NULL, error)
else:
_forwardParserError(<xmlparser.xmlParserCtxt*>c_context, error)
cdef int _raiseParseError(xmlparser.xmlParserCtxt* ctxt, filename,
_ErrorLog error_log) except -1:
if filename is not None and \
ctxt.lastError.domain == xmlerror.XML_FROM_IO:
if isinstance(filename, bytes):
filename = _decodeFilenameWithLength(
<bytes>filename, len(<bytes>filename))
if ctxt.lastError.message is not NULL:
try:
message = ctxt.lastError.message.decode('utf-8')
except UnicodeDecodeError:
# the filename may be in there => play it safe
message = ctxt.lastError.message.decode('iso8859-1')
message = f"Error reading file '{filename}': {message.strip()}"
else:
message = f"Error reading '{filename}'"
raise IOError, message
elif error_log:
raise error_log._buildParseException(
XMLSyntaxError, u"Document is not well formed")
elif ctxt.lastError.message is not NULL:
message = ctxt.lastError.message.strip()
code = ctxt.lastError.code
line = ctxt.lastError.line
column = ctxt.lastError.int2
if ctxt.lastError.line > 0:
message = f"line {line}: {message}"
raise XMLSyntaxError(message, code, line, column, filename)
else:
raise XMLSyntaxError(None, xmlerror.XML_ERR_INTERNAL_ERROR, 0, 0,
filename)
cdef xmlDoc* _handleParseResult(_ParserContext context,
xmlparser.xmlParserCtxt* c_ctxt,
xmlDoc* result, filename,
bint recover, bint free_doc) except NULL:
cdef bint well_formed
if result is not NULL:
__GLOBAL_PARSER_CONTEXT.initDocDict(result)
if c_ctxt.myDoc is not NULL:
if c_ctxt.myDoc is not result:
__GLOBAL_PARSER_CONTEXT.initDocDict(c_ctxt.myDoc)
tree.xmlFreeDoc(c_ctxt.myDoc)
c_ctxt.myDoc = NULL
if result is not NULL:
if (context._validator is not None and
not context._validator.isvalid()):
well_formed = 0 # actually not 'valid', but anyway ...
elif (not c_ctxt.wellFormed and not c_ctxt.html and
c_ctxt.charset == tree.XML_CHAR_ENCODING_8859_1 and
[1 for error in context._error_log
if error.type == ErrorTypes.ERR_INVALID_CHAR]):
# An encoding error occurred and libxml2 switched from UTF-8
# input to (undecoded) Latin-1, at some arbitrary point in the
# document. Better raise an error than allowing for a broken
# tree with mixed encodings.
well_formed = 0
elif recover or (c_ctxt.wellFormed and
c_ctxt.lastError.level < xmlerror.XML_ERR_ERROR):
well_formed = 1
elif not c_ctxt.replaceEntities and not c_ctxt.validate \
and context is not None:
# in this mode, we ignore errors about undefined entities
for error in context._error_log.filter_from_errors():
if error.type != ErrorTypes.WAR_UNDECLARED_ENTITY and \
error.type != ErrorTypes.ERR_UNDECLARED_ENTITY:
well_formed = 0
break
else:
well_formed = 1
else:
well_formed = 0
if not well_formed:
if free_doc:
tree.xmlFreeDoc(result)
result = NULL
if context is not None and context._has_raised():
if result is not NULL:
if free_doc:
tree.xmlFreeDoc(result)
result = NULL
context._raise_if_stored()
if result is NULL:
if context is not None:
_raiseParseError(c_ctxt, filename, context._error_log)
else:
_raiseParseError(c_ctxt, filename, None)
else:
if result.URL is NULL and filename is not None:
result.URL = tree.xmlStrdup(_xcstr(filename))
if result.encoding is NULL:
result.encoding = tree.xmlStrdup(<unsigned char*>"UTF-8")
if context._validator is not None and \
context._validator._add_default_attributes:
# we currently need to do this here as libxml2 does not
# support inserting default attributes during parse-time
# validation
context._validator.inject_default_attributes(result)
return result
cdef int _fixHtmlDictNames(tree.xmlDict* c_dict, xmlDoc* c_doc) nogil:
cdef xmlNode* c_node
if c_doc is NULL:
return 0
c_node = c_doc.children
tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
if c_node.type == tree.XML_ELEMENT_NODE:
if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
return -1
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
return 0
cdef int _fixHtmlDictSubtreeNames(tree.xmlDict* c_dict, xmlDoc* c_doc,
xmlNode* c_start_node) nogil:
"""
Move names to the dict, iterating in document order, starting at
c_start_node. This is used in incremental parsing after each chunk.
"""
cdef xmlNode* c_node
if not c_doc:
return 0
if not c_start_node:
return _fixHtmlDictNames(c_dict, c_doc)
c_node = c_start_node
tree.BEGIN_FOR_EACH_ELEMENT_FROM(<xmlNode*>c_doc, c_node, 1)
if c_node.type == tree.XML_ELEMENT_NODE:
if _fixHtmlDictNodeNames(c_dict, c_node) < 0:
return -1
tree.END_FOR_EACH_ELEMENT_FROM(c_node)
return 0
cdef inline int _fixHtmlDictNodeNames(tree.xmlDict* c_dict,
xmlNode* c_node) nogil:
cdef xmlNode* c_attr
c_name = tree.xmlDictLookup(c_dict, c_node.name, -1)
if c_name is NULL:
return -1
if c_name is not c_node.name:
tree.xmlFree(<char*>c_node.name)
c_node.name = c_name
c_attr = <xmlNode*>c_node.properties
while c_attr is not NULL:
c_name = tree.xmlDictLookup(c_dict, c_attr.name, -1)
if c_name is NULL:
return -1
if c_name is not c_attr.name:
tree.xmlFree(<char*>c_attr.name)
c_attr.name = c_name
c_attr = c_attr.next
return 0
@cython.internal
cdef class _BaseParser:
cdef ElementClassLookup _class_lookup
cdef _ResolverRegistry _resolvers
cdef _ParserContext _parser_context
cdef _ParserContext _push_parser_context
cdef int _parse_options
cdef bint _for_html
cdef bint _remove_comments
cdef bint _remove_pis
cdef bint _strip_cdata
cdef bint _collect_ids
cdef XMLSchema _schema
cdef bytes _filename
cdef readonly object target
cdef object _default_encoding
cdef tuple _events_to_collect # (event_types, tag)
def __init__(self, int parse_options, bint for_html, XMLSchema schema,
remove_comments, remove_pis, strip_cdata, collect_ids,
target, encoding):
cdef tree.xmlCharEncodingHandler* enchandler
cdef int c_encoding
if not isinstance(self, (XMLParser, HTMLParser)):
raise TypeError, u"This class cannot be instantiated"
self._parse_options = parse_options
self.target = target
self._for_html = for_html
self._remove_comments = remove_comments
self._remove_pis = remove_pis
self._strip_cdata = strip_cdata
self._collect_ids = collect_ids
self._schema = schema
self._resolvers = _ResolverRegistry()
if encoding is None:
self._default_encoding = None
else:
encoding = _utf8(encoding)
enchandler = tree.xmlFindCharEncodingHandler(_cstr(encoding))
if enchandler is NULL:
raise LookupError, f"unknown encoding: '{encoding}'"
tree.xmlCharEncCloseFunc(enchandler)
self._default_encoding = encoding
cdef _setBaseURL(self, base_url):
self._filename = _encodeFilename(base_url)
cdef _collectEvents(self, event_types, tag):
if event_types is None:
event_types = ()
else:
event_types = tuple(set(event_types))
_buildParseEventFilter(event_types) # purely for validation
self._events_to_collect = (event_types, tag)
cdef _ParserContext _getParserContext(self):
cdef xmlparser.xmlParserCtxt* pctxt
if self._parser_context is None:
self._parser_context = self._createContext(self.target, None)
self._parser_context._collect_ids = self._collect_ids
if self._schema is not None:
self._parser_context._validator = \
self._schema._newSaxValidator(
self._parse_options & xmlparser.XML_PARSE_DTDATTR)
pctxt = self._newParserCtxt()
_initParserContext(self._parser_context, self._resolvers, pctxt)
self._configureSaxContext(pctxt)
return self._parser_context
cdef _ParserContext _getPushParserContext(self):
cdef xmlparser.xmlParserCtxt* pctxt
if self._push_parser_context is None:
self._push_parser_context = self._createContext(
self.target, self._events_to_collect)
self._push_parser_context._collect_ids = self._collect_ids
if self._schema is not None:
self._push_parser_context._validator = \
self._schema._newSaxValidator(
self._parse_options & xmlparser.XML_PARSE_DTDATTR)
pctxt = self._newPushParserCtxt()
_initParserContext(
self._push_parser_context, self._resolvers, pctxt)
self._configureSaxContext(pctxt)
return self._push_parser_context
cdef _ParserContext _createContext(self, target, events_to_collect):
cdef _SaxParserContext sax_context
if target is not None:
sax_context = _TargetParserContext(self)
(<_TargetParserContext>sax_context)._setTarget(target)
elif events_to_collect:
sax_context = _SaxParserContext(self)
else:
# nothing special to configure
return _ParserContext()
if events_to_collect:
events, tag = events_to_collect
sax_context._setEventFilter(events, tag)
return sax_context
@cython.final
cdef int _configureSaxContext(self, xmlparser.xmlParserCtxt* pctxt) except -1:
if self._remove_comments:
pctxt.sax.comment = NULL
if self._remove_pis:
pctxt.sax.processingInstruction = NULL
if self._strip_cdata:
# hard switch-off for CDATA nodes => makes them plain text
pctxt.sax.cdataBlock = NULL
cdef int _registerHtmlErrorHandler(self, xmlparser.xmlParserCtxt* c_ctxt) except -1:
cdef xmlparser.xmlSAXHandler* sax = c_ctxt.sax
if sax is not NULL and sax.initialized and sax.initialized != xmlparser.XML_SAX2_MAGIC:
# need to extend SAX1 context to SAX2 to get proper error reports
if <xmlparser.xmlSAXHandlerV1*>sax is &htmlparser.htmlDefaultSAXHandler:
sax = <xmlparser.xmlSAXHandler*> tree.xmlMalloc(sizeof(xmlparser.xmlSAXHandler))
if sax is NULL:
raise MemoryError()
cstring_h.memcpy(sax, &htmlparser.htmlDefaultSAXHandler,
sizeof(htmlparser.htmlDefaultSAXHandler))
c_ctxt.sax = sax
sax.initialized = xmlparser.XML_SAX2_MAGIC
sax.serror = _receiveParserError
sax.startElementNs = NULL
sax.endElementNs = NULL
sax._private = NULL
return 0
cdef xmlparser.xmlParserCtxt* _newParserCtxt(self) except NULL:
cdef xmlparser.xmlParserCtxt* c_ctxt
if self._for_html:
c_ctxt = htmlparser.htmlCreateMemoryParserCtxt('dummy', 5)
if c_ctxt is not NULL:
self._registerHtmlErrorHandler(c_ctxt)
else:
c_ctxt = xmlparser.xmlNewParserCtxt()
if c_ctxt is NULL:
raise MemoryError
c_ctxt.sax.startDocument = _initSaxDocument
return c_ctxt
cdef xmlparser.xmlParserCtxt* _newPushParserCtxt(self) except NULL:
cdef xmlparser.xmlParserCtxt* c_ctxt
cdef char* c_filename = _cstr(self._filename) if self._filename is not None else NULL
if self._for_html:
c_ctxt = htmlparser.htmlCreatePushParserCtxt(
NULL, NULL, NULL, 0, c_filename, tree.XML_CHAR_ENCODING_NONE)
if c_ctxt is not NULL:
self._registerHtmlErrorHandler(c_ctxt)
htmlparser.htmlCtxtUseOptions(c_ctxt, self._parse_options)
else:
c_ctxt = xmlparser.xmlCreatePushParserCtxt(
NULL, NULL, NULL, 0, c_filename)
if c_ctxt is not NULL:
xmlparser.xmlCtxtUseOptions(c_ctxt, self._parse_options)
if c_ctxt is NULL:
raise MemoryError()
c_ctxt.sax.startDocument = _initSaxDocument
return c_ctxt
@property
def error_log(self):
"""The error log of the last parser run.
"""
cdef _ParserContext context
context = self._getParserContext()
return context._error_log.copy()
@property
def resolvers(self):
"""The custom resolver registry of this parser."""
return self._resolvers
@property
def version(self):
"""The version of the underlying XML parser."""
return u"libxml2 %d.%d.%d" % LIBXML_VERSION
def setElementClassLookup(self, ElementClassLookup lookup = None):
u":deprecated: use ``parser.set_element_class_lookup(lookup)`` instead."
self.set_element_class_lookup(lookup)
def set_element_class_lookup(self, ElementClassLookup lookup = None):
u"""set_element_class_lookup(self, lookup = None)
Set a lookup scheme for element classes generated from this parser.
Reset it by passing None or nothing.
"""
self._class_lookup = lookup
cdef _BaseParser _copy(self):
u"Create a new parser with the same configuration."
cdef _BaseParser parser
parser = self.__class__()
parser._parse_options = self._parse_options
parser._for_html = self._for_html
parser._remove_comments = self._remove_comments
parser._remove_pis = self._remove_pis
parser._strip_cdata = self._strip_cdata
parser._filename = self._filename
parser._resolvers = self._resolvers
parser.target = self.target
parser._class_lookup = self._class_lookup
parser._default_encoding = self._default_encoding
parser._schema = self._schema
parser._events_to_collect = self._events_to_collect
return parser
def copy(self):
u"""copy(self)
Create a new parser with the same configuration.
"""
return self._copy()
def makeelement(self, _tag, attrib=None, nsmap=None, **_extra):
u"""makeelement(self, _tag, attrib=None, nsmap=None, **_extra)