| 1 |
from pypy.interpreter.baseobjspace import W_Root |
| 2 |
from pypy.interpreter.typedef import TypeDef, GetSetProperty |
| 3 |
from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault |
| 4 |
from pypy.interpreter.error import OperationError, oefmt |
| 5 |
from rpython.rlib import rgc, jit, rutf8 |
| 6 |
from rpython.rlib.objectmodel import specialize |
| 7 |
from rpython.rtyper.lltypesystem import rffi, lltype |
| 8 |
from rpython.rtyper.tool import rffi_platform |
| 9 |
from rpython.translator.tool.cbuild import ExternalCompilationInfo |
| 10 |
from rpython.translator.platform import platform |
| 11 |
|
| 12 |
import sys |
| 13 |
import weakref |
| 14 |
import py |
| 15 |
import math |
| 16 |
|
| 17 |
if sys.platform == "win32": |
| 18 |
pre_include_bits = ["#define XML_STATIC"] |
| 19 |
else: |
| 20 |
pre_include_bits = [] |
| 21 |
|
| 22 |
eci = ExternalCompilationInfo( |
| •23 |
libraries=['expat'], |
| 24 |
library_dirs=platform.preprocess_library_dirs([]), |
| 25 |
includes=['expat_config.h', 'expat.h'], |
| 26 |
include_dirs=platform.preprocess_include_dirs([]), |
| 27 |
pre_include_bits = pre_include_bits, |
| •28 |
) |
| 29 |
eci = rffi_platform.configure_external_library( |
| 30 |
'expat', eci, |
| 31 |
[dict(prefix='expat-', |
| 32 |
include_dir='lib', library_dir='win32/bin/release'), |
| 33 |
]) |
| 34 |
|
| 35 |
XML_Content_Ptr = lltype.Ptr(lltype.ForwardReference()) |
| 36 |
XML_Parser = rffi.COpaquePtr(typedef='XML_Parser') |
| 37 |
|
| 38 |
xml_error_list = [ |
| 39 |
"XML_ERROR_NO_MEMORY", |
| 40 |
"XML_ERROR_SYNTAX", |
| 41 |
"XML_ERROR_NO_ELEMENTS", |
| 42 |
"XML_ERROR_INVALID_TOKEN", |
| 43 |
"XML_ERROR_UNCLOSED_TOKEN", |
| 44 |
"XML_ERROR_PARTIAL_CHAR", |
| 45 |
"XML_ERROR_TAG_MISMATCH", |
| 46 |
"XML_ERROR_DUPLICATE_ATTRIBUTE", |
| 47 |
"XML_ERROR_JUNK_AFTER_DOC_ELEMENT", |
| 48 |
"XML_ERROR_PARAM_ENTITY_REF", |
| 49 |
"XML_ERROR_UNDEFINED_ENTITY", |
| 50 |
"XML_ERROR_RECURSIVE_ENTITY_REF", |
| 51 |
"XML_ERROR_ASYNC_ENTITY", |
| 52 |
"XML_ERROR_BAD_CHAR_REF", |
| 53 |
"XML_ERROR_BINARY_ENTITY_REF", |
| 54 |
"XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", |
| 55 |
"XML_ERROR_MISPLACED_XML_PI", |
| 56 |
"XML_ERROR_UNKNOWN_ENCODING", |
| 57 |
"XML_ERROR_INCORRECT_ENCODING", |
| 58 |
"XML_ERROR_UNCLOSED_CDATA_SECTION", |
| 59 |
"XML_ERROR_EXTERNAL_ENTITY_HANDLING", |
| 60 |
"XML_ERROR_NOT_STANDALONE", |
| 61 |
"XML_ERROR_UNEXPECTED_STATE", |
| 62 |
"XML_ERROR_ENTITY_DECLARED_IN_PE", |
| 63 |
"XML_ERROR_FEATURE_REQUIRES_XML_DTD", |
| 64 |
"XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING", |
| 65 |
|
| 66 |
"XML_ERROR_UNBOUND_PREFIX", |
| 67 |
|
| 68 |
"XML_ERROR_UNDECLARING_PREFIX", |
| 69 |
"XML_ERROR_INCOMPLETE_PE", |
| 70 |
"XML_ERROR_XML_DECL", |
| 71 |
"XML_ERROR_TEXT_DECL", |
| 72 |
"XML_ERROR_PUBLICID", |
| 73 |
"XML_ERROR_SUSPENDED", |
| 74 |
"XML_ERROR_NOT_SUSPENDED", |
| 75 |
"XML_ERROR_ABORTED", |
| 76 |
"XML_ERROR_FINISHED", |
| 77 |
"XML_ERROR_SUSPEND_PE", |
| 78 |
] |
| 79 |
xml_model_list = [ |
| 80 |
"XML_CTYPE_EMPTY", |
| 81 |
"XML_CTYPE_ANY", |
| 82 |
"XML_CTYPE_MIXED", |
| 83 |
"XML_CTYPE_NAME", |
| 84 |
"XML_CTYPE_CHOICE", |
| 85 |
"XML_CTYPE_SEQ", |
| 86 |
"XML_CQUANT_NONE", |
| 87 |
"XML_CQUANT_OPT", |
| 88 |
"XML_CQUANT_REP", |
| 89 |
"XML_CQUANT_PLUS", |
| 90 |
] |
| 91 |
|
| 92 |
class CConfigure: |
| 93 |
_compilation_info_ = eci |
| 94 |
XML_Content = rffi_platform.Struct('XML_Content', [ |
| 95 |
('numchildren', rffi.UINT), |
| 96 |
('children', XML_Content_Ptr), |
| 97 |
('name', rffi.CCHARP), |
| 98 |
('type', rffi.INT), |
| 99 |
('quant', rffi.INT), |
| 100 |
]) |
| 101 |
XML_Encoding = rffi_platform.Struct('XML_Encoding', [ |
| 102 |
('map', rffi.CFixedArray(rffi.INT, 1)), |
| 103 |
('data', rffi.VOIDP), |
| 104 |
('convert', rffi.VOIDP), |
| 105 |
('release', rffi.VOIDP), |
| 106 |
]) |
| 107 |
for name in ['XML_PARAM_ENTITY_PARSING_NEVER', |
| 108 |
'XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE', |
| 109 |
'XML_PARAM_ENTITY_PARSING_ALWAYS']: |
| 110 |
locals()[name] = rffi_platform.ConstantInteger(name) |
| 111 |
XML_MAJOR_VERSION = rffi_platform.ConstantInteger('XML_MAJOR_VERSION') |
| 112 |
XML_MINOR_VERSION = rffi_platform.ConstantInteger('XML_MINOR_VERSION') |
| 113 |
XML_MICRO_VERSION = rffi_platform.ConstantInteger('XML_MICRO_VERSION') |
| 114 |
XML_FALSE = rffi_platform.ConstantInteger('XML_FALSE') |
| 115 |
XML_TRUE = rffi_platform.ConstantInteger('XML_TRUE') |
| 116 |
|
| 117 |
for name in xml_error_list: |
| 118 |
locals()[name] = rffi_platform.ConstantInteger(name) |
| 119 |
for name in xml_model_list: |
| 120 |
locals()[name] = rffi_platform.ConstantInteger(name) |
| 121 |
XML_Parser_SIZE = rffi_platform.SizeOf("XML_Parser") |
| 122 |
|
| 123 |
for k, v in rffi_platform.configure(CConfigure).items(): |
| 124 |
globals()[k] = v |
| 125 |
|
| 126 |
XML_COMBINED_VERSION = 10000*XML_MAJOR_VERSION+100*XML_MINOR_VERSION+XML_MICRO_VERSION |
| 127 |
|
| 128 |
XML_Content_Ptr.TO.become(rffi.CArray(XML_Content)) |
| 129 |
XML_Encoding_Ptr = lltype.Ptr(XML_Encoding) |
| 130 |
|
| 131 |
|
| 132 |
def expat_external(*a, **kw): |
| 133 |
kw['compilation_info'] = eci |
| 134 |
return rffi.llexternal(*a, **kw) |
| 135 |
|
| 136 |
INTERNED_CCHARP = "INTERNED" |
| 137 |
CONST_CCHARPP = lltype.Ptr(lltype.Array(rffi.CONST_CCHARP, hints={'nolength': True})) |
| 138 |
|
| 139 |
HANDLERS = dict( |
| 140 |
StartElementHandler = [INTERNED_CCHARP, CONST_CCHARPP], |
| 141 |
EndElementHandler = [INTERNED_CCHARP], |
| 142 |
ProcessingInstructionHandler = [INTERNED_CCHARP, INTERNED_CCHARP], |
| 143 |
CharacterDataHandler = [rffi.CCHARP, rffi.INT_real], |
| 144 |
UnparsedEntityDeclHandler = [INTERNED_CCHARP] * 5, |
| 145 |
NotationDeclHandler = [INTERNED_CCHARP] * 4, |
| 146 |
StartNamespaceDeclHandler = [INTERNED_CCHARP, INTERNED_CCHARP], |
| 147 |
EndNamespaceDeclHandler = [INTERNED_CCHARP], |
| 148 |
CommentHandler = [INTERNED_CCHARP], |
| 149 |
StartCdataSectionHandler = [], |
| 150 |
EndCdataSectionHandler = [], |
| 151 |
DefaultHandler = [INTERNED_CCHARP, rffi.INT_real], |
| 152 |
DefaultHandlerExpand = [INTERNED_CCHARP, rffi.INT_real], |
| 153 |
NotStandaloneHandler = [], |
| 154 |
ExternalEntityRefHandler = [INTERNED_CCHARP] * 4, |
| 155 |
StartDoctypeDeclHandler = [INTERNED_CCHARP, INTERNED_CCHARP, |
| 156 |
INTERNED_CCHARP, rffi.INT_real], |
| 157 |
EndDoctypeDeclHandler = [], |
| 158 |
EntityDeclHandler = [INTERNED_CCHARP, rffi.INT_real, INTERNED_CCHARP, |
| 159 |
rffi.INT_real, INTERNED_CCHARP, INTERNED_CCHARP, |
| 160 |
INTERNED_CCHARP, INTERNED_CCHARP], |
| 161 |
XmlDeclHandler = [INTERNED_CCHARP, INTERNED_CCHARP, rffi.INT_real], |
| 162 |
ElementDeclHandler = [INTERNED_CCHARP, lltype.Ptr(XML_Content)], |
| 163 |
AttlistDeclHandler = [INTERNED_CCHARP, INTERNED_CCHARP, |
| 164 |
INTERNED_CCHARP, INTERNED_CCHARP, rffi.INT_real], |
| 165 |
SkippedEntityHandler = [INTERNED_CCHARP, rffi.INT_real], |
| 166 |
) |
| 167 |
NB_HANDLERS = len(HANDLERS) |
| 168 |
|
| 169 |
class Storage: |
| 170 |
"Store objects under a non moving ID" |
| 171 |
def __init__(self): |
| 172 |
self.clear() |
| 173 |
|
| 174 |
def clear(self): |
| 175 |
self.next_id = 0 |
| 176 |
self._last_object_id = -1 |
| 177 |
self._last_object = None |
| 178 |
self.storage = {} |
| 179 |
|
| 180 |
@staticmethod |
| 181 |
def get_nonmoving_id(obj, id=-1): |
| 182 |
if id < 0: |
| 183 |
id = global_storage.next_id |
| 184 |
global_storage.next_id += 1 |
| 185 |
global_storage.storage[id] = obj |
| 186 |
return id |
| 187 |
|
| 188 |
@staticmethod |
| 189 |
def get_object(id): |
| 190 |
if id == global_storage._last_object_id: |
| 191 |
return global_storage._last_object |
| 192 |
result = global_storage.storage[id] |
| 193 |
global_storage._last_object_id = id |
| 194 |
global_storage._last_object = result |
| 195 |
return result |
| 196 |
|
| 197 |
@staticmethod |
| 198 |
def free_nonmoving_id(id): |
| 199 |
if id == global_storage._last_object_id: |
| 200 |
global_storage._last_object = None |
| 201 |
global_storage._last_object_id = -1 |
| 202 |
del global_storage.storage[id] |
| 203 |
|
| 204 |
global_storage = Storage() |
| 205 |
|
| 206 |
class CallbackData(W_Root): |
| 207 |
def __init__(self, space, parser): |
| 208 |
self.space = space |
| 209 |
self.parser = weakref.ref(parser) |
| 210 |
|
| 211 |
SETTERS = {} |
| 212 |
for index, (name, params) in enumerate(HANDLERS.items()): |
| 213 |
arg_names = ['arg%d' % (i,) for i in range(len(params))] |
| 214 |
warg_names = ['w_arg%d' % (i,) for i in range(len(params))] |
| 215 |
|
| 216 |
converters = [] |
| 217 |
real_params = [] |
| 218 |
|
| 219 |
for i, ARG in enumerate(params): |
| 220 |
|
| 221 |
if name == "StartElementHandler" and i == 1: |
| 222 |
converters.append( |
| 223 |
'w_arg%d = parser.w_convert_attributes(space, arg%d)' % (i, i)) |
| 224 |
elif name in ["CharacterDataHandler", "DefaultHandlerExpand", "DefaultHandler"] and i == 0: |
| 225 |
converters.append( |
| 226 |
'w_arg%d = parser.w_convert_interned_n(space, arg%d, arg%d)' % (i, i, i+1)) |
| 227 |
del warg_names[i+1] |
| 228 |
ARG = rffi.CONST_CCHARP |
| 229 |
elif name in ["EntityDeclHandler"] and i == 2: |
| 230 |
converters.append( |
| 231 |
'w_arg%d = parser.w_convert_interned_n(space, arg%d, arg%d)' % (i, i, i+1)) |
| 232 |
del warg_names[i+1] |
| 233 |
ARG = rffi.CONST_CCHARP |
| 234 |
|
| 235 |
elif ARG == rffi.CCHARP: |
| 236 |
converters.append( |
| 237 |
'w_arg%d = parser.w_convert_charp(space, arg%d)' % (i, i)) |
| 238 |
elif ARG == INTERNED_CCHARP: |
| 239 |
converters.append( |
| 240 |
'w_arg%d = parser.w_convert_interned(space, arg%d)' % (i, i)) |
| 241 |
ARG = rffi.CONST_CCHARP |
| 242 |
elif ARG == lltype.Ptr(XML_Content): |
| 243 |
converters.append( |
| 244 |
'w_arg%d = parser.w_convert_model(space, arg%d)' % (i, i)) |
| 245 |
converters.append( |
| 246 |
'XML_FreeContentModel(parser.itself, arg%d)' % (i,)) |
| 247 |
elif ARG == rffi.INT: |
| 248 |
converters.append("w_arg%d = space.newint(arg%d)" % (i, i)) |
| 249 |
elif ARG == rffi.INT_real: |
| 250 |
converters.append("w_arg%d = space.newint(arg%d)" % (i, i)) |
| 251 |
elif ARG == rffi.ULONGLONG: |
| 252 |
|
| 253 |
converters.append("w_arg%d = space.newint(arg%d)" % (i, i)) |
| 254 |
real_params.append(ARG) |
| 255 |
converters = '; '.join(converters) |
| 256 |
|
| 257 |
args = ', '.join(arg_names) |
| 258 |
wargs = ', '.join(warg_names) |
| 259 |
|
| 260 |
if name in ['ExternalEntityRefHandler', |
| 261 |
'NotStandaloneHandler']: |
| 262 |
result_type = rffi.INT_real |
| 263 |
result_converter = "rffi.cast(rffi.INT_real, space.int_w(w_result))" |
| 264 |
result_error = "rffi.cast(rffi.INT_real, 0)" |
| 265 |
else: |
| 266 |
result_type = lltype.Void |
| 267 |
result_converter = "None" |
| 268 |
result_error = "None" |
| 269 |
|
| 270 |
if name == 'CharacterDataHandler': |
| 271 |
pre_code = 'if parser.buffer_string(space, w_arg0, arg1): return' |
| 272 |
else: |
| 273 |
pre_code = 'parser.flush_character_buffer(space)' |
| 274 |
|
| 275 |
if name == 'ExternalEntityRefHandler': |
| 276 |
first_arg = 'll_parser' |
| 277 |
first_lltype = XML_Parser |
| 278 |
ll_id = 'XML_GetUserData(ll_parser)' |
| 279 |
post_code = 'if space.is_w(w_result, space.w_None): return 0' |
| 280 |
else: |
| 281 |
first_arg = 'll_userdata' |
| 282 |
first_lltype = rffi.VOIDP |
| 283 |
ll_id = 'll_userdata' |
| 284 |
post_code = '' |
| 285 |
|
| 286 |
src = py.code.Source(""" |
| 287 |
@jit.jit_callback('XML:%(name)s') |
| 288 |
def %(name)s_callback(%(first_arg)s, %(args)s): |
| 289 |
id = rffi.cast(lltype.Signed, %(ll_id)s) |
| 290 |
userdata = global_storage.get_object(id) |
| 291 |
space = userdata.space |
| 292 |
parser = userdata.parser() |
| 293 |
|
| 294 |
handler = parser.handlers[%(index)s] |
| 295 |
if not handler: |
| 296 |
return %(result_error)s |
| 297 |
|
| 298 |
try: |
| 299 |
%(converters)s |
| 300 |
%(pre_code)s |
| 301 |
w_result = space.call_function(handler, %(wargs)s) |
| 302 |
%(post_code)s |
| 303 |
except OperationError, e: |
| 304 |
if not parser._exc_info: # don't override an existing exception |
| 305 |
parser._exc_info = e |
| 306 |
XML_StopParser(parser.itself, XML_FALSE) |
| 307 |
return %(result_error)s |
| 308 |
return %(result_converter)s |
| 309 |
callback = %(name)s_callback |
| 310 |
""" % locals()) |
| 311 |
|
| 312 |
exec src.compile() |
| 313 |
|
| 314 |
c_name = 'XML_Set' + name |
| 315 |
callback_type = lltype.Ptr(lltype.FuncType( |
| 316 |
[first_lltype] + real_params, result_type)) |
| 317 |
func = expat_external(c_name, |
| 318 |
[XML_Parser, callback_type], lltype.Void) |
| 319 |
SETTERS[name] = (index, func, callback) |
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
def UnknownEncodingHandlerData_callback(ll_userdata, name, info): |
| 325 |
id = rffi.cast(lltype.Signed, ll_userdata) |
| 326 |
userdata = global_storage.get_object(id) |
| 327 |
space = userdata.space |
| 328 |
parser = userdata.parser() |
| 329 |
|
| 330 |
name = rffi.constcharp2str(name) |
| 331 |
|
| 332 |
try: |
| 333 |
parser.UnknownEncodingHandler(space, name, info) |
| 334 |
except OperationError as e: |
| 335 |
if not parser._exc_info: |
| 336 |
parser._exc_info = e |
| 337 |
XML_StopParser(parser.itself, XML_FALSE) |
| 338 |
result = 0 |
| 339 |
else: |
| 340 |
result = 1 |
| 341 |
return rffi.cast(rffi.INT_real, result) |
| 342 |
|
| 343 |
callback_type = lltype.Ptr(lltype.FuncType( |
| 344 |
[rffi.VOIDP, rffi.CONST_CCHARP, XML_Encoding_Ptr], rffi.INT_real)) |
| 345 |
XML_SetUnknownEncodingHandler = expat_external( |
| 346 |
'XML_SetUnknownEncodingHandler', |
| 347 |
[XML_Parser, callback_type, rffi.VOIDP], lltype.Void) |
| 348 |
XML_SetEncoding = expat_external( |
| 349 |
'XML_SetEncoding', [XML_Parser, rffi.CCHARP], rffi.INT) |
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
XML_ParserCreate = expat_external( |
| 354 |
'XML_ParserCreate', [rffi.CCHARP], XML_Parser) |
| 355 |
XML_ParserCreateNS = expat_external( |
| 356 |
'XML_ParserCreateNS', [rffi.CCHARP, rffi.CHAR], XML_Parser) |
| 357 |
XML_ParserFree = expat_external( |
| 358 |
'XML_ParserFree', [XML_Parser], lltype.Void, releasegil=False) |
| 359 |
XML_SetUserData = expat_external( |
| 360 |
'XML_SetUserData', [XML_Parser, rffi.VOIDP], lltype.Void) |
| 361 |
def XML_GetUserData(parser): |
| 362 |
|
| 363 |
return rffi.cast(rffi.VOIDPP, parser)[0] |
| 364 |
XML_Parse = expat_external( |
| 365 |
'XML_Parse', [XML_Parser, rffi.CCHARP, rffi.INT, rffi.INT], rffi.INT) |
| 366 |
XML_StopParser = expat_external( |
| 367 |
'XML_StopParser', [XML_Parser, rffi.INT], lltype.Void) |
| 368 |
|
| 369 |
XML_SetReturnNSTriplet = expat_external( |
| 370 |
'XML_SetReturnNSTriplet', [XML_Parser, rffi.INT], lltype.Void) |
| 371 |
XML_GetSpecifiedAttributeCount = expat_external( |
| 372 |
'XML_GetSpecifiedAttributeCount', [XML_Parser], rffi.INT) |
| 373 |
XML_SetParamEntityParsing = expat_external( |
| 374 |
'XML_SetParamEntityParsing', [XML_Parser, rffi.INT], lltype.Void) |
| 375 |
XML_SetBase = expat_external( |
| 376 |
'XML_SetBase', [XML_Parser, rffi.CCHARP], lltype.Void) |
| 377 |
XML_UseForeignDTD = expat_external( |
| 378 |
'XML_UseForeignDTD', [XML_Parser, rffi.INT], lltype.Void) |
| 379 |
XML_SetAllocTrackerActivationThreshold = expat_external( |
| 380 |
'XML_SetAllocTrackerActivationThreshold', [XML_Parser, rffi.ULONGLONG], rffi.INT) |
| 381 |
XML_SetAllocTrackerMaximumAmplification = expat_external( |
| 382 |
'XML_SetAllocTrackerMaximumAmplification', [XML_Parser, rffi.FLOAT], rffi.INT) |
| 383 |
XML_GetErrorCode = expat_external( |
| 384 |
'XML_GetErrorCode', [XML_Parser], rffi.INT) |
| 385 |
XML_ErrorString = expat_external( |
| 386 |
'XML_ErrorString', [rffi.INT], |
| 387 |
rffi.CONST_CCHARP) |
| 388 |
XML_GetCurrentLineNumber = expat_external( |
| 389 |
'XML_GetCurrentLineNumber', [XML_Parser], rffi.INT) |
| 390 |
XML_GetErrorLineNumber = XML_GetCurrentLineNumber |
| 391 |
XML_GetCurrentColumnNumber = expat_external( |
| 392 |
'XML_GetCurrentColumnNumber', [XML_Parser], rffi.INT) |
| 393 |
XML_GetErrorColumnNumber = XML_GetCurrentColumnNumber |
| 394 |
XML_GetCurrentByteIndex = expat_external( |
| 395 |
'XML_GetCurrentByteIndex', [XML_Parser], rffi.INT) |
| 396 |
XML_GetErrorByteIndex = XML_GetCurrentByteIndex |
| 397 |
|
| 398 |
XML_FreeContentModel = expat_external( |
| 399 |
'XML_FreeContentModel', [XML_Parser, lltype.Ptr(XML_Content)], lltype.Void) |
| 400 |
XML_ExternalEntityParserCreate = expat_external( |
| 401 |
'XML_ExternalEntityParserCreate', [XML_Parser, rffi.CCHARP, rffi.CCHARP], |
| 402 |
XML_Parser) |
| 403 |
if XML_COMBINED_VERSION >= 20600: |
| 404 |
XML_SetReparseDeferralEnabled = expat_external( |
| 405 |
'XML_SetReparseDeferralEnabled', [XML_Parser, rffi.UCHAR], rffi.INT) |
| 406 |
XML_ExpatVersion = expat_external( |
| 407 |
'XML_ExpatVersion', [], rffi.CONST_CCHARP) |
| 408 |
|
| 409 |
def get_expat_version(space): |
| 410 |
return space.newtext(rffi.constcharp2str(XML_ExpatVersion())) |
| 411 |
|
| 412 |
def get_expat_version_info(space): |
| 413 |
return space.newtuple([ |
| 414 |
space.newint(XML_MAJOR_VERSION), |
| 415 |
space.newint(XML_MINOR_VERSION), |
| 416 |
space.newint(XML_MICRO_VERSION)]) |
| 417 |
|
| 418 |
class Cache: |
| 419 |
def __init__(self, space): |
| 420 |
self.w_error = space.new_exception_class("pyexpat.ExpatError") |
| 421 |
|
| 422 |
|
| 423 |
class W_XMLParserType(W_Root): |
| 424 |
id = -1 |
| 425 |
|
| 426 |
def __init__(self, space, parser, w_intern): |
| 427 |
self.itself = parser |
| 428 |
self.register_finalizer(space) |
| 429 |
|
| 430 |
self.w_intern = w_intern |
| 431 |
|
| 432 |
self.ordered_attributes = False |
| 433 |
self.specified_attributes = False |
| 434 |
self.ns_prefixes = False |
| 435 |
|
| 436 |
self.handlers = [None] * NB_HANDLERS |
| 437 |
|
| 438 |
self.buffer = None |
| 439 |
self.buffer_size = 8192 |
| 440 |
self.buffer_used = 0 |
| 441 |
if XML_COMBINED_VERSION >= 20600: |
| 442 |
self.reparse_deferral_enabled = True |
| 443 |
else: |
| 444 |
self.reparse_deferral_enabled = False |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
self.w_character_data_handler = None |
| 452 |
|
| 453 |
self._exc_info = None |
| 454 |
|
| 455 |
|
| 456 |
self.id = global_storage.get_nonmoving_id( |
| 457 |
CallbackData(space, self)) |
| 458 |
XML_SetUserData(self.itself, rffi.cast(rffi.VOIDP, self.id)) |
| 459 |
|
| 460 |
def _finalize_(self): |
| 461 |
if XML_ParserFree: |
| 462 |
if self.itself: |
| 463 |
XML_ParserFree(self.itself) |
| 464 |
self.itself = lltype.nullptr(XML_Parser.TO) |
| 465 |
if global_storage and self.id >= 0: |
| 466 |
try: |
| 467 |
global_storage.free_nonmoving_id(self.id) |
| 468 |
except KeyError: |
| 469 |
pass |
| 470 |
self.id = -1 |
| 471 |
|
| 472 |
@unwrap_spec(flag=int) |
| 473 |
def SetParamEntityParsing(self, space, flag): |
| 474 |
"""SetParamEntityParsing(flag) -> success |
| 475 |
Controls parsing of parameter entities (including the external DTD |
| 476 |
subset). Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER, |
| 477 |
XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and |
| 478 |
XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag |
| 479 |
was successful.""" |
| 480 |
XML_SetParamEntityParsing(self.itself, flag) |
| 481 |
|
| 482 |
@unwrap_spec(w_flag=WrappedDefault(True)) |
| 483 |
def UseForeignDTD(self, space, w_flag): |
| 484 |
"""UseForeignDTD([flag]) |
| 485 |
Allows the application to provide an artificial external subset if one is |
| 486 |
not specified as part of the document instance. This readily allows the |
| 487 |
use of a 'default' document type controlled by the application, while still |
| 488 |
getting the advantage of providing document type information to the parser. |
| 489 |
'flag' defaults to True if not provided.""" |
| 490 |
flag = space.is_true(w_flag) |
| 491 |
XML_UseForeignDTD(self.itself, flag) |
| 492 |
|
| 493 |
@unwrap_spec(threshold=rffi.r_ulonglong) |
| 494 |
def SetAllocTrackerActivationThreshold(self, space, threshold): |
| 495 |
"""SetAllocTrackerActivationThreshold(threshold) -> success |
| 496 |
Sets the number of allocated bytes of dynamic memory needed to activate protection against disproportionate use of RAM. |
| 497 |
|
| 498 |
By default, parser objects have an allocation activation threshold of 64 MiB. |
| 499 |
[clinic start generated code]""" |
| 500 |
|
| 501 |
ret = XML_SetAllocTrackerActivationThreshold(self.itself, threshold) |
| 502 |
if ret == XML_TRUE: |
| 503 |
return None |
| 504 |
raise self.set_error_msg(space, "parser must be a root parser") |
| 505 |
|
| 506 |
|
| 507 |
@unwrap_spec(max_factor=float) |
| 508 |
def SetAllocTrackerMaximumAmplification(self, space, max_factor): |
| 509 |
"""SetAllocTrackerMaximumAmplification(max_factor) -> success |
| 510 |
Sets the maximum amplification factor between direct input and bytes of dynamic memory allocated. |
| 511 |
|
| 512 |
The amplification factor is calculated as "allocated / direct" while parsing, |
| 513 |
where "direct" is the number of bytes read from the primary document in parsing |
| 514 |
and "allocated" is the number of bytes of dynamic memory allocated in the parser |
| 515 |
hierarchy. |
| 516 |
|
| 517 |
The 'max_factor' value must be a non-NaN floating point value greater than |
| 518 |
or equal to 1.0. Amplification factors greater than 100.0 can be observed |
| 519 |
near the start of parsing even with benign files in practice. In particular, |
| 520 |
the activation threshold should be carefully chosen to avoid false positives. |
| 521 |
|
| 522 |
By default, parser objects have a maximum amplification factor of 100.0.""" |
| 523 |
|
| 524 |
if math.isnan(max_factor) or max_factor < 1.0: |
| 525 |
raise self.set_error_msg(space, "'max_factor' must be at least 1.0") |
| 526 |
max_factorF = rffi.cast(rffi.FLOAT, max_factor) |
| 527 |
ret = XML_SetAllocTrackerMaximumAmplification(self.itself, max_factorF) |
| 528 |
if ret == XML_TRUE: |
| 529 |
return None |
| 530 |
raise self.set_error_msg(space, "parser must be a root parser") |
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
def w_convert(self, space, s): |
| 536 |
|
| 537 |
|
| 538 |
try: |
| 539 |
lgt = rutf8.check_utf8(s, True) |
| 540 |
return space.newutf8(s, lgt) |
| 541 |
except rutf8.CheckError: |
| 542 |
from pypy.interpreter import unicodehelper |
| 543 |
|
| 544 |
w_s = space.newbytes(s) |
| 545 |
unicodehelper.str_decode_utf8(space, s, w_s, 'string', True, |
| 546 |
unicodehelper.decode_error_handler(space)) |
| 547 |
assert False, "always raises" |
| 548 |
return space.newtext(s) |
| 549 |
|
| 550 |
def w_convert_charp(self, space, data): |
| 551 |
if data: |
| 552 |
return self.w_convert(space, rffi.charp2str(data)) |
| 553 |
else: |
| 554 |
return space.w_None |
| 555 |
|
| 556 |
def w_convert_interned(self, space, data): |
| 557 |
if not data: |
| 558 |
return space.w_None |
| 559 |
w_data = self.w_convert(space, rffi.constcharp2str(data)) |
| 560 |
if not self.w_intern: |
| 561 |
return w_data |
| 562 |
|
| 563 |
try: |
| 564 |
return space.getitem(self.w_intern, w_data) |
| 565 |
except OperationError as e: |
| 566 |
if not e.match(space, space.w_KeyError): |
| 567 |
raise |
| 568 |
space.setitem(self.w_intern, w_data, w_data) |
| 569 |
return w_data |
| 570 |
|
| 571 |
def w_convert_charp_n(self, space, data, length): |
| 572 |
ll_length = rffi.cast(lltype.Signed, length) |
| 573 |
if data: |
| 574 |
return self.w_convert(space, rffi.charp2strn(data, ll_length)) |
| 575 |
else: |
| 576 |
return space.w_None |
| 577 |
|
| 578 |
def w_convert_interned_n(self, space, data, length): |
| 579 |
ll_length = rffi.cast(lltype.Signed, length) |
| 580 |
if data: |
| 581 |
return self.w_convert(space, rffi.constcharpsize2str(data, ll_length)) |
| 582 |
else: |
| 583 |
return space.w_None |
| 584 |
|
| 585 |
def w_convert_attributes(self, space, attrs): |
| 586 |
if self.specified_attributes: |
| 587 |
maxindex = XML_GetSpecifiedAttributeCount(self.itself) |
| 588 |
else: |
| 589 |
maxindex = 0 |
| 590 |
while attrs[maxindex]: |
| 591 |
maxindex += 2 |
| 592 |
|
| 593 |
if self.ordered_attributes: |
| 594 |
w_attrs = space.newlist([ |
| 595 |
self.w_convert_interned(space, attrs[i]) |
| 596 |
for i in range(maxindex)]) |
| 597 |
else: |
| 598 |
w_attrs = space.newdict() |
| 599 |
for i in range(0, maxindex, 2): |
| 600 |
space.setitem( |
| 601 |
w_attrs, |
| 602 |
self.w_convert_interned(space, attrs[i]), |
| 603 |
self.w_convert_interned(space, attrs[i + 1])) |
| 604 |
|
| 605 |
return w_attrs |
| 606 |
|
| 607 |
def w_convert_model(self, space, model): |
| 608 |
children = [self.w_convert_model(space, model.c_children[i]) |
| 609 |
for i in range(model.c_numchildren)] |
| 610 |
return space.newtuple([ |
| 611 |
space.newint(model.c_type), |
| 612 |
space.newint(model.c_quant), |
| 613 |
self.w_convert_charp(space, model.c_name), |
| 614 |
space.newtuple(children)]) |
| 615 |
|
| 616 |
def buffer_string(self, space, w_string, length): |
| 617 |
ll_length = rffi.cast(lltype.Signed, length) |
| 618 |
if self.buffer is not None: |
| 619 |
if self.buffer_used + ll_length > self.buffer_size: |
| 620 |
self.flush_character_buffer(space) |
| 621 |
|
| 622 |
|
| 623 |
if self.w_character_data_handler is None: |
| 624 |
return True |
| 625 |
if ll_length <= self.buffer_size: |
| 626 |
self.buffer.append(w_string) |
| 627 |
self.buffer_used += ll_length |
| 628 |
return True |
| 629 |
else: |
| 630 |
self.buffer = [] |
| 631 |
self.buffer_used = 0 |
| 632 |
return False |
| 633 |
|
| 634 |
def gethandler(self, space, name, index): |
| 635 |
if name == 'CharacterDataHandler': |
| 636 |
return self.w_character_data_handler or space.w_None |
| 637 |
return self.handlers[index] |
| 638 |
|
| 639 |
@specialize.arg(2) |
| 640 |
def sethandler(self, space, name, w_handler, index, setter, handler): |
| 641 |
if name == 'CharacterDataHandler': |
| 642 |
self.flush_character_buffer(space) |
| 643 |
if space.is_w(w_handler, space.w_None): |
| 644 |
self.w_character_data_handler = None |
| 645 |
else: |
| 646 |
self.w_character_data_handler = w_handler |
| 647 |
|
| 648 |
self.handlers[index] = w_handler |
| 649 |
setter(self.itself, handler) |
| 650 |
|
| 651 |
all_chars = ''.join(chr(i) for i in range(256)) |
| 652 |
|
| 653 |
def UnknownEncodingHandler(self, space, name, info): |
| 654 |
|
| 655 |
translationmap, lgt = space.utf8_len_w( |
| 656 |
space.call_method( |
| 657 |
space.newbytes(self.all_chars), "decode", |
| 658 |
space.newtext(name), space.newtext("replace"))) |
| 659 |
|
| 660 |
if lgt != 256: |
| 661 |
raise oefmt(space.w_ValueError, |
| 662 |
"multi-byte encodings are not supported") |
| 663 |
|
| 664 |
i = 0 |
| 665 |
for c in rutf8.Utf8StringIterator(translationmap): |
| 666 |
if c == 0xfffd: |
| 667 |
info.c_map[i] = rffi.cast(rffi.INT, -1) |
| 668 |
else: |
| 669 |
info.c_map[i] = rffi.cast(rffi.INT, c) |
| 670 |
i += 1 |
| 671 |
info.c_data = lltype.nullptr(rffi.VOIDP.TO) |
| 672 |
info.c_convert = lltype.nullptr(rffi.VOIDP.TO) |
| 673 |
info.c_release = lltype.nullptr(rffi.VOIDP.TO) |
| 674 |
return True |
| 675 |
|
| 676 |
|
| 677 |
@staticmethod |
| 678 |
def _make_property(name): |
| 679 |
index, setter, handler = SETTERS[name] |
| 680 |
|
| 681 |
def descr_get_property(self, space): |
| 682 |
return self.gethandler(space, name, index) |
| 683 |
|
| 684 |
def descr_set_property(self, space, w_value): |
| 685 |
return self.sethandler(space, name, w_value, |
| 686 |
index, setter, handler) |
| 687 |
|
| 688 |
return GetSetProperty(descr_get_property, |
| 689 |
descr_set_property, |
| 690 |
cls=W_XMLParserType) |
| 691 |
|
| 692 |
|
| 693 |
def get_namespace_prefixes(self, space): |
| 694 |
return space.newbool(self.ns_prefixes) |
| 695 |
|
| 696 |
def set_namespace_prefixes(self, space, w_value): |
| 697 |
self.ns_prefixes = space.bool_w(w_value) |
| 698 |
XML_SetReturnNSTriplet(self.itself, self.ns_prefixes) |
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
@unwrap_spec(isfinal=int) |
| 703 |
def Parse(self, space, w_data, isfinal=False): |
| 704 |
"""Parse(data[, isfinal]) |
| 705 |
Parse XML data. `isfinal' should be true at end of input.""" |
| 706 |
if space.isinstance_w(w_data, space.w_unicode): |
| 707 |
data = w_data.utf8_w(space) |
| 708 |
|
| 709 |
XML_SetEncoding(self.itself, "utf-8") |
| 710 |
else: |
| 711 |
data = space.charbuf_w(w_data) |
| 712 |
isfinal = bool(isfinal) |
| 713 |
res = XML_Parse(self.itself, data, len(data), isfinal) |
| 714 |
if self._exc_info: |
| 715 |
e = self._exc_info |
| 716 |
self._exc_info = None |
| 717 |
raise e |
| 718 |
elif res == 0: |
| 719 |
exc = self.set_error(space, XML_GetErrorCode(self.itself)) |
| 720 |
raise exc |
| 721 |
self.flush_character_buffer(space) |
| 722 |
return space.newint(res) |
| 723 |
|
| 724 |
def ParseFile(self, space, w_file): |
| 725 |
"""ParseFile(file) |
| 726 |
Parse XML data from file-like object.""" |
| 727 |
eof = False |
| 728 |
while not eof: |
| 729 |
w_data = space.call_method(w_file, 'read', space.newint(2048)) |
| 730 |
eof = space.len_w(w_data) == 0 |
| 731 |
w_res = self.Parse(space, w_data, isfinal=eof) |
| 732 |
return w_res |
| 733 |
|
| 734 |
@unwrap_spec(base='text') |
| 735 |
def SetBase(self, space, base): |
| 736 |
XML_SetBase(self.itself, base) |
| 737 |
|
| 738 |
def ExternalEntityParserCreate(self, space, w_context, w_encoding=None): |
| 739 |
"""ExternalEntityParserCreate(context[, encoding]) |
| 740 |
Create a parser for parsing an external entity based on the |
| 741 |
information passed to the ExternalEntityRefHandler.""" |
| 742 |
if space.is_w(w_context, space.w_None): |
| 743 |
context = None |
| 744 |
else: |
| 745 |
context = space.text_w(w_context) |
| 746 |
|
| 747 |
if space.is_none(w_encoding): |
| 748 |
encoding = None |
| 749 |
else: |
| 750 |
encoding = space.text_w(w_encoding) |
| 751 |
|
| 752 |
xmlparser = XML_ExternalEntityParserCreate( |
| 753 |
self.itself, context, encoding) |
| 754 |
if not xmlparser: |
| 755 |
raise MemoryError |
| 756 |
|
| 757 |
parser = W_XMLParserType(space, xmlparser, self.w_intern) |
| 758 |
|
| 759 |
|
| 760 |
for i in range(NB_HANDLERS): |
| 761 |
parser.handlers[i] = self.handlers[i] |
| 762 |
|
| 763 |
return parser |
| 764 |
|
| 765 |
def flush_character_buffer(self, space): |
| 766 |
if not self.buffer: |
| 767 |
return |
| 768 |
w_data = space.call_function( |
| 769 |
space.getattr(space.newtext(''), space.newtext('join')), |
| 770 |
space.newlist(self.buffer)) |
| 771 |
self.buffer = [] |
| 772 |
self.buffer_used = 0 |
| 773 |
|
| 774 |
if self.w_character_data_handler: |
| 775 |
space.call_function(self.w_character_data_handler, w_data) |
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
def set_error(self, space, code): |
| 780 |
err = rffi.constcharp2str(XML_ErrorString(code)) |
| 781 |
lineno = XML_GetCurrentLineNumber(self.itself) |
| 782 |
colno = XML_GetCurrentColumnNumber(self.itself) |
| 783 |
msg = "%s: line %d, column %d" % (err, lineno, colno) |
| 784 |
w_errorcls = space.fromcache(Cache).w_error |
| 785 |
w_error = space.call_function(w_errorcls, space.newtext(msg)) |
| 786 |
space.setattr(w_error, space.newtext("code"), space.newint(code)) |
| 787 |
space.setattr(w_error, space.newtext("offset"), space.newint(colno)) |
| 788 |
space.setattr(w_error, space.newtext("lineno"), space.newint(lineno)) |
| 789 |
|
| 790 |
self.w_error = w_error |
| 791 |
return OperationError(w_errorcls, w_error) |
| 792 |
|
| 793 |
def set_error_msg(self, space, msg): |
| 794 |
w_errorcls = space.fromcache(Cache).w_error |
| 795 |
w_error = space.call_function(w_errorcls, space.newtext(msg)) |
| 796 |
space.setattr(w_error, space.newtext("code"), space.newint(0)) |
| 797 |
space.setattr(w_error, space.newtext("offset"), space.newint(0)) |
| 798 |
space.setattr(w_error, space.newtext("lineno"), space.newint(0)) |
| 799 |
|
| 800 |
self.w_error = w_error |
| 801 |
return OperationError(w_errorcls, w_error) |
| 802 |
|
| 803 |
def descr_ErrorCode(self, space): |
| 804 |
return space.newint(XML_GetErrorCode(self.itself)) |
| 805 |
|
| 806 |
def descr_ErrorLineNumber(self, space): |
| 807 |
return space.newint(XML_GetErrorLineNumber(self.itself)) |
| 808 |
|
| 809 |
def descr_ErrorColumnNumber(self, space): |
| 810 |
return space.newint(XML_GetErrorColumnNumber(self.itself)) |
| 811 |
|
| 812 |
def descr_ErrorByteIndex(self, space): |
| 813 |
return space.newint(XML_GetErrorByteIndex(self.itself)) |
| 814 |
|
| 815 |
def get_buffer_size(self, space): |
| 816 |
return space.newint(self.buffer_size) |
| 817 |
def set_buffer_size(self, space, w_value): |
| 818 |
value = space.getindex_w(w_value, space.w_OverflowError) |
| 819 |
if value <= 0: |
| 820 |
raise oefmt(space.w_ValueError, |
| 821 |
"buffer_size must be greater than zero") |
| 822 |
self.flush_character_buffer(space) |
| 823 |
self.buffer_size = value |
| 824 |
|
| 825 |
def get_buffer_text(self, space): |
| 826 |
return space.newbool(self.buffer is not None) |
| 827 |
def set_buffer_text(self, space, w_value): |
| 828 |
if space.is_true(w_value): |
| 829 |
self.buffer = [] |
| 830 |
self.buffer_used = 0 |
| 831 |
else: |
| 832 |
self.flush_character_buffer(space) |
| 833 |
self.buffer = None |
| 834 |
|
| 835 |
def get_intern(self, space): |
| 836 |
if self.w_intern: |
| 837 |
return self.w_intern |
| 838 |
else: |
| 839 |
return space.w_None |
| 840 |
|
| 841 |
def descr_flush(self, space): |
| 842 |
XML_SetReparseDeferralEnabled(self.itself, XML_FALSE) |
| 843 |
res = XML_Parse(self.itself, "", 0, XML_FALSE) |
| 844 |
if self._exc_info: |
| 845 |
e = self._exc_info |
| 846 |
self._exc_info = None |
| 847 |
raise e |
| 848 |
elif res == 0: |
| 849 |
raise self.set_error(space, XML_GetErrorCode(self.itself)) |
| 850 |
XML_SetReparseDeferralEnabled(self.itself, XML_TRUE) |
| 851 |
self.flush_character_buffer(space) |
| 852 |
return space.newint(res) |
| 853 |
|
| 854 |
@unwrap_spec(val=int) |
| 855 |
def descr_SetReparseDeferralEnabled(self, space, val): |
| 856 |
"""Enable/Disable reparse deferral; enabled by default with Expat >=2.6.0. |
| 857 |
""" |
| 858 |
if XML_COMBINED_VERSION >=2600: |
| 859 |
enabled = bool(val) |
| 860 |
XML_SetReparseDeferralEnabled(self.itself, rffi.cast(rffi.UCHAR, enabled)) |
| 861 |
self.reparse_deferral_enabled = enabled |
| 862 |
|
| 863 |
def descr_GetReparseDeferralEnabled(self, space): |
| 864 |
return space.newbool(self.reparse_deferral_enabled) |
| 865 |
|
| 866 |
def bool_property(name, cls, doc=None): |
| 867 |
def fget(space, obj): |
| 868 |
return space.newbool(getattr(obj, name)) |
| 869 |
def fset(space, obj, value): |
| 870 |
setattr(obj, name, space.bool_w(value)) |
| 871 |
return GetSetProperty(fget, fset, cls=cls, doc=doc) |
| 872 |
|
| 873 |
XMLParser_methods = ['Parse', 'ParseFile', 'SetBase', 'SetParamEntityParsing', |
| 874 |
'ExternalEntityParserCreate', 'UseForeignDTD', |
| 875 |
'SetAllocTrackerActivationThreshold', |
| 876 |
'SetAllocTrackerMaximumAmplification', |
| 877 |
] |
| 878 |
|
| 879 |
_XMLParser_extras = {} |
| 880 |
for name in XMLParser_methods: |
| 881 |
_XMLParser_extras[name] = interp2app(getattr(W_XMLParserType, name)) |
| 882 |
for name in SETTERS: |
| 883 |
_XMLParser_extras[name] = W_XMLParserType._make_property(name) |
| 884 |
|
| 885 |
W_XMLParserType.typedef = TypeDef( |
| 886 |
"pyexpat.XMLParserType", |
| 887 |
__doc__ = "XML parser", |
| 888 |
namespace_prefixes = GetSetProperty(W_XMLParserType.get_namespace_prefixes, |
| 889 |
W_XMLParserType.set_namespace_prefixes, |
| 890 |
cls=W_XMLParserType), |
| 891 |
ordered_attributes = bool_property('ordered_attributes', W_XMLParserType), |
| 892 |
specified_attributes = bool_property('specified_attributes', W_XMLParserType), |
| 893 |
intern = GetSetProperty(W_XMLParserType.get_intern, cls=W_XMLParserType), |
| 894 |
buffer_size = GetSetProperty(W_XMLParserType.get_buffer_size, |
| 895 |
W_XMLParserType.set_buffer_size, |
| 896 |
cls=W_XMLParserType), |
| 897 |
buffer_text = GetSetProperty(W_XMLParserType.get_buffer_text, |
| 898 |
W_XMLParserType.set_buffer_text, cls=W_XMLParserType), |
| 899 |
flush = interp2app(W_XMLParserType.descr_flush), |
| 900 |
|
| 901 |
ErrorCode = GetSetProperty(W_XMLParserType.descr_ErrorCode, cls=W_XMLParserType), |
| 902 |
ErrorLineNumber = GetSetProperty(W_XMLParserType.descr_ErrorLineNumber, cls=W_XMLParserType), |
| 903 |
ErrorColumnNumber = GetSetProperty(W_XMLParserType.descr_ErrorColumnNumber, cls=W_XMLParserType), |
| 904 |
ErrorByteIndex = GetSetProperty(W_XMLParserType.descr_ErrorByteIndex, cls=W_XMLParserType), |
| 905 |
CurrentLineNumber = GetSetProperty(W_XMLParserType.descr_ErrorLineNumber, cls=W_XMLParserType), |
| 906 |
CurrentColumnNumber = GetSetProperty(W_XMLParserType.descr_ErrorColumnNumber, cls=W_XMLParserType), |
| 907 |
CurrentByteIndex = GetSetProperty(W_XMLParserType.descr_ErrorByteIndex, cls=W_XMLParserType), |
| 908 |
SetReparseDeferralEnabled = interp2app(W_XMLParserType.descr_SetReparseDeferralEnabled), |
| 909 |
GetReparseDeferralEnabled = interp2app(W_XMLParserType.descr_GetReparseDeferralEnabled), |
| 910 |
|
| 911 |
**_XMLParser_extras |
| 912 |
) |
| 913 |
|
| 914 |
def ParserCreate(space, w_encoding=None, w_namespace_separator=None, |
| 915 |
w_intern=None): |
| 916 |
"""ParserCreate([encoding[, namespace_separator]]) -> parser |
| 917 |
Return a new XML parser object.""" |
| 918 |
if space.is_none(w_encoding): |
| 919 |
encoding = None |
| 920 |
elif space.isinstance_w(w_encoding, space.w_text): |
| 921 |
encoding = space.text_w(w_encoding) |
| 922 |
else: |
| 923 |
raise oefmt(space.w_TypeError, |
| 924 |
"ParserCreate() argument 'encoding' must be str or None, not %T", |
| 925 |
w_encoding) |
| 926 |
|
| 927 |
if space.is_none(w_namespace_separator): |
| 928 |
namespace_separator = -1 |
| 929 |
elif space.isinstance_w(w_namespace_separator, space.w_text): |
| 930 |
separator = space.text_w(w_namespace_separator) |
| 931 |
if len(separator) == 0: |
| 932 |
namespace_separator = 0 |
| 933 |
elif len(separator) == 1: |
| 934 |
namespace_separator = ord(separator[0]) |
| 935 |
else: |
| 936 |
raise oefmt(space.w_ValueError, |
| 937 |
"namespace_separator must be at most one character, " |
| 938 |
"omitted, or None") |
| 939 |
else: |
| 940 |
raise oefmt(space.w_TypeError, |
| 941 |
"ParserCreate() argument 'namespace_separator' must be str or None, not %T", |
| 942 |
w_namespace_separator) |
| 943 |
|
| 944 |
|
| 945 |
|
| 946 |
if w_intern is None: |
| 947 |
w_intern = space.newdict() |
| 948 |
elif space.is_w(w_intern, space.w_None): |
| 949 |
w_intern = None |
| 950 |
|
| 951 |
if namespace_separator >= 0: |
| 952 |
xmlparser = XML_ParserCreateNS( |
| 953 |
encoding, |
| 954 |
rffi.cast(rffi.CHAR, namespace_separator)) |
| 955 |
else: |
| 956 |
xmlparser = XML_ParserCreate(encoding) |
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
if not xmlparser: |
| 961 |
raise oefmt(space.w_RuntimeError, "XML_ParserCreate failed") |
| 962 |
|
| 963 |
parser = W_XMLParserType(space, xmlparser, w_intern) |
| 964 |
rgc.add_memory_pressure(XML_Parser_SIZE + 300, parser) |
| 965 |
XML_SetUnknownEncodingHandler( |
| 966 |
parser.itself, UnknownEncodingHandlerData_callback, |
| 967 |
rffi.cast(rffi.VOIDP, parser.id)) |
| 968 |
return parser |
| 969 |
|
| 970 |
@unwrap_spec(code=int) |
| 971 |
def ErrorString(space, code): |
| 972 |
"""ErrorString(errno) -> string |
| 973 |
Returns string error for given number.""" |
| 974 |
cstr = XML_ErrorString(code) |
| 975 |
if not cstr: |
| 976 |
return space.w_None |
| 977 |
return space.newtext(rffi.constcharp2str(cstr)) |
| 978 |
|