| 1 |
import sys |
| 2 |
from rpython.rlib import jit, rutf8 |
| 3 |
from rpython.rlib.objectmodel import we_are_translated, not_rpython |
| 4 |
from rpython.rlib.rstring import StringBuilder, UnicodeBuilder |
| 5 |
from rpython.rlib.rutf8 import MAXUNICODE |
| 6 |
from rpython.rlib import runicode |
| 7 |
|
| 8 |
from pypy.interpreter.error import OperationError, oefmt, wrap_oserror |
| 9 |
from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault |
| 10 |
from pypy.interpreter import unicodehelper |
| 11 |
from pypy.module.unicodedata.interp_ucd import unicodedb |
| 12 |
|
| 13 |
|
| 14 |
class VersionTag(object): |
| 15 |
pass |
| 16 |
|
| 17 |
|
| 18 |
class CodecState(object): |
| 19 |
_immutable_fields_ = ["version?"] |
| 20 |
|
| 21 |
def __init__(self, space): |
| 22 |
self.codec_search_path = [] |
| 23 |
self.codec_search_cache = {} |
| 24 |
self.codec_error_registry = {} |
| 25 |
self.codec_need_encodings = True |
| 26 |
self.decode_error_handler = self.make_decode_errorhandler(space) |
| 27 |
self.encode_error_handler = self.make_encode_errorhandler(space) |
| 28 |
|
| 29 |
self.unicodedata_handler = None |
| 30 |
self.modified() |
| 31 |
|
| 32 |
def _make_errorhandler(self, space, decode): |
| 33 |
def call_errorhandler(errors, encoding, reason, w_input, startpos, |
| 34 |
endpos): |
| 35 |
"""Generic wrapper for calling into error handlers. |
| 36 |
|
| 37 |
Note that error handler receives and returns position into |
| 38 |
the unicode characters, not into the position of utf8 bytes, |
| 39 |
so it needs to be converted by the codec |
| 40 |
|
| 41 |
Returns (str_or_none, newpos) as error |
| 42 |
handlers return utf8 so we add whether they used unicode or bytes |
| 43 |
""" |
| 44 |
w_errorhandler = lookup_error(space, errors) |
| 45 |
length = space.len_w(w_input) |
| 46 |
if decode: |
| 47 |
w_cls = space.w_UnicodeDecodeError |
| 48 |
else: |
| 49 |
w_cls = space.w_UnicodeEncodeError |
| 50 |
w_exc = space.call_function( |
| 51 |
w_cls, |
| 52 |
space.newtext(encoding), |
| 53 |
w_input, |
| 54 |
space.newint(startpos), |
| 55 |
space.newint(endpos), |
| 56 |
space.newtext(reason)) |
| 57 |
w_res = space.call_function(w_errorhandler, w_exc) |
| 58 |
if (not space.isinstance_w(w_res, space.w_tuple) |
| 59 |
or space.len_w(w_res) != 2): |
| 60 |
if decode: |
| 61 |
msg = ("decoding error handler must return " |
| 62 |
"(str, int) tuple") |
| 63 |
else: |
| 64 |
msg = ("encoding error handler must return " |
| 65 |
"(str/bytes, int) tuple") |
| 66 |
raise OperationError(space.w_TypeError, space.newtext(msg)) |
| 67 |
|
| 68 |
w_replace, w_newpos = space.fixedview(w_res, 2) |
| 69 |
if space.isinstance_w(w_replace, space.w_unicode): |
| 70 |
rettype = 'u' |
| 71 |
elif not decode and space.isinstance_w(w_replace, space.w_bytes): |
| 72 |
rettype = 'b' |
| 73 |
else: |
| 74 |
if decode: |
| 75 |
msg = ("decoding error handler must return " |
| 76 |
"(str, int) tuple") |
| 77 |
else: |
| 78 |
msg = ("encoding error handler must return " |
| 79 |
"(str/bytes, int) tuple") |
| 80 |
raise OperationError(space.w_TypeError, space.newtext(msg)) |
| 81 |
try: |
| 82 |
newpos = space.int_w(w_newpos) |
| 83 |
except OperationError as e: |
| 84 |
if not e.match(space, space.w_OverflowError): |
| 85 |
raise |
| 86 |
newpos = -1 |
| 87 |
else: |
| 88 |
if newpos < 0: |
| 89 |
newpos = length + newpos |
| 90 |
if newpos < 0 or newpos > length: |
| 91 |
raise oefmt(space.w_IndexError, |
| 92 |
"position %d from error handler out of bounds", |
| 93 |
newpos) |
| 94 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 95 |
if decode: |
| 96 |
if not space.isinstance_w(w_obj, space.w_bytes): |
| 97 |
raise oefmt(space.w_ValueError, |
| 98 |
"error handler modified exc.object must be bytes") |
| 99 |
obj = space.bytes_w(w_obj) |
| 100 |
else: |
| 101 |
if not space.isinstance_w(w_obj, space.w_unicode): |
| 102 |
raise oefmt(space.w_ValueError, |
| 103 |
"error handler modified exc.object must be str") |
| 104 |
obj = space.utf8_w(w_obj) |
| 105 |
if rettype == 'b': |
| 106 |
return space.bytes_w(w_replace), newpos, rettype, obj, w_obj |
| 107 |
else: |
| 108 |
return space.utf8_w(w_replace), newpos, rettype, obj, w_obj |
| 109 |
return call_errorhandler |
| 110 |
|
| 111 |
def make_decode_errorhandler(self, space): |
| 112 |
return self._make_errorhandler(space, True) |
| 113 |
|
| 114 |
def make_encode_errorhandler(self, space): |
| 115 |
return self._make_errorhandler(space, False) |
| 116 |
|
| 117 |
def get_unicodedata_handler(self, space): |
| 118 |
if self.unicodedata_handler: |
| 119 |
return self.unicodedata_handler |
| 120 |
try: |
| 121 |
w_unicodedata = space.getbuiltinmodule("unicodedata") |
| 122 |
w_getcode = space.getattr(w_unicodedata, space.newtext("_get_code")) |
| 123 |
except OperationError: |
| 124 |
return None |
| 125 |
else: |
| 126 |
self.unicodedata_handler = UnicodeData_Handler(space, w_getcode) |
| 127 |
return self.unicodedata_handler |
| 128 |
|
| 129 |
def modified(self): |
| 130 |
self.version = VersionTag() |
| 131 |
|
| 132 |
def get_codec_from_cache(self, key): |
| 133 |
return self._get_codec_with_version(key, self.version) |
| 134 |
|
| 135 |
@jit.elidable |
| 136 |
def _get_codec_with_version(self, key, version): |
| 137 |
return self.codec_search_cache.get(key, None) |
| 138 |
|
| 139 |
def _cleanup_(self): |
| 140 |
assert not self.codec_search_path |
| 141 |
|
| 142 |
|
| 143 |
def register_codec(space, w_search_function): |
| 144 |
"""register(search_function) |
| 145 |
|
| 146 |
Register a codec search function. Search functions are expected to take |
| 147 |
one argument, the encoding name in all lower case letters, and return |
| 148 |
a tuple of functions (encoder, decoder, stream_reader, stream_writer). |
| 149 |
""" |
| 150 |
state = space.fromcache(CodecState) |
| 151 |
if space.is_true(space.callable(w_search_function)): |
| 152 |
state.codec_search_path.append(w_search_function) |
| 153 |
else: |
| 154 |
raise oefmt(space.w_TypeError, "argument must be callable") |
| 155 |
|
| 156 |
def unregister(space, w_search_function): |
| 157 |
"""unregister(search_function) |
| 158 |
|
| 159 |
Unregister a codec search function and clear the registry's cache. |
| 160 |
If the search function is not registered, do nothing.""" |
| 161 |
state = space.fromcache(CodecState) |
| 162 |
try: |
| 163 |
state.codec_search_path.remove(w_search_function) |
| 164 |
state.codec_search_cache.clear() |
| 165 |
state.modified() |
| 166 |
return space.newint(0) |
| 167 |
except ValueError: |
| 168 |
return space.newint(-1) |
| 169 |
|
| 170 |
@jit.elidable |
| 171 |
def normalize(encoding): |
| 172 |
""" Normalize an encoding name. |
| 173 |
|
| 174 |
Normalization works as follows: all non-alphanumeric |
| 175 |
characters except the dot used for Python package names are |
| 176 |
collapsed and replaced with a single underscore, e.g. ' -;#' |
| 177 |
becomes '_'. Leading and trailing underscores are removed. |
| 178 |
Also convert to lower case |
| 179 |
|
| 180 |
Note that encoding names should be ASCII only. |
| 181 |
|
| 182 |
""" |
| 183 |
chars = [] |
| 184 |
punct = False |
| 185 |
for c in encoding: |
| 186 |
if c.isalnum() or c == '.': |
| 187 |
if punct and chars: |
| 188 |
chars.append('_') |
| 189 |
if ord(c) <= 127: |
| 190 |
chars.append(c.lower()) |
| 191 |
punct = False |
| 192 |
else: |
| 193 |
punct = True |
| 194 |
return ''.join(chars) |
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
@unwrap_spec(encoding='text0') |
| 199 |
def lookup_codec(space, encoding): |
| 200 |
"""lookup(encoding) -> (encoder, decoder, stream_reader, stream_writer) |
| 201 |
Looks up a codec tuple in the Python codec registry and returns |
| 202 |
a tuple of functions. |
| 203 |
""" |
| 204 |
assert not (space.config.translating and not we_are_translated()), \ |
| 205 |
"lookup_codec() should not be called during translation" |
| 206 |
state = space.fromcache(CodecState) |
| 207 |
normalized_encoding = normalize(encoding) |
| 208 |
w_result = state.get_codec_from_cache(normalized_encoding) |
| 209 |
if w_result is not None: |
| 210 |
return w_result |
| 211 |
return _lookup_codec_loop(space, encoding, normalized_encoding) |
| 212 |
|
| 213 |
|
| 214 |
def _lookup_codec_loop(space, encoding, normalized_encoding): |
| 215 |
state = space.fromcache(CodecState) |
| 216 |
if state.codec_need_encodings: |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
w_import = space.getattr(space.builtin, space.newtext("__import__")) |
| 221 |
space.call_function(w_import, space.newtext("encodings")) |
| 222 |
from pypy.module.sys.interp_encoding import base_encoding |
| 223 |
|
| 224 |
normalized_base = base_encoding.replace("-", "_").lower() |
| 225 |
space.call_function(w_import, space.newtext("encodings." + |
| 226 |
normalized_base)) |
| 227 |
state.codec_need_encodings = False |
| 228 |
if len(state.codec_search_path) == 0: |
| 229 |
raise oefmt(space.w_LookupError, |
| 230 |
"no codec search functions registered: can't find " |
| 231 |
"encoding") |
| 232 |
w_v = space.newtext(normalized_encoding) |
| 233 |
for w_search in state.codec_search_path: |
| 234 |
w_result = space.call_function(w_search, w_v) |
| 235 |
if not space.is_w(w_result, space.w_None): |
| 236 |
if not (space.isinstance_w(w_result, space.w_tuple) and |
| 237 |
space.len_w(w_result) == 4): |
| 238 |
raise oefmt(space.w_TypeError, |
| 239 |
"codec search functions must return 4-tuples") |
| 240 |
else: |
| 241 |
state.codec_search_cache[normalized_encoding] = w_result |
| 242 |
state.modified() |
| 243 |
return w_result |
| 244 |
raise oefmt(space.w_LookupError, "unknown encoding: %s", encoding) |
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
def check_exception(space, w_exc): |
| 250 |
try: |
| 251 |
w_start = space.getattr(w_exc, space.newtext('start')) |
| 252 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 253 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 254 |
except OperationError as e: |
| 255 |
if not e.match(space, space.w_AttributeError): |
| 256 |
raise |
| 257 |
raise oefmt(space.w_TypeError, "wrong exception") |
| 258 |
|
| 259 |
delta = space.int_w(w_end) - space.int_w(w_start) |
| 260 |
if delta < 0 or not (space.isinstance_w(w_obj, space.w_bytes) or |
| 261 |
space.isinstance_w(w_obj, space.w_unicode)): |
| 262 |
raise oefmt(space.w_TypeError, "wrong exception") |
| 263 |
|
| 264 |
def strict_errors(space, w_exc): |
| 265 |
check_exception(space, w_exc) |
| 266 |
if space.isinstance_w(w_exc, space.w_BaseException): |
| 267 |
raise OperationError(space.type(w_exc), w_exc) |
| 268 |
else: |
| 269 |
raise oefmt(space.w_TypeError, "codec must pass exception instance") |
| 270 |
|
| 271 |
def ignore_errors(space, w_exc): |
| 272 |
check_exception(space, w_exc) |
| 273 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 274 |
return space.newtuple2(space.newutf8('', 0), w_end) |
| 275 |
|
| 276 |
REPLACEMENT = u'\ufffd'.encode('utf8') |
| 277 |
|
| 278 |
def replace_errors(space, w_exc): |
| 279 |
check_exception(space, w_exc) |
| 280 |
w_start = space.getattr(w_exc, space.newtext('start')) |
| 281 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 282 |
size = space.int_w(w_end) - space.int_w(w_start) |
| 283 |
if size < 0: |
| 284 |
size = 0 |
| 285 |
if space.isinstance_w(w_exc, space.w_UnicodeEncodeError): |
| 286 |
text = '?' * size |
| 287 |
return space.newtuple2(space.newutf8(text, size), w_end) |
| 288 |
elif space.isinstance_w(w_exc, space.w_UnicodeDecodeError): |
| 289 |
text = REPLACEMENT |
| 290 |
return space.newtuple2(space.newutf8(text, 1), w_end) |
| 291 |
elif space.isinstance_w(w_exc, space.w_UnicodeTranslateError): |
| 292 |
text = REPLACEMENT * size |
| 293 |
return space.newtuple2(space.newutf8(text, size), w_end) |
| 294 |
else: |
| 295 |
raise oefmt(space.w_TypeError, |
| 296 |
"don't know how to handle %T in error callback", w_exc) |
| 297 |
|
| 298 |
def xmlcharrefreplace_errors(space, w_exc): |
| 299 |
|
| 300 |
check_exception(space, w_exc) |
| 301 |
if space.isinstance_w(w_exc, space.w_UnicodeEncodeError): |
| 302 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 303 |
space.realutf8_w(w_obj) |
| 304 |
w_obj = space.convert_arg_to_w_unicode(w_obj) |
| 305 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 306 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 307 |
end = space.int_w(w_end) |
| 308 |
start = w_obj._index_to_byte(start) |
| 309 |
end = w_obj._index_to_byte(end) |
| 310 |
builder = StringBuilder() |
| 311 |
pos = start |
| 312 |
obj = w_obj._utf8 |
| 313 |
while pos < end: |
| 314 |
code = rutf8.codepoint_at_pos(obj, pos) |
| 315 |
builder.append("&#") |
| 316 |
builder.append(str(code)) |
| 317 |
builder.append(";") |
| 318 |
pos = rutf8.next_codepoint_pos(obj, pos) |
| 319 |
r = builder.build() |
| 320 |
lgt = rutf8.check_utf8(r, True) |
| 321 |
return space.newtuple2(space.newutf8(r, lgt), w_end) |
| 322 |
else: |
| 323 |
raise oefmt(space.w_TypeError, |
| 324 |
"don't know how to handle %T in error callback", w_exc) |
| 325 |
|
| 326 |
def backslashreplace_errors(space, w_exc): |
| 327 |
|
| 328 |
check_exception(space, w_exc) |
| 329 |
if (space.isinstance_w(w_exc, space.w_UnicodeEncodeError) or |
| 330 |
space.isinstance_w(w_exc, space.w_UnicodeTranslateError)): |
| 331 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 332 |
space.realutf8_w(w_obj) |
| 333 |
w_obj = space.convert_arg_to_w_unicode(w_obj) |
| 334 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 335 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 336 |
end = space.int_w(w_end) |
| 337 |
start = w_obj._index_to_byte(start) |
| 338 |
end = w_obj._index_to_byte(end) |
| 339 |
builder = StringBuilder() |
| 340 |
pos = start |
| 341 |
obj = w_obj._utf8 |
| 342 |
while pos < end: |
| 343 |
code = rutf8.codepoint_at_pos(obj, pos) |
| 344 |
unicodehelper.raw_unicode_escape_helper(builder, code) |
| 345 |
pos = rutf8.next_codepoint_pos(obj, pos) |
| 346 |
return space.newtuple([space.newtext(builder.build()), w_end]) |
| 347 |
elif space.isinstance_w(w_exc, space.w_UnicodeDecodeError): |
| 348 |
obj = space.bytes_w(space.getattr(w_exc, space.newtext('object'))) |
| 349 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 350 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 351 |
end = space.int_w(w_end) |
| 352 |
builder = StringBuilder() |
| 353 |
pos = start |
| 354 |
while pos < end: |
| 355 |
oc = ord(obj[pos]) |
| 356 |
unicodehelper.raw_unicode_escape_helper(builder, oc) |
| 357 |
pos += 1 |
| 358 |
return space.newtuple([space.newtext(builder.build()), w_end]) |
| 359 |
else: |
| 360 |
raise oefmt(space.w_TypeError, |
| 361 |
"don't know how to handle %T in error callback", w_exc) |
| 362 |
|
| 363 |
def namereplace_errors(space, w_exc): |
| 364 |
check_exception(space, w_exc) |
| 365 |
if space.isinstance_w(w_exc, space.w_UnicodeEncodeError): |
| 366 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 367 |
space.realutf8_w(w_obj) |
| 368 |
w_obj = space.convert_arg_to_w_unicode(w_obj) |
| 369 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 370 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 371 |
end = space.int_w(w_end) |
| 372 |
start = w_obj._index_to_byte(start) |
| 373 |
end = w_obj._index_to_byte(end) |
| 374 |
builder = StringBuilder() |
| 375 |
obj = w_obj._utf8 |
| 376 |
pos = start |
| 377 |
while pos < end: |
| 378 |
oc = rutf8.codepoint_at_pos(obj, pos) |
| 379 |
try: |
| 380 |
name = unicodedb.name(oc) |
| 381 |
except KeyError: |
| 382 |
unicodehelper.raw_unicode_escape_helper(builder, oc) |
| 383 |
else: |
| 384 |
builder.append('\\N{') |
| 385 |
builder.append(name) |
| 386 |
builder.append('}') |
| 387 |
pos = rutf8.next_codepoint_pos(obj, pos) |
| 388 |
r = builder.build() |
| 389 |
lgt = rutf8.check_utf8(r, True) |
| 390 |
return space.newtuple2(space.newutf8(r, lgt), w_end) |
| 391 |
else: |
| 392 |
raise oefmt(space.w_TypeError, |
| 393 |
"don't know how to handle %T in error callback", w_exc) |
| 394 |
|
| 395 |
|
| 396 |
(ENC_UNKNOWN, ENC_UTF8, |
| 397 |
ENC_UTF16BE, ENC_UTF16LE, |
| 398 |
ENC_UTF32BE, ENC_UTF32LE) = range(-1, 5) |
| 399 |
BIG_ENDIAN = sys.byteorder == 'big' |
| 400 |
|
| 401 |
STANDARD_ENCODINGS = { |
| 402 |
'utf8': (3, ENC_UTF8), |
| 403 |
'utf_8': (3, ENC_UTF8), |
| 404 |
'cp_utf8': (3, ENC_UTF8), |
| 405 |
'utf16': (2, ENC_UTF16BE) if BIG_ENDIAN else (2, ENC_UTF16LE), |
| 406 |
'utf_16': (2, ENC_UTF16BE) if BIG_ENDIAN else (2, ENC_UTF16LE), |
| 407 |
'utf16be': (2, ENC_UTF16BE), |
| 408 |
'utf_16be': (2, ENC_UTF16BE), |
| 409 |
'utf16_be': (2, ENC_UTF16BE), |
| 410 |
'utf_16_be': (2, ENC_UTF16BE), |
| 411 |
'utf16le': (2, ENC_UTF16LE), |
| 412 |
'utf_16le': (2, ENC_UTF16LE), |
| 413 |
'utf16_le': (2, ENC_UTF16LE), |
| 414 |
'utf_16_le': (2, ENC_UTF16LE), |
| 415 |
'utf32': (4, ENC_UTF32BE) if BIG_ENDIAN else (4, ENC_UTF32LE), |
| 416 |
'utf_32': (4, ENC_UTF32BE) if BIG_ENDIAN else (4, ENC_UTF32LE), |
| 417 |
'utf32be': (4, ENC_UTF32BE), |
| 418 |
'utf_32be': (4, ENC_UTF32BE), |
| 419 |
'utf32_be': (4, ENC_UTF32BE), |
| 420 |
'utf_32_be': (4, ENC_UTF32BE), |
| 421 |
'utf32le': (4, ENC_UTF32LE), |
| 422 |
'utf_32le': (4, ENC_UTF32LE), |
| 423 |
'utf32_le': (4, ENC_UTF32LE), |
| 424 |
'utf_32_le': (4, ENC_UTF32LE), |
| 425 |
} |
| 426 |
|
| 427 |
def get_standard_encoding(encoding): |
| 428 |
encoding = encoding.lower().replace('-', '_') |
| 429 |
return STANDARD_ENCODINGS.get(encoding, (0, ENC_UNKNOWN)) |
| 430 |
|
| 431 |
def surrogatepass_errors(space, w_exc): |
| 432 |
check_exception(space, w_exc) |
| 433 |
if space.isinstance_w(w_exc, space.w_UnicodeEncodeError): |
| 434 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 435 |
w_obj = space.convert_arg_to_w_unicode(w_obj) |
| 436 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 437 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 438 |
encoding = space.text_w(space.getattr(w_exc, space.newtext('encoding'))) |
| 439 |
bytelength, code = get_standard_encoding(encoding) |
| 440 |
if code == ENC_UNKNOWN: |
| 441 |
|
| 442 |
raise OperationError(space.type(w_exc), w_exc) |
| 443 |
end = space.int_w(w_end) |
| 444 |
builder = StringBuilder() |
| 445 |
start = w_obj._index_to_byte(start) |
| 446 |
end = w_obj._index_to_byte(end) |
| 447 |
obj = w_obj._utf8 |
| 448 |
pos = start |
| 449 |
while pos < end: |
| 450 |
ch = rutf8.codepoint_at_pos(obj, pos) |
| 451 |
pos = rutf8.next_codepoint_pos(obj, pos) |
| 452 |
if ch < 0xd800 or ch > 0xdfff: |
| 453 |
|
| 454 |
raise OperationError(space.type(w_exc), w_exc) |
| 455 |
if code == ENC_UTF8: |
| 456 |
builder.append(chr(0xe0 | (ch >> 12))) |
| 457 |
builder.append(chr(0x80 | ((ch >> 6) & 0x3f))) |
| 458 |
builder.append(chr(0x80 | (ch & 0x3f))) |
| 459 |
elif code == ENC_UTF16LE: |
| 460 |
builder.append(chr(ch & 0xff)) |
| 461 |
builder.append(chr(ch >> 8)) |
| 462 |
elif code == ENC_UTF16BE: |
| 463 |
builder.append(chr(ch >> 8)) |
| 464 |
builder.append(chr(ch & 0xff)) |
| 465 |
elif code == ENC_UTF32LE: |
| 466 |
builder.append(chr(ch & 0xff)) |
| 467 |
builder.append(chr(ch >> 8)) |
| 468 |
builder.append(chr(0)) |
| 469 |
builder.append(chr(0)) |
| 470 |
elif code == ENC_UTF32BE: |
| 471 |
builder.append(chr(0)) |
| 472 |
builder.append(chr(0)) |
| 473 |
builder.append(chr(ch >> 8)) |
| 474 |
builder.append(chr(ch & 0xff)) |
| 475 |
return space.newtuple([space.newbytes(builder.build()), w_end]) |
| 476 |
elif space.isinstance_w(w_exc, space.w_UnicodeDecodeError): |
| 477 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 478 |
obj = space.bytes_w(space.getattr(w_exc, space.newtext('object'))) |
| 479 |
encoding = space.text_w(space.getattr(w_exc, space.newtext('encoding'))) |
| 480 |
bytelength, code = get_standard_encoding(encoding) |
| 481 |
ch = 0 |
| 482 |
|
| 483 |
|
| 484 |
ch0 = ord(obj[start + 0]) if len(obj) > start + 0 else -1 |
| 485 |
ch1 = ord(obj[start + 1]) if len(obj) > start + 1 else -1 |
| 486 |
ch2 = ord(obj[start + 2]) if len(obj) > start + 2 else -1 |
| 487 |
ch3 = ord(obj[start + 3]) if len(obj) > start + 3 else -1 |
| 488 |
if code == ENC_UTF8: |
| 489 |
if (ch1 != -1 and ch2 != -1 and |
| 490 |
ch0 & 0xf0 == 0xe0 and |
| 491 |
ch1 & 0xc0 == 0x80 and |
| 492 |
ch2 & 0xc0 == 0x80): |
| 493 |
|
| 494 |
ch = ((ch0 & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f) |
| 495 |
elif code == ENC_UTF16LE: |
| 496 |
ch = (ch1 << 8) | ch0 |
| 497 |
elif code == ENC_UTF16BE: |
| 498 |
ch = (ch0 << 8) | ch1 |
| 499 |
elif code == ENC_UTF32LE: |
| 500 |
ch = (ch3 << 24) | (ch2 << 16) | (ch1 << 8) | ch0 |
| 501 |
elif code == ENC_UTF32BE: |
| 502 |
ch = (ch0 << 24) | (ch1 << 16) | (ch2 << 8) | ch3 |
| 503 |
if ch < 0xd800 or ch > 0xdfff: |
| 504 |
|
| 505 |
ch = 0 |
| 506 |
if ch == 0: |
| 507 |
raise OperationError(space.type(w_exc), w_exc) |
| 508 |
ch_utf8 = rutf8.unichr_as_utf8(ch, allow_surrogates=True) |
| 509 |
return space.newtuple([space.newtext(ch_utf8, 1), |
| 510 |
space.newint(start + bytelength)]) |
| 511 |
else: |
| 512 |
raise oefmt(space.w_TypeError, |
| 513 |
"don't know how to handle %T in error callback", w_exc) |
| 514 |
|
| 515 |
def surrogateescape_errors(space, w_exc): |
| 516 |
check_exception(space, w_exc) |
| 517 |
if space.isinstance_w(w_exc, space.w_UnicodeEncodeError): |
| 518 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 519 |
w_obj = space.convert_arg_to_w_unicode(w_obj) |
| 520 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 521 |
w_end = space.getattr(w_exc, space.newtext('end')) |
| 522 |
end = space.int_w(w_end) |
| 523 |
res = '' |
| 524 |
start = w_obj._index_to_byte(start) |
| 525 |
end = w_obj._index_to_byte(end) |
| 526 |
obj = w_obj._utf8 |
| 527 |
pos = start |
| 528 |
while pos < end: |
| 529 |
code = rutf8.codepoint_at_pos(obj, pos) |
| 530 |
if code < 0xdc80 or code > 0xdcff: |
| 531 |
|
| 532 |
raise OperationError(space.type(w_exc), w_exc) |
| 533 |
res += chr(code - 0xdc00) |
| 534 |
pos = rutf8.next_codepoint_pos(obj, pos) |
| 535 |
return space.newtuple([space.newbytes(res), w_end]) |
| 536 |
elif space.isinstance_w(w_exc, space.w_UnicodeDecodeError): |
| 537 |
consumed = 0 |
| 538 |
start = space.int_w(space.getattr(w_exc, space.newtext('start'))) |
| 539 |
end = space.int_w(space.getattr(w_exc, space.newtext('end'))) |
| 540 |
obj = space.bytes_w(space.getattr(w_exc, space.newtext('object'))) |
| 541 |
replace = u'' |
| 542 |
while consumed < 4 and consumed < end - start: |
| 543 |
c = ord(obj[start+consumed]) |
| 544 |
if c < 128: |
| 545 |
|
| 546 |
break |
| 547 |
replace += unichr(0xdc00 + c) |
| 548 |
consumed += 1 |
| 549 |
if not consumed: |
| 550 |
|
| 551 |
raise OperationError(space.type(w_exc), w_exc) |
| 552 |
replace_utf8 = runicode.unicode_encode_utf_8(replace, len(replace), |
| 553 |
'strict', allow_surrogates=True) |
| 554 |
return space.newtuple([space.newtext(replace_utf8, len(replace)), |
| 555 |
space.newint(start + consumed)]) |
| 556 |
else: |
| 557 |
raise oefmt(space.w_TypeError, |
| 558 |
"don't know how to handle %T in error callback", w_exc) |
| 559 |
|
| 560 |
@not_rpython |
| 561 |
def register_builtin_error_handlers(space): |
| 562 |
state = space.fromcache(CodecState) |
| 563 |
for error in ("strict", "ignore", "replace", "xmlcharrefreplace", |
| 564 |
"backslashreplace", "surrogateescape", "surrogatepass", |
| 565 |
"namereplace"): |
| 566 |
name = error + "_errors" |
| 567 |
state.codec_error_registry[error] = interp2app( |
| 568 |
globals()[name]).spacebind(space) |
| 569 |
|
| 570 |
|
| 571 |
def _wrap_codec_error(space, operr, action, encoding): |
| 572 |
|
| 573 |
|
| 574 |
message = "%s with '%s' codec failed" % (action, encoding) |
| 575 |
return operr.try_set_from_cause(space, message) |
| 576 |
|
| 577 |
def _call_codec(space, w_coder, w_obj, action, encoding, errors): |
| 578 |
try: |
| 579 |
if errors: |
| 580 |
w_res = space.call_function(w_coder, w_obj, space.newtext(errors)) |
| 581 |
else: |
| 582 |
w_res = space.call_function(w_coder, w_obj) |
| 583 |
except OperationError as operr: |
| 584 |
raise _wrap_codec_error(space, operr, action, encoding) |
| 585 |
if (not space.isinstance_w(w_res, space.w_tuple) or space.len_w(w_res) != 2): |
| 586 |
if action[:2] == 'en': |
| 587 |
raise oefmt(space.w_TypeError, |
| 588 |
"encoder must return a tuple (object, integer)") |
| 589 |
elif action[:2] == 'de': |
| 590 |
raise oefmt(space.w_TypeError, |
| 591 |
"decoder must return a tuple (object, integer)") |
| 592 |
else: |
| 593 |
raise oefmt(space.w_TypeError, |
| 594 |
"%s must return a tuple (object, integer)", action) |
| 595 |
return space.getitem(w_res, space.newint(0)) |
| 596 |
|
| 597 |
@unwrap_spec(errors='text0') |
| 598 |
def lookup_error(space, errors): |
| 599 |
"""lookup_error(errors) -> handler |
| 600 |
|
| 601 |
Return the error handler for the specified error handling name |
| 602 |
or raise a LookupError, if no handler exists under this name. |
| 603 |
""" |
| 604 |
|
| 605 |
state = space.fromcache(CodecState) |
| 606 |
try: |
| 607 |
w_err_handler = state.codec_error_registry[errors] |
| 608 |
except KeyError: |
| 609 |
raise oefmt(space.w_LookupError, |
| 610 |
"unknown error handler name %s", errors) |
| 611 |
return w_err_handler |
| 612 |
|
| 613 |
|
| 614 |
@unwrap_spec(encoding='text_or_none', errors='text_or_none') |
| 615 |
def encode(space, w_obj, encoding=None, errors=None): |
| 616 |
"""encode(obj, [encoding[,errors]]) -> object |
| 617 |
|
| 618 |
Encodes obj using the codec registered for encoding. encoding defaults |
| 619 |
to the default encoding. errors may be given to set a different error |
| 620 |
handling scheme. Default is 'strict' meaning that encoding errors raise |
| 621 |
a ValueError. Other possible values are 'ignore', 'replace' and |
| 622 |
'xmlcharrefreplace' as well as any other name registered with |
| 623 |
codecs.register_error that can handle ValueErrors. |
| 624 |
""" |
| 625 |
if encoding is None: |
| 626 |
encoding = space.sys.defaultencoding |
| 627 |
w_encoder = space.getitem(lookup_codec(space, encoding), space.newint(0)) |
| 628 |
return _call_codec(space, w_encoder, w_obj, "encoding", encoding, errors) |
| 629 |
|
| 630 |
@unwrap_spec(errors='text_or_none') |
| 631 |
def readbuffer_encode(space, w_data, errors='strict'): |
| 632 |
s = space.getarg_w('s#', w_data) |
| 633 |
return space.newtuple2(space.newbytes(s), space.newint(len(s))) |
| 634 |
|
| 635 |
@unwrap_spec(encoding='text_or_none', errors='text_or_none') |
| 636 |
def decode(space, w_obj, encoding=None, errors=None): |
| 637 |
from pypy.objspace.std.unicodeobject import W_UnicodeObject |
| 638 |
"""decode(obj, [encoding[,errors]]) -> object |
| 639 |
|
| 640 |
Decodes obj using the codec registered for encoding. encoding defaults |
| 641 |
to the default encoding. errors may be given to set a different error |
| 642 |
handling scheme. Default is 'strict' meaning that encoding errors raise |
| 643 |
a ValueError. Other possible values are 'ignore' and 'replace' |
| 644 |
as well as any other name registered with codecs.register_error that is |
| 645 |
able to handle ValueErrors. |
| 646 |
""" |
| 647 |
if encoding is None: |
| 648 |
encoding = space.sys.defaultencoding |
| 649 |
w_decoder = space.getitem(lookup_codec(space, encoding), space.newint(1)) |
| 650 |
return _call_codec(space, w_decoder, w_obj, "decoding", encoding, errors) |
| 651 |
|
| 652 |
@unwrap_spec(errors='text') |
| 653 |
def register_error(space, errors, w_handler): |
| 654 |
"""register_error(errors, handler) |
| 655 |
|
| 656 |
Register the specified error handler under the name |
| 657 |
errors. handler must be a callable object, that |
| 658 |
will be called with an exception instance containing |
| 659 |
information about the location of the encoding/decoding |
| 660 |
error and must return a (replacement, new position) tuple. |
| 661 |
""" |
| 662 |
state = space.fromcache(CodecState) |
| 663 |
if space.is_true(space.callable(w_handler)): |
| 664 |
state.codec_error_registry[errors] = w_handler |
| 665 |
else: |
| 666 |
raise oefmt(space.w_TypeError, "handler must be callable") |
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
def lookup_text_codec(space, action, encoding): |
| 671 |
w_codec_info = lookup_codec(space, encoding) |
| 672 |
try: |
| 673 |
is_text_encoding = space.is_true( |
| 674 |
space.getattr(w_codec_info, space.newtext('_is_text_encoding'))) |
| 675 |
except OperationError as e: |
| 676 |
if e.match(space, space.w_AttributeError): |
| 677 |
is_text_encoding = True |
| 678 |
else: |
| 679 |
raise |
| 680 |
if not is_text_encoding: |
| 681 |
raise oefmt(space.w_LookupError, |
| 682 |
"'%s' is not a text encoding; " |
| 683 |
"use codecs.%s() to handle arbitrary codecs", encoding, action) |
| 684 |
return w_codec_info |
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
def _find_implementation(impl_name): |
| 689 |
func = getattr(unicodehelper, impl_name) |
| 690 |
return func |
| 691 |
|
| 692 |
def make_encoder_wrapper(name): |
| 693 |
rname = "utf8_encode_%s" % (name.replace("_encode", ""), ) |
| 694 |
func = _find_implementation(rname) |
| 695 |
@unwrap_spec(errors='text_or_none') |
| 696 |
def wrap_encoder(space, w_arg, errors="strict"): |
| 697 |
|
| 698 |
w_arg = space.convert_arg_to_w_unicode(w_arg, errors) |
| 699 |
if errors is None: |
| 700 |
errors = 'strict' |
| 701 |
allow_surrogates = False |
| 702 |
if errors in ('surrogatepass',): |
| 703 |
allow_surrogates = True |
| 704 |
state = space.fromcache(CodecState) |
| 705 |
ulen = w_arg._length |
| 706 |
result = func(space, w_arg._utf8, w_arg, errors, state.encode_error_handler, |
| 707 |
allow_surrogates=allow_surrogates) |
| 708 |
return space.newtuple2(space.newbytes(result), space.newint(ulen)) |
| 709 |
wrap_encoder.__name__ = func.__name__ |
| 710 |
globals()[name] = wrap_encoder |
| 711 |
|
| 712 |
def make_decoder_wrapper(name): |
| 713 |
rname = "str_decode_%s" % (name.replace("_decode", ""), ) |
| 714 |
func = _find_implementation(rname) |
| 715 |
@unwrap_spec(string='bufferstr', errors='text_or_none', |
| 716 |
w_final=WrappedDefault(False)) |
| 717 |
def wrap_decoder(space, string, errors="strict", w_final=None): |
| 718 |
if errors is None: |
| 719 |
errors = 'strict' |
| 720 |
final = space.is_true(w_final) |
| 721 |
state = space.fromcache(CodecState) |
| 722 |
w_str = space.newbytes(string) |
| 723 |
result, length, pos = func(space, string, w_str, errors, final, state.decode_error_handler) |
| 724 |
|
| 725 |
return space.newtuple2(space.newutf8(result, length), space.newint(pos)) |
| 726 |
wrap_decoder.__name__ = func.__name__ |
| 727 |
globals()[name] = wrap_decoder |
| 728 |
|
| 729 |
for encoder in [ |
| 730 |
"ascii_encode", |
| 731 |
"latin_1_encode", |
| 732 |
"utf_7_encode", |
| 733 |
"utf_16_encode", |
| 734 |
"utf_16_be_encode", |
| 735 |
"utf_16_le_encode", |
| 736 |
"utf_32_encode", |
| 737 |
"utf_32_be_encode", |
| 738 |
"utf_32_le_encode", |
| 739 |
"unicode_escape_encode", |
| 740 |
"raw_unicode_escape_encode", |
| 741 |
]: |
| 742 |
make_encoder_wrapper(encoder) |
| 743 |
|
| 744 |
for decoder in [ |
| 745 |
"ascii_decode", |
| 746 |
"latin_1_decode", |
| 747 |
"utf_7_decode", |
| 748 |
"utf_16_decode", |
| 749 |
"utf_16_be_decode", |
| 750 |
"utf_16_le_decode", |
| 751 |
"utf_32_decode", |
| 752 |
"utf_32_be_decode", |
| 753 |
"utf_32_le_decode", |
| 754 |
"raw_unicode_escape_decode", |
| 755 |
]: |
| 756 |
make_decoder_wrapper(decoder) |
| 757 |
|
| 758 |
if getattr(unicodehelper, '_WIN32', False): |
| 759 |
make_encoder_wrapper('mbcs_encode') |
| 760 |
make_decoder_wrapper('mbcs_decode') |
| 761 |
make_encoder_wrapper('oem_encode') |
| 762 |
make_decoder_wrapper('oem_decode') |
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
@unwrap_spec(code_page=int, errors='text_or_none') |
| 767 |
def code_page_encode(space, code_page, w_arg, errors="strict"): |
| 768 |
|
| 769 |
if code_page < 0: |
| 770 |
raise oefmt(space.w_ValueError, "invalid code page number %d", |
| 771 |
code_page) |
| 772 |
w_arg = space.convert_arg_to_w_unicode(w_arg, errors) |
| 773 |
if errors is None: |
| 774 |
errors = 'strict' |
| 775 |
allow_surrogates = False |
| 776 |
if errors in ('surrogatepass',): |
| 777 |
allow_surrogates = True |
| 778 |
state = space.fromcache(CodecState) |
| 779 |
ulen = w_arg._length |
| 780 |
try: |
| 781 |
result = unicodehelper.utf8_encode_code_page(space, code_page, |
| 782 |
w_arg._utf8, w_arg, |
| 783 |
errors, state.encode_error_handler, |
| 784 |
allow_surrogates=allow_surrogates) |
| 785 |
except OSError as e: |
| 786 |
raise wrap_oserror(space, e) |
| 787 |
return space.newtuple([space.newbytes(result), space.newint(ulen)]) |
| 788 |
|
| 789 |
@unwrap_spec(code_page=int, string='bufferstr', errors='text_or_none', |
| 790 |
w_final=WrappedDefault(False)) |
| 791 |
def code_page_decode(space, code_page, string, errors="strict", w_final=None): |
| 792 |
if code_page < 0: |
| 793 |
raise oefmt(space.w_ValueError, "invalid code page number %d", |
| 794 |
code_page) |
| 795 |
if errors is None: |
| 796 |
errors = 'strict' |
| 797 |
final = space.is_true(w_final) |
| 798 |
state = space.fromcache(CodecState) |
| 799 |
try: |
| 800 |
w_s = space.newbytes(string) |
| 801 |
result, pos, length = unicodehelper.str_decode_code_page(space, code_page, |
| 802 |
string, w_s, errors, final, |
| 803 |
state.decode_error_handler) |
| 804 |
except OSError as e: |
| 805 |
raise wrap_oserror(space, e) |
| 806 |
|
| 807 |
return space.newtuple([space.newutf8(result, length), space.newint(len(string))]) |
| 808 |
|
| 809 |
def utf8_encode_wrapper(space, utf8, w_obj, errors): |
| 810 |
state = space.fromcache(CodecState) |
| 811 |
return unicodehelper.utf8_encode_utf_8(space, utf8, w_obj, errors, |
| 812 |
state.encode_error_handler, allow_surrogates=False) |
| 813 |
|
| 814 |
|
| 815 |
|
| 816 |
@unwrap_spec(errors='text_or_none') |
| 817 |
def utf_8_encode(space, w_obj, errors="strict"): |
| 818 |
utf8, lgt = space.utf8_len_w(w_obj) |
| 819 |
if lgt == len(utf8): |
| 820 |
return space.newtuple2(space.newbytes(utf8), space.newint(lgt)) |
| 821 |
if errors is None: |
| 822 |
errors = 'strict' |
| 823 |
result = utf8_encode_wrapper(space, utf8, w_obj, errors) |
| 824 |
if errors == 'strict': |
| 825 |
|
| 826 |
|
| 827 |
jit.record_known_result(lgt, rutf8._check_utf8, utf8, False, 0, -1) |
| 828 |
return space.newtuple2(space.newbytes(result), space.newint(lgt)) |
| 829 |
|
| 830 |
@unwrap_spec(string='bufferstr', errors='text_or_none', |
| 831 |
w_final = WrappedDefault(False)) |
| 832 |
def utf_8_decode(space, string, errors="strict", w_final=None): |
| 833 |
if errors is None: |
| 834 |
errors = 'strict' |
| 835 |
final = space.is_true(w_final) |
| 836 |
state = space.fromcache(CodecState) |
| 837 |
if errors == 'surrogatepass': |
| 838 |
allow_surrogates = True |
| 839 |
else: |
| 840 |
allow_surrogates = False |
| 841 |
w_string = space.newbytes(string) |
| 842 |
res, lgt, pos = unicodehelper.str_decode_utf8(space, string, w_string, |
| 843 |
errors, final, state.decode_error_handler, allow_surrogates=allow_surrogates) |
| 844 |
return space.newtuple2(space.newutf8(res, lgt), |
| 845 |
space.newint(pos)) |
| 846 |
|
| 847 |
@unwrap_spec(data='bufferstr', errors='text_or_none', byteorder=int, |
| 848 |
w_final=WrappedDefault(False)) |
| 849 |
def utf_16_ex_decode(space, data, errors='strict', byteorder=0, w_final=None): |
| 850 |
if errors is None: |
| 851 |
errors = 'strict' |
| 852 |
final = space.is_true(w_final) |
| 853 |
state = space.fromcache(CodecState) |
| 854 |
if byteorder == 0: |
| 855 |
_byteorder = 'native' |
| 856 |
elif byteorder == -1: |
| 857 |
_byteorder = 'little' |
| 858 |
else: |
| 859 |
_byteorder = 'big' |
| 860 |
w_data = space.newbytes(data) |
| 861 |
res, lgt, pos, bo = unicodehelper.str_decode_utf_16_helper( |
| 862 |
space, data, w_data, errors, final, |
| 863 |
state.decode_error_handler, _byteorder) |
| 864 |
|
| 865 |
return space.newtuple([space.newutf8(res, lgt), |
| 866 |
space.newint(pos), space.newint(bo)]) |
| 867 |
|
| 868 |
@unwrap_spec(data='bufferstr', errors='text_or_none', byteorder=int, |
| 869 |
w_final=WrappedDefault(False)) |
| 870 |
def utf_32_ex_decode(space, data, errors='strict', byteorder=0, w_final=None): |
| 871 |
final = space.is_true(w_final) |
| 872 |
state = space.fromcache(CodecState) |
| 873 |
if byteorder == 0: |
| 874 |
_byteorder = 'native' |
| 875 |
elif byteorder == -1: |
| 876 |
_byteorder = 'little' |
| 877 |
else: |
| 878 |
_byteorder = 'big' |
| 879 |
w_data = space.newbytes(data) |
| 880 |
res, lgt, pos, bo = unicodehelper.str_decode_utf_32_helper( |
| 881 |
space, data, w_data, errors, final, |
| 882 |
state.decode_error_handler, _byteorder) |
| 883 |
|
| 884 |
return space.newtuple([space.newutf8(res, lgt), |
| 885 |
space.newint(pos), space.newint(bo)]) |
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
class Charmap_Decode: |
| 891 |
def __init__(self, space, w_mapping): |
| 892 |
self.space = space |
| 893 |
self.w_mapping = w_mapping |
| 894 |
|
| 895 |
|
| 896 |
if space.isinstance_w(w_mapping, space.w_tuple): |
| 897 |
self.mapping_w = space.fixedview(w_mapping) |
| 898 |
else: |
| 899 |
self.mapping_w = None |
| 900 |
|
| 901 |
def get(self, ch, errorchar): |
| 902 |
space = self.space |
| 903 |
|
| 904 |
|
| 905 |
if self.mapping_w is not None: |
| 906 |
w_ch = self.mapping_w[ch] |
| 907 |
else: |
| 908 |
try: |
| 909 |
w_ch = space.getitem(self.w_mapping, space.newint(ch)) |
| 910 |
except OperationError as e: |
| 911 |
if not e.match(space, space.w_LookupError): |
| 912 |
raise |
| 913 |
return errorchar |
| 914 |
|
| 915 |
if space.isinstance_w(w_ch, space.w_unicode): |
| 916 |
|
| 917 |
return space.utf8_w(w_ch) |
| 918 |
elif space.isinstance_w(w_ch, space.w_int): |
| 919 |
|
| 920 |
x = space.int_w(w_ch) |
| 921 |
if not 0 <= x <= 0x10FFFF: |
| 922 |
raise oefmt(space.w_TypeError, |
| 923 |
"character mapping must be in range(0x110000)") |
| 924 |
return rutf8.unichr_as_utf8(x, allow_surrogates=True) |
| 925 |
elif space.is_w(w_ch, space.w_None): |
| 926 |
|
| 927 |
return errorchar |
| 928 |
|
| 929 |
raise oefmt(space.w_TypeError, |
| 930 |
"character mapping must return integer, None or str") |
| 931 |
|
| 932 |
class Charmap_Encode: |
| 933 |
def __init__(self, space, w_mapping): |
| 934 |
self.space = space |
| 935 |
self.w_mapping = w_mapping |
| 936 |
|
| 937 |
def get(self, ch, errorchar): |
| 938 |
space = self.space |
| 939 |
|
| 940 |
|
| 941 |
try: |
| 942 |
w_ch = space.getitem(self.w_mapping, space.newint(ch)) |
| 943 |
except OperationError as e: |
| 944 |
if not e.match(space, space.w_LookupError): |
| 945 |
raise |
| 946 |
return errorchar |
| 947 |
|
| 948 |
if space.isinstance_w(w_ch, space.w_bytes): |
| 949 |
|
| 950 |
return space.bytes_w(w_ch) |
| 951 |
elif space.isinstance_w(w_ch, space.w_int): |
| 952 |
|
| 953 |
x = space.int_w(w_ch) |
| 954 |
if not 0 <= x < 256: |
| 955 |
raise oefmt(space.w_TypeError, |
| 956 |
"character mapping must be in range(256)") |
| 957 |
return chr(x) |
| 958 |
elif space.is_w(w_ch, space.w_None): |
| 959 |
|
| 960 |
return errorchar |
| 961 |
|
| 962 |
raise oefmt(space.w_TypeError, |
| 963 |
"character mapping must return integer, bytes or None, not str") |
| 964 |
|
| 965 |
|
| 966 |
@unwrap_spec(string='bufferstr', errors='text_or_none') |
| 967 |
def charmap_decode(space, string, errors="strict", w_mapping=None): |
| 968 |
if errors is None: |
| 969 |
errors = 'strict' |
| 970 |
if len(string) == 0: |
| 971 |
return space.newtuple2(space.newutf8('', 0), |
| 972 |
space.newint(0)) |
| 973 |
|
| 974 |
if space.is_none(w_mapping): |
| 975 |
mapping = None |
| 976 |
else: |
| 977 |
mapping = Charmap_Decode(space, w_mapping) |
| 978 |
|
| 979 |
final = True |
| 980 |
state = space.fromcache(CodecState) |
| 981 |
w_string = space.newbytes(string) |
| 982 |
result, lgt, pos = unicodehelper.str_decode_charmap( |
| 983 |
space, string, w_string, errors, final, |
| 984 |
state.decode_error_handler, mapping) |
| 985 |
return space.newtuple2(space.newutf8(result, lgt), |
| 986 |
space.newint(len(string))) |
| 987 |
|
| 988 |
@unwrap_spec(errors='text_or_none') |
| 989 |
def charmap_encode(space, w_unicode, errors="strict", w_mapping=None): |
| 990 |
if errors is None: |
| 991 |
errors = 'strict' |
| 992 |
if space.is_none(w_mapping): |
| 993 |
mapping = None |
| 994 |
else: |
| 995 |
mapping = Charmap_Encode(space, w_mapping) |
| 996 |
|
| 997 |
state = space.fromcache(CodecState) |
| 998 |
w_uni = space.convert_arg_to_w_unicode(w_unicode) |
| 999 |
result = unicodehelper.utf8_encode_charmap( |
| 1000 |
space, space.utf8_w(w_uni), w_uni, errors, |
| 1001 |
state.encode_error_handler, mapping) |
| 1002 |
return space.newtuple2(space.newbytes(result), space.newint(w_uni._len())) |
| 1003 |
|
| 1004 |
|
| 1005 |
@unwrap_spec(chars='utf8') |
| 1006 |
def charmap_build(space, chars): |
| 1007 |
|
| 1008 |
w_charmap = space.newdict() |
| 1009 |
pos = 0 |
| 1010 |
num = 0 |
| 1011 |
while pos < len(chars): |
| 1012 |
w_char = space.newint(rutf8.codepoint_at_pos(chars, pos)) |
| 1013 |
space.setitem(w_charmap, w_char, space.newint(num)) |
| 1014 |
pos = rutf8.next_codepoint_pos(chars, pos) |
| 1015 |
num += 1 |
| 1016 |
return w_charmap |
| 1017 |
|
| 1018 |
|
| 1019 |
|
| 1020 |
|
| 1021 |
class UnicodeData_Handler: |
| 1022 |
def __init__(self, space, w_getcode): |
| 1023 |
self.space = space |
| 1024 |
self.w_getcode = w_getcode |
| 1025 |
|
| 1026 |
def call(self, name): |
| 1027 |
space = self.space |
| 1028 |
try: |
| 1029 |
w_code = space.call_function(self.w_getcode, space.newtext(name)) |
| 1030 |
except OperationError as e: |
| 1031 |
if not e.match(space, space.w_KeyError): |
| 1032 |
raise |
| 1033 |
return -1 |
| 1034 |
return space.int_w(w_code) |
| 1035 |
|
| 1036 |
@unwrap_spec(errors='text_or_none', w_final=WrappedDefault(True)) |
| 1037 |
def unicode_escape_decode(space, w_string, errors="strict", w_final=None): |
| 1038 |
string = space.getarg_w('s*', w_string).as_str() |
| 1039 |
|
| 1040 |
|
| 1041 |
if errors is None: |
| 1042 |
errors = 'strict' |
| 1043 |
final = space.is_true(w_final) |
| 1044 |
state = space.fromcache(CodecState) |
| 1045 |
|
| 1046 |
unicode_name_handler = state.get_unicodedata_handler(space) |
| 1047 |
|
| 1048 |
w_s = space.newbytes(string) |
| 1049 |
result, u_len, lgt, first_escape_error_char = unicodehelper.str_decode_unicode_escape( |
| 1050 |
space, string, w_s, errors, |
| 1051 |
final, state.decode_error_handler, |
| 1052 |
unicode_name_handler) |
| 1053 |
|
| 1054 |
if first_escape_error_char is not None: |
| 1055 |
|
| 1056 |
|
| 1057 |
|
| 1058 |
if len(first_escape_error_char) == 3: |
| 1059 |
msg = "invalid octal escape sequence '\\%s'" % (first_escape_error_char,) |
| 1060 |
elif ' ' <= first_escape_error_char <= '\x7f': |
| 1061 |
msg = "invalid escape sequence '\\%s'" % (first_escape_error_char,) |
| 1062 |
else: |
| 1063 |
msg = "invalid escape sequence: '\\' followed by %s" % ( |
| 1064 |
space.text_w(space.repr( |
| 1065 |
space.newbytes(first_escape_error_char))),) |
| 1066 |
space.warn( |
| 1067 |
space.newtext(msg), |
| 1068 |
space.w_DeprecationWarning |
| 1069 |
) |
| 1070 |
return space.newtuple2(space.newutf8(result, u_len), space.newint(lgt)) |
| 1071 |
|
| 1072 |
|
| 1073 |
|
| 1074 |
|
| 1075 |
@unwrap_spec(errors='text_or_none', w_final=WrappedDefault(True)) |
| 1076 |
def raw_unicode_escape_decode(space, w_string, errors="strict", w_final=None): |
| 1077 |
string = space.getarg_w('s*', w_string).as_str() |
| 1078 |
if errors is None: |
| 1079 |
errors = 'strict' |
| 1080 |
final = space.is_true(w_final) |
| 1081 |
state = space.fromcache(CodecState) |
| 1082 |
w_s = space.newbytes(string) |
| 1083 |
result, u_len, lgt = unicodehelper.str_decode_raw_unicode_escape( |
| 1084 |
space, string, w_s, errors, final, state.decode_error_handler) |
| 1085 |
return space.newtuple2(space.newtext(result), space.newint(lgt)) |
| 1086 |
|
| 1087 |
|
| 1088 |
|
| 1089 |
|
| 1090 |
|
| 1091 |
|
| 1092 |
|
| 1093 |
|
| 1094 |
@unwrap_spec(data='bytes', errors='text_or_none') |
| 1095 |
def escape_encode(space, data, errors='strict'): |
| 1096 |
from pypy.objspace.std.bytesobject import string_escape_encode |
| 1097 |
result = string_escape_encode(data, False) |
| 1098 |
return space.newtuple([space.newbytes(result), space.newint(len(data))]) |
| 1099 |
|
| 1100 |
@unwrap_spec(errors='text_or_none') |
| 1101 |
def escape_decode(space, w_data, errors='strict'): |
| 1102 |
data = space.getarg_w('s#', w_data) |
| 1103 |
from pypy.interpreter.pyparser.parsestring import PyString_DecodeEscape |
| 1104 |
result, _ = PyString_DecodeEscape(space, data, errors, None) |
| 1105 |
|
| 1106 |
return space.newtuple2(space.newbytes(result), space.newint(len(data))) |