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