| 1 |
from rpython.rlib.rstring import StringBuilder |
| 2 |
from rpython.rlib.rutf8 import Utf8StringIterator, Utf8StringPosIterator |
| 3 |
from rpython.rlib.rfloat import isfinite, formatd, DTSF_ADD_DOT_0 |
| 4 |
from pypy.interpreter.error import oefmt, OperationError |
| 5 |
from pypy.interpreter.baseobjspace import W_Root |
| 6 |
from pypy.interpreter.typedef import TypeDef |
| 7 |
from pypy.interpreter.gateway import interp2app, unwrap_spec |
| 8 |
from pypy.interpreter.typedef import interp_attrproperty |
| 9 |
|
| 10 |
HEX = '0123456789abcdef' |
| 11 |
|
| 12 |
ESCAPE_DICT = { |
| 13 |
'\b': '\\b', |
| 14 |
'\f': '\\f', |
| 15 |
'\n': '\\n', |
| 16 |
'\r': '\\r', |
| 17 |
'\t': '\\t', |
| 18 |
} |
| 19 |
ESCAPE_BEFORE_SPACE = [ESCAPE_DICT.get(chr(_i), '\\u%04x' % _i) |
| 20 |
for _i in range(32)] |
| 21 |
|
| 22 |
|
| 23 |
def raw_encode_basestring_ascii(space, w_unicode): |
| 24 |
u = space.utf8_w(w_unicode) |
| 25 |
for i in range(len(u)): |
| 26 |
c = ord(u[i]) |
| 27 |
if c < 32 or c > 126 or c == ord('\\') or c == ord('"'): |
| 28 |
break |
| 29 |
else: |
| 30 |
|
| 31 |
return w_unicode |
| 32 |
|
| 33 |
sb = StringBuilder(len(u) + 20) |
| 34 |
_append_str_ascii_helper(sb, u) |
| 35 |
res = sb.build() |
| 36 |
return space.newtext(res) |
| 37 |
|
| 38 |
|
| 39 |
def _append_str_ascii(sb, u): |
| 40 |
"""Append a JSON-encoded string (with quotes) escaping all non-ASCII.""" |
| 41 |
sb.append('"') |
| 42 |
_append_str_ascii_helper(sb, u) |
| 43 |
sb.append('"') |
| 44 |
|
| 45 |
def _append_str_ascii_helper(sb, u): |
| 46 |
for c in Utf8StringIterator(u): |
| 47 |
if c <= ord('~'): |
| 48 |
if c == ord('"') or c == ord('\\'): |
| 49 |
sb.append('\\') |
| 50 |
elif c < ord(' '): |
| 51 |
sb.append(ESCAPE_BEFORE_SPACE[c]) |
| 52 |
continue |
| 53 |
sb.append(chr(c)) |
| 54 |
else: |
| 55 |
if c <= ord(u'\uffff'): |
| 56 |
sb.append('\\u') |
| 57 |
sb.append(HEX[c >> 12]) |
| 58 |
sb.append(HEX[(c >> 8) & 0x0f]) |
| 59 |
sb.append(HEX[(c >> 4) & 0x0f]) |
| 60 |
sb.append(HEX[c & 0x0f]) |
| 61 |
else: |
| 62 |
|
| 63 |
n = c - 0x10000 |
| 64 |
s1 = 0xd800 | ((n >> 10) & 0x3ff) |
| 65 |
sb.append('\\ud') |
| 66 |
sb.append(HEX[(s1 >> 8) & 0x0f]) |
| 67 |
sb.append(HEX[(s1 >> 4) & 0x0f]) |
| 68 |
sb.append(HEX[s1 & 0x0f]) |
| 69 |
s2 = 0xdc00 | (n & 0x3ff) |
| 70 |
sb.append('\\ud') |
| 71 |
sb.append(HEX[(s2 >> 8) & 0x0f]) |
| 72 |
sb.append(HEX[(s2 >> 4) & 0x0f]) |
| 73 |
sb.append(HEX[s2 & 0x0f]) |
| 74 |
|
| 75 |
def _append_str_unicode(sb, u): |
| 76 |
"""Append a JSON-encoded string (with quotes) preserving non-ASCII chars.""" |
| 77 |
sb.append('"') |
| 78 |
for c, pos in Utf8StringPosIterator(u): |
| 79 |
if c <= ord('~'): |
| 80 |
if c == ord('"') or c == ord('\\'): |
| 81 |
sb.append('\\') |
| 82 |
elif c < ord(' '): |
| 83 |
sb.append(ESCAPE_BEFORE_SPACE[c]) |
| 84 |
continue |
| 85 |
sb.append(chr(c)) |
| 86 |
else: |
| 87 |
|
| 88 |
b0 = ord(u[pos]) |
| 89 |
if b0 < 0xE0: |
| 90 |
sb.append(u[pos:pos + 2]) |
| 91 |
elif b0 < 0xF0: |
| 92 |
sb.append(u[pos:pos + 3]) |
| 93 |
else: |
| 94 |
sb.append(u[pos:pos + 4]) |
| 95 |
sb.append('"') |
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
FAST_ENCODE_ASCII = 0 |
| 100 |
FAST_ENCODE_UNICODE = 1 |
| 101 |
FAST_ENCODE_CUSTOM = 2 |
| 102 |
|
| 103 |
|
| 104 |
class W_Encoder(W_Root): |
| 105 |
"""RPython JSON encoder returned by make_encoder().""" |
| 106 |
|
| 107 |
def __init__(self, space, w_markers, w_default, w_str_encoder, |
| 108 |
key_separator, item_separator, sort_keys, skipkeys, |
| 109 |
allow_nan, fast_encode_mode): |
| 110 |
self.space = space |
| 111 |
self.w_markers = w_markers |
| 112 |
self.w_default = w_default |
| 113 |
self.w_str_encoder = w_str_encoder |
| 114 |
self.key_separator = key_separator |
| 115 |
self.item_separator = item_separator |
| 116 |
self.sort_keys = sort_keys |
| 117 |
self.skipkeys = skipkeys |
| 118 |
self.allow_nan = allow_nan |
| 119 |
self.fast_encode_mode = fast_encode_mode |
| 120 |
|
| 121 |
@unwrap_spec(indent_level=int) |
| 122 |
def descr_call(self, space, w_obj, indent_level=0): |
| 123 |
sb = StringBuilder() |
| 124 |
self._encode(sb, w_obj) |
| 125 |
return space.newlist([space.newtext(sb.build())]) |
| 126 |
|
| 127 |
def _encode_float(self, sb, f): |
| 128 |
if not isfinite(f): |
| 129 |
if f > 0.0: |
| 130 |
text = 'Infinity' |
| 131 |
elif f < 0.0: |
| 132 |
text = '-Infinity' |
| 133 |
else: |
| 134 |
text = 'NaN' |
| 135 |
if not self.allow_nan: |
| 136 |
raise oefmt(self.space.w_ValueError, |
| 137 |
"Out of range float values are not JSON compliant: %s", text) |
| 138 |
sb.append(text) |
| 139 |
else: |
| 140 |
sb.append(formatd(f, 'r', 0, DTSF_ADD_DOT_0)) |
| 141 |
|
| 142 |
def _encode_str(self, sb, w_str): |
| 143 |
"""Encode a W_Unicode string into sb, respecting fast_encode_mode.""" |
| 144 |
space = self.space |
| 145 |
mode = self.fast_encode_mode |
| 146 |
if mode == FAST_ENCODE_ASCII: |
| 147 |
_append_str_ascii(sb, space.utf8_w(w_str)) |
| 148 |
elif mode == FAST_ENCODE_UNICODE: |
| 149 |
_append_str_unicode(sb, space.utf8_w(w_str)) |
| 150 |
else: |
| 151 |
|
| 152 |
w_encoded = space.call_function(self.w_str_encoder, w_str) |
| 153 |
sb.append(space.utf8_w(w_encoded)) |
| 154 |
|
| 155 |
def _encode(self, sb, w_obj): |
| 156 |
space = self.space |
| 157 |
if space.is_w(w_obj, space.w_None): |
| 158 |
sb.append('null') |
| 159 |
elif space.is_w(w_obj, space.w_True): |
| 160 |
sb.append('true') |
| 161 |
elif space.is_w(w_obj, space.w_False): |
| 162 |
sb.append('false') |
| 163 |
elif space.isinstance_w(w_obj, space.w_unicode): |
| 164 |
self._encode_str(sb, w_obj) |
| 165 |
elif space.isinstance_w(w_obj, space.w_int): |
| 166 |
|
| 167 |
sb.append(space.text_w(space.call_method(space.w_int, '__repr__', w_obj))) |
| 168 |
elif space.isinstance_w(w_obj, space.w_float): |
| 169 |
self._encode_float(sb, space.float_w(w_obj)) |
| 170 |
elif space.isinstance_w(w_obj, space.w_list) or \ |
| 171 |
space.isinstance_w(w_obj, space.w_tuple): |
| 172 |
self._encode_list(sb, w_obj) |
| 173 |
elif space.isinstance_w(w_obj, space.w_dict): |
| 174 |
self._encode_dict(sb, w_obj) |
| 175 |
else: |
| 176 |
self._encode_default(sb, w_obj) |
| 177 |
|
| 178 |
def _encode_default(self, sb, w_obj): |
| 179 |
space = self.space |
| 180 |
w_markers = self.w_markers |
| 181 |
w_id = space.w_None |
| 182 |
check_circular = not space.is_none(w_markers) |
| 183 |
if check_circular: |
| 184 |
w_id = space.id(w_obj) |
| 185 |
if space.contains_w(w_markers, w_id): |
| 186 |
raise oefmt(space.w_ValueError, "Circular reference detected") |
| 187 |
space.setitem(w_markers, w_id, w_obj) |
| 188 |
w_result = space.call_function(self.w_default, w_obj) |
| 189 |
self._encode(sb, w_result) |
| 190 |
if check_circular: |
| 191 |
space.delitem(w_markers, w_id) |
| 192 |
|
| 193 |
def _encode_list(self, sb, w_list): |
| 194 |
space = self.space |
| 195 |
w_markers = self.w_markers |
| 196 |
w_id = space.w_None |
| 197 |
check_circular = not space.is_none(w_markers) |
| 198 |
if check_circular: |
| 199 |
w_id = space.id(w_list) |
| 200 |
if space.contains_w(w_markers, w_id): |
| 201 |
raise oefmt(space.w_ValueError, "Circular reference detected") |
| 202 |
space.setitem(w_markers, w_id, w_list) |
| 203 |
sb.append('[') |
| 204 |
first = True |
| 205 |
|
| 206 |
w_iter = space.iter(w_list) |
| 207 |
while True: |
| 208 |
try: |
| 209 |
w_item = space.next(w_iter) |
| 210 |
except OperationError as e: |
| 211 |
if e.match(space, space.w_StopIteration): |
| 212 |
break |
| 213 |
raise |
| 214 |
if first: |
| 215 |
first = False |
| 216 |
else: |
| 217 |
sb.append(self.item_separator) |
| 218 |
self._encode(sb, w_item) |
| 219 |
sb.append(']') |
| 220 |
if check_circular: |
| 221 |
space.delitem(w_markers, w_id) |
| 222 |
|
| 223 |
def _coerce_dict_key(self, w_key): |
| 224 |
"""Return (w_str_key, skip) where skip=True means omit this entry.""" |
| 225 |
space = self.space |
| 226 |
if space.isinstance_w(w_key, space.w_unicode): |
| 227 |
return w_key, False |
| 228 |
elif space.is_w(w_key, space.w_True): |
| 229 |
return space.newtext('true'), False |
| 230 |
elif space.is_w(w_key, space.w_False): |
| 231 |
return space.newtext('false'), False |
| 232 |
elif space.is_w(w_key, space.w_None): |
| 233 |
return space.newtext('null'), False |
| 234 |
elif space.isinstance_w(w_key, space.w_int): |
| 235 |
return space.call_method(space.w_int, '__repr__', w_key), False |
| 236 |
elif space.isinstance_w(w_key, space.w_float): |
| 237 |
float_sb = StringBuilder() |
| 238 |
self._encode_float(float_sb, space.float_w(w_key)) |
| 239 |
return space.newtext(float_sb.build()), False |
| 240 |
elif self.skipkeys: |
| 241 |
return space.w_None, True |
| 242 |
else: |
| 243 |
raise oefmt(space.w_TypeError, |
| 244 |
'keys must be str, int, float, bool or None, not %T', w_key) |
| 245 |
|
| 246 |
def _encode_dict(self, sb, w_dict): |
| 247 |
space = self.space |
| 248 |
w_markers = self.w_markers |
| 249 |
w_id = space.w_None |
| 250 |
check_circular = not space.is_none(w_markers) |
| 251 |
if check_circular: |
| 252 |
w_id = space.id(w_dict) |
| 253 |
if space.contains_w(w_markers, w_id): |
| 254 |
raise oefmt(space.w_ValueError, "Circular reference detected") |
| 255 |
space.setitem(w_markers, w_id, w_dict) |
| 256 |
keys_w = space.unpackiterable(w_dict) |
| 257 |
sb.append('{') |
| 258 |
first = True |
| 259 |
if self.sort_keys: |
| 260 |
wkey_list = [] |
| 261 |
wstr_list = [] |
| 262 |
for w_key in keys_w: |
| 263 |
w_key_str, skip = self._coerce_dict_key(w_key) |
| 264 |
if skip: |
| 265 |
continue |
| 266 |
wkey_list.append(w_key) |
| 267 |
wstr_list.append(w_key_str) |
| 268 |
|
| 269 |
|
| 270 |
n = len(wkey_list) |
| 271 |
for i in range(1, n): |
| 272 |
wk = wkey_list[i] |
| 273 |
ws = wstr_list[i] |
| 274 |
j = i |
| 275 |
while j > 0 and space.is_true(space.lt(wk, wkey_list[j - 1])): |
| 276 |
wkey_list[j] = wkey_list[j - 1] |
| 277 |
wstr_list[j] = wstr_list[j - 1] |
| 278 |
j -= 1 |
| 279 |
wkey_list[j] = wk |
| 280 |
wstr_list[j] = ws |
| 281 |
for i in range(len(wkey_list)): |
| 282 |
w_val = space.getitem(w_dict, wkey_list[i]) |
| 283 |
if first: |
| 284 |
first = False |
| 285 |
else: |
| 286 |
sb.append(self.item_separator) |
| 287 |
self._encode_str(sb, wstr_list[i]) |
| 288 |
sb.append(self.key_separator) |
| 289 |
self._encode(sb, w_val) |
| 290 |
else: |
| 291 |
for w_key in keys_w: |
| 292 |
w_key_str, skip = self._coerce_dict_key(w_key) |
| 293 |
if skip: |
| 294 |
continue |
| 295 |
w_val = space.getitem(w_dict, w_key) |
| 296 |
if first: |
| 297 |
first = False |
| 298 |
else: |
| 299 |
sb.append(self.item_separator) |
| 300 |
self._encode_str(sb, w_key_str) |
| 301 |
sb.append(self.key_separator) |
| 302 |
self._encode(sb, w_val) |
| 303 |
sb.append('}') |
| 304 |
if check_circular: |
| 305 |
space.delitem(w_markers, w_id) |
| 306 |
|
| 307 |
|
| 308 |
W_Encoder.typedef = TypeDef( |
| 309 |
'_pypyjson.Encoder', |
| 310 |
__call__=interp2app(W_Encoder.descr_call), |
| 311 |
fast_encode_mode=interp_attrproperty('fast_encode_mode', cls=W_Encoder, |
| 312 |
wrapfn='newint'), |
| 313 |
) |
| 314 |
W_Encoder.typedef.acceptable_as_base_class = False |
| 315 |
|
| 316 |
|
| 317 |
def _get_fast_encode_mode(space, w_str_encoder): |
| 318 |
"""Determine encoding mode by comparing w_str_encoder against the two |
| 319 |
standard functions in json.encoder -- same logic as CPython's |
| 320 |
PyCFunction_GetFunction identity check in _json.c encoder_new().""" |
| 321 |
w_sys_modules = space.sys.get('modules') |
| 322 |
try: |
| 323 |
w_enc_mod = space.getitem(w_sys_modules, space.newtext('json.encoder')) |
| 324 |
except OperationError: |
| 325 |
return FAST_ENCODE_CUSTOM |
| 326 |
w_ascii_enc = space.getattr(w_enc_mod, space.newtext('encode_basestring_ascii')) |
| 327 |
w_unicode_enc = space.getattr(w_enc_mod, space.newtext('encode_basestring')) |
| 328 |
if space.is_w(w_str_encoder, w_ascii_enc): |
| 329 |
return FAST_ENCODE_ASCII |
| 330 |
elif space.is_w(w_str_encoder, w_unicode_enc): |
| 331 |
return FAST_ENCODE_UNICODE |
| 332 |
else: |
| 333 |
return FAST_ENCODE_CUSTOM |
| 334 |
|
| 335 |
|
| 336 |
@unwrap_spec(key_separator='text', item_separator='text', |
| 337 |
sort_keys=bool, skipkeys=bool, allow_nan=bool) |
| 338 |
def make_encoder(space, w_markers, w_default, w_str_encoder, w_indent, |
| 339 |
key_separator, item_separator, sort_keys, skipkeys, allow_nan): |
| 340 |
"""Return an encoder callable for use as json.encoder.c_make_encoder.""" |
| 341 |
fast_encode_mode = _get_fast_encode_mode(space, w_str_encoder) |
| 342 |
return W_Encoder(space, w_markers, w_default, w_str_encoder, |
| 343 |
key_separator, item_separator, sort_keys, skipkeys, |
| 344 |
allow_nan, fast_encode_mode) |