Debian Codegraph @

pypy/module/_pypyjson/interp_decoder.py

raw symbols SCIP
1 import sys
2 from rpython.rlib.rstring import StringBuilder
3 from rpython.rlib.objectmodel import specialize, always_inline
4 from rpython.rlib import rfloat, jit, objectmodel, rutf8
5 from rpython.rtyper.lltypesystem import lltype, rffi
6 from pypy.interpreter.error import oefmt, OperationError
7 from rpython.rlib.rarithmetic import r_uint
8 from pypy.interpreter import unicodehelper
9 from pypy.interpreter.baseobjspace import W_Root
10 from pypy.module._pypyjson import simd
11
12 OVF_DIGITS = len(str(sys.maxint))
13
14 def is_whitespace(ch):
15 return ch == ' ' or ch == '\t' or ch == '\r' or ch == '\n'
16
17 # precomputing negative powers of 10 is MUCH faster than using e.g. math.pow
18 # at runtime
19 NEG_POW_10 = [10.0**-i for i in range(16)]
20 del i
21
22 def neg_pow_10(x, exp):
23 if exp >= len(NEG_POW_10):
24 return 0.0
25 return x * NEG_POW_10[exp]
26
27
28 class IntCache(object):
29 """ A cache for wrapped ints between START and END """
30
31 # I also tried various combinations of having an LRU cache for ints as
32 # well, didn't really help.
33
34 # XXX one thing to do would be to use withintprebuilt in general again,
35 # hidden behind a 'we_are_jitted'
36
37 START = -10
38 END = 256
39
40 def __init__(self, space):
41 self.space = space
42 self.cache = [self.space.newint(i)
43 for i in range(self.START, self.END)]
44
45 def newint(self, intval):
46 if self.START <= intval < self.END:
47 return self.cache[intval - self.START]
48 return self.space.newint(intval)
49
50 class DecoderError(Exception):
51 def __init__(self, msg, pos):
52 self.msg = msg
53 self.pos = pos
54
55 class JSONDecoder(W_Root):
56
57 LRU_SIZE = 16
58 LRU_MASK = LRU_SIZE - 1
59
60 DEFAULT_SIZE_SCRATCH = 20
61
62 # string caching is only used if the total size of the message is larger
63 # than a megabyte. Below that, there can't be that many repeated big
64 # strings anyway (some experiments showed this to be a reasonable cutoff
65 # size)
66 MIN_SIZE_FOR_STRING_CACHE = 1024 * 1024
67
68 # evaluate the string cache for 200 strings, before looking at the hit rate
69 # and deciding whether to keep doing it
70 STRING_CACHE_EVALUATION_SIZE = 200
71
72 # keep using the string cache if at least 25% of all decoded strings are a
73 # hit in the cache
74 STRING_CACHE_USEFULNESS_FACTOR = 4
75
76 # don't make arbitrarily huge maps
77 MAX_MAP_SIZE = 100
78
79
80 def __init__(self, space, s):
81 self.space = space
82 self.w_empty_string = space.newutf8("", 0)
83
84 self.s = s
85
86 # we put our string in a raw buffer so:
87 # 1) we automatically get the '\0' sentinel at the end of the string,
88 # which means that we never have to check for the "end of string"
89 # 2) we can pass the buffer directly to strtod
90 self.ll_chars, self.llobj, self.flag = rffi.get_nonmovingbuffer_ll_final_null(self.s)
91 self.end_ptr = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
92 self.pos = 0
93 self.intcache = space.fromcache(IntCache)
94
95 # two caches, one for keys, one for general strings. they both have the
96 # form {hash-as-int: StringCacheEntry} and they don't deal with
97 # collisions at all. For every hash there is simply one string stored
98 # and we ignore collisions.
99 self.cache_keys = {}
100 self.cache_values = {}
101
102 # we don't cache *all* non-key strings, that would be too expensive.
103 # instead, keep a cache of the last 16 strings hashes around and add a
104 # string to the cache only if its hash is seen a second time
105 self.lru_cache = [0] * self.LRU_SIZE
106 self.lru_index = 0
107
108 self.startmap = self.space.fromcache(Terminator)
109
110 # keep a list of objects that are created with maps that aren't clearly
111 # useful. If they turn out to be useful in the end we are good,
112 # otherwise convert them to dicts (see .close())
113 self.unclear_objects = []
114
115 # this is a freelist of lists that store the decoded value of an
116 # object, before they get copied into the eventual dict
117 self.scratch = [[None] * self.DEFAULT_SIZE_SCRATCH]
118
119
120 def close(self):
121 rffi.free_nonmovingbuffer_ll(self.ll_chars, self.llobj, self.flag)
122 lltype.free(self.end_ptr, flavor='raw')
123 # clean up objects that are instances of now blocked maps
124 for w_obj in self.unclear_objects:
125 jsonmap = self._get_jsonmap_from_dict(w_obj)
126 if jsonmap.is_state_blocked():
127 self._devolve_jsonmap_dict(w_obj)
128
129 def getslice(self, start, end):
130 assert start >= 0
131 assert end >= 0
132 return self.s[start:end]
133
134 def skip_whitespace(self, i):
135 ll_chars = self.ll_chars
136 while True:
137 ch = ll_chars[i]
138 if is_whitespace(ch):
139 i += 1
140 else:
141 break
142 return i
143
144 def decode_any(self, i, contextmap=None):
145 """ Decode an object at position i. Optionally pass a contextmap, if
146 the value is decoded as the value of a dict. """
147 i = self.skip_whitespace(i)
148 ch = self.ll_chars[i]
149 if ch == '"':
150 return self.decode_string(i+1, contextmap)
151 elif ch == '[':
152 return self.decode_array(i+1)
153 elif ch == '{':
154 return self.decode_object(i+1)
155 elif ch == 'n':
156 return self.decode_null(i+1)
157 elif ch == 't':
158 return self.decode_true(i+1)
159 elif ch == 'f':
160 return self.decode_false(i+1)
161 elif ch == 'I':
162 return self.decode_infinity(i+1)
163 elif ch == 'N':
164 return self.decode_nan(i+1)
165 elif ch == '-':
166 if self.ll_chars[i+1] == 'I':
167 return self.decode_infinity(i+2, sign=-1)
168 return self.decode_numeric(i)
169 elif ch.isdigit():
170 return self.decode_numeric(i)
171 else:
172 raise DecoderError("Unexpected '%s'" % ch, i)
173
174
175 def _raise(self, msg, pos):
176 raise DecoderError(msg, pos)
177
178 def decode_null(self, i):
179 if (self.ll_chars[i] == 'u' and
180 self.ll_chars[i+1] == 'l' and
181 self.ll_chars[i+2] == 'l'):
182 self.pos = i+3
183 return self.space.w_None
184 raise DecoderError("Error when decoding null", i)
185
186 def decode_true(self, i):
187 if (self.ll_chars[i] == 'r' and
188 self.ll_chars[i+1] == 'u' and
189 self.ll_chars[i+2] == 'e'):
190 self.pos = i+3
191 return self.space.w_True
192 raise DecoderError("Error when decoding true", i)
193
194 def decode_false(self, i):
195 if (self.ll_chars[i] == 'a' and
196 self.ll_chars[i+1] == 'l' and
197 self.ll_chars[i+2] == 's' and
198 self.ll_chars[i+3] == 'e'):
199 self.pos = i+4
200 return self.space.w_False
201 raise DecoderError("Error when decoding false", i)
202
203 def decode_infinity(self, i, sign=1):
204 if (self.ll_chars[i] == 'n' and
205 self.ll_chars[i+1] == 'f' and
206 self.ll_chars[i+2] == 'i' and
207 self.ll_chars[i+3] == 'n' and
208 self.ll_chars[i+4] == 'i' and
209 self.ll_chars[i+5] == 't' and
210 self.ll_chars[i+6] == 'y'):
211 self.pos = i+7
212 return self.space.newfloat(rfloat.INFINITY * sign)
213 raise DecoderError("Error when decoding Infinity", i)
214
215 def decode_nan(self, i):
216 if (self.ll_chars[i] == 'a' and
217 self.ll_chars[i+1] == 'N'):
218 self.pos = i+2
219 return self.space.newfloat(rfloat.NAN)
220 raise DecoderError("Error when decoding NaN", i)
221
222 def decode_numeric(self, i):
223 start = i
224 i, ovf_maybe, intval = self.parse_integer(i)
225 #
226 # check for the optional fractional part
227 ch = self.ll_chars[i]
228 if ch == '.':
229 if not self.ll_chars[i+1].isdigit():
230 raise DecoderError("Expected digit", i+1)
231 return self.decode_float(start)
232 elif ch == 'e' or ch == 'E':
233 return self.decode_float(start)
234 elif ovf_maybe:
235 return self.decode_int_slow(start)
236
237 self.pos = i
238 return self.intcache.newint(intval)
239
240 def decode_float(self, i):
241 from rpython.rlib import rdtoa
242 start = rffi.ptradd(self.ll_chars, i)
243 floatval = rdtoa.dg_strtod(rffi.cast(rffi.CONST_CCHARP, start), self.end_ptr)
244 diff = rffi.cast(rffi.SIGNED, self.end_ptr[0]) - rffi.cast(rffi.SIGNED, start)
245 self.pos = i + diff
246 return self.space.newfloat(floatval)
247
248 def decode_int_slow(self, i):
249 start = i
250 if self.ll_chars[i] == '-':
251 i += 1
252 while self.ll_chars[i].isdigit():
253 i += 1
254 s = self.getslice(start, i)
255 self.pos = i
256 return self.space.call_function(self.space.w_int, self.space.newtext(s))
257
258 @always_inline
259 def parse_integer(self, i):
260 "Parse a decimal number with an optional minus sign"
261 sign = 1
262 # parse the sign
263 if self.ll_chars[i] == '-':
264 sign = -1
265 i += 1
266 elif self.ll_chars[i] == '+':
267 i += 1
268 #
269 if self.ll_chars[i] == '0':
270 i += 1
271 return i, False, 0
272
273 intval = 0
274 start = i
275 while True:
276 ch = self.ll_chars[i]
277 if ch.isdigit():
278 intval = intval*10 + ord(ch)-ord('0')
279 i += 1
280 else:
281 break
282 count = i - start
283 if count == 0:
284 raise DecoderError("Expected digit", i)
285 # if the number has more digits than OVF_DIGITS, it might have
286 # overflowed
287 ovf_maybe = (count >= OVF_DIGITS)
288 return i, ovf_maybe, sign * intval
289
290 def _raise_control_char_in_string(self, ch, startindex, currindex):
291 if ch == '\0':
292 self._raise("Unterminated string starting at",
293 startindex - 1)
294 else:
295 self._raise("Invalid control character at", currindex-1)
296
297 def _raise_object_error(self, ch, start, i):
298 if ch == '\0':
299 self._raise("Unterminated object starting at", start)
300 else:
301 self._raise("Unexpected '%s' when decoding object" % ch, i)
302
303 def decode_array(self, i):
304 """ Decode a list. i must be after the opening '[' """
305 w_list = self.space.newlist([])
306 start = i
307 i = self.skip_whitespace(start)
308 if self.ll_chars[i] == ']':
309 self.pos = i+1
310 return w_list
311 #
312 while True:
313 w_item = self.decode_any(i)
314 i = self.pos
315 self.space.call_method(w_list, 'append', w_item)
316 i = self.skip_whitespace(i)
317 ch = self.ll_chars[i]
318 i += 1
319 if ch == ']':
320 self.pos = i
321 return w_list
322 elif ch == ',':
323 pass
324 elif ch == '\0':
325 raise DecoderError("Unterminated array starting at", start)
326 else:
327 raise DecoderError("Unexpected '%s' when decoding array" % ch,
328 i-1)
329
330 def decode_object(self, i):
331 start = i
332
333 i = self.skip_whitespace(i)
334 if self.ll_chars[i] == '}':
335 self.pos = i+1
336 return self.space.newdict()
337
338 if self.scratch:
339 values_w = self.scratch.pop()
340 else:
341 values_w = [None] * self.DEFAULT_SIZE_SCRATCH
342 nextindex = 0
343 currmap = self.startmap
344 while True:
345 # parse a key: value
346 newmap = self.decode_key_map(i, currmap)
347 if newmap is None:
348 # We've seen a repeated value, switch to dict-based storage.
349 dict_w = self._switch_to_dict(currmap, values_w, nextindex)
350 # We re-parse the last key, to get the correct overwriting
351 # effect. Pointless to care for performance here.
352 return self.decode_object_dict(i, start, dict_w)
353 currmap = newmap
354 i = self.skip_whitespace(self.pos)
355 ch = self.ll_chars[i]
356 if ch != ':':
357 raise DecoderError("No ':' found at", i)
358 i += 1
359
360 w_value = self.decode_any(i, currmap)
361
362 if nextindex == len(values_w): # full
363 values_w = values_w + [None] * len(values_w) # double
364 values_w[nextindex] = w_value
365 nextindex += 1
366 i = self.skip_whitespace(self.pos)
367 ch = self.ll_chars[i]
368 i += 1
369 if ch == '}':
370 self.pos = i
371 self.scratch.append(values_w) # can reuse next time
372 if currmap.is_state_blocked():
373 dict_w = self._switch_to_dict(currmap, values_w, nextindex)
374 return self._create_dict(dict_w)
375 values_w = values_w[:nextindex]
376 w_res = self._create_dict_map(values_w, currmap)
377 if not currmap.is_state_useful():
378 self.unclear_objects.append(w_res)
379 return w_res
380 elif ch == ',':
381 i = self.skip_whitespace(i)
382 if currmap.is_state_blocked() or nextindex > self.MAX_MAP_SIZE:
383 self.scratch.append(values_w) # can reuse next time
384 dict_w = self._switch_to_dict(currmap, values_w, nextindex)
385 return self.decode_object_dict(i, start, dict_w)
386 else:
387 self._raise_object_error(ch, start, i - 1)
388
389 def _create_dict_map(self, values_w, jsonmap):
390 from pypy.objspace.std.jsondict import from_values_and_jsonmap
391 return from_values_and_jsonmap(self.space, values_w, jsonmap)
392
393 def _devolve_jsonmap_dict(self, w_dict):
394 from pypy.objspace.std.jsondict import devolve_jsonmap_dict
395 devolve_jsonmap_dict(w_dict)
396
397 def _get_jsonmap_from_dict(self, w_dict):
398 from pypy.objspace.std.jsondict import get_jsonmap_from_dict
399 return get_jsonmap_from_dict(w_dict)
400
401 def _switch_to_dict(self, currmap, values_w, nextindex):
402 dict_w = self._create_empty_dict()
403 currmap.fill_dict(dict_w, values_w)
404 assert len(dict_w) == nextindex
405 return dict_w
406
407 def decode_object_dict(self, i, start, dict_w):
408 while True:
409 # parse a key: value
410 w_key = self.decode_key_string(i)
411 i = self.skip_whitespace(self.pos)
412 ch = self.ll_chars[i]
413 if ch != ':':
414 self._raise("No ':' found at", i)
415 i += 1
416
417 w_value = self.decode_any(i)
418 dict_w[w_key] = w_value
419 i = self.skip_whitespace(self.pos)
420 ch = self.ll_chars[i]
421 i += 1
422 if ch == '}':
423 self.pos = i
424 return self._create_dict(dict_w)
425 elif ch == ',':
426 i = self.skip_whitespace(i)
427 else:
428 self._raise_object_error(ch, start, i - 1)
429
430 def decode_string_uncached(self, i):
431 start = i
432 ll_chars = self.ll_chars
433 nonascii, i = simd.find_end_of_string_no_hash(ll_chars, i, len(self.s))
434 ch = ll_chars[i]
435 if ch == '\\':
436 self.pos = i
437 return self.decode_string_escaped(start, nonascii)
438 if ch < '\x20':
439 self._raise_control_char_in_string(ch, start, i)
440 else:
441 assert ch == '"'
442
443 self.pos = i + 1
444 return self._create_string_wrapped(start, i, nonascii)
445
446 def _create_string_wrapped(self, start, end, nonascii):
447 content = self.getslice(start, end)
448 if nonascii:
449 # contains non-ascii chars, we need to check that it's valid utf-8
450 lgt = unicodehelper.check_utf8_or_raise(self.space,
451 content)
452 else:
453 lgt = end - start
454 return self.space.newutf8(content, lgt)
455
456 def _create_dict(self, d):
457 from pypy.objspace.std.dictmultiobject import from_unicode_key_dict
458 return from_unicode_key_dict(self.space, d)
459
460 def _create_empty_dict(self):
461 from pypy.objspace.std.dictmultiobject import create_empty_unicode_key_dict
462 return create_empty_unicode_key_dict(self.space)
463
464 def decode_string_escaped(self, start, nonascii):
465 i = self.pos
466 builder = StringBuilder((i - start) * 2) # just an estimate
467 assert start >= 0
468 assert i >= 0
469 builder.append_slice(self.s, start, i)
470 while True:
471 ch = self.ll_chars[i]
472 i += 1
473 if ch == '"':
474 content_utf8 = builder.build()
475 length = unicodehelper.check_utf8_or_raise(self.space,
476 content_utf8)
477 self.pos = i
478 return self.space.newutf8(content_utf8, length)
479 elif ch == '\\':
480 i = self.decode_escape_sequence_to_utf8(i, builder)
481 elif ch < '\x20':
482 self._raise_control_char_in_string(ch, start, i)
483 else:
484 builder.append(ch)
485
486 def decode_escape_sequence_to_utf8(self, i, stringbuilder):
487 ch = self.ll_chars[i]
488 i += 1
489 put = stringbuilder.append
490 if ch == '\\': put('\\')
491 elif ch == '"': put('"' )
492 elif ch == '/': put('/' )
493 elif ch == 'b': put('\b')
494 elif ch == 'f': put('\f')
495 elif ch == 'n': put('\n')
496 elif ch == 'r': put('\r')
497 elif ch == 't': put('\t')
498 elif ch == 'u':
499 # may be a surrogate pair
500 return self.decode_escape_sequence_unicode(i, stringbuilder)
501 else:
502 if ch <= ' ':
503 self._raise("Invalid \\escape: (char %d)" % (i-2,), i-2)
504 else:
505 self._raise("Invalid \\escape: %s (char %d)" % (ch, i-2), i-2)
506 return i
507
508 def _get_int_val_from_hex4(self, i):
509 ll_chars = self.ll_chars
510 res = 0
511 for i in range(i, i + 4):
512 ch = ord(ll_chars[i])
513 if ord('a') <= ch <= ord('f'):
514 digit = ch - ord('a') + 10
515 elif ord('A') <= ch <= ord('F'):
516 digit = ch - ord('A') + 10
517 elif ord('0') <= ch <= ord('9'):
518 digit = ch - ord('0')
519 else:
520 raise ValueError
521 res = (res << 4) + digit
522 return res
523
524 def decode_escape_sequence_unicode(self, i, builder):
525 # at this point we are just after the 'u' of the \u1234 sequence.
526 start = i
527 i += 4
528 try:
529 val = self._get_int_val_from_hex4(start)
530 if (0xd800 <= val <= 0xdbff and
531 self.ll_chars[i] == '\\' and self.ll_chars[i+1] == 'u'):
532 lowsurr = self._get_int_val_from_hex4(i + 2)
533 if 0xdc00 <= lowsurr <= 0xdfff:
534 # decode surrogate pair
535 val = 0x10000 + (((val - 0xd800) << 10) |
536 (lowsurr - 0xdc00))
537 i += 6
538 except ValueError:
539 raise DecoderError("Invalid \uXXXX escape (char %d)", i-1)
540 return # help the annotator to know that we'll never go beyond
541 # this point
542 #
543 utf8_ch = rutf8.unichr_as_utf8(r_uint(val), allow_surrogates=True)
544 builder.append(utf8_ch)
545 return i
546
547
548 def decode_string(self, i, contextmap=None):
549 """ Decode a string at position i (which is right after the opening ").
550 Optionally pass a contextmap, if the value is decoded as the value of a
551 dict."""
552
553 ll_chars = self.ll_chars
554 start = i
555 ch = ll_chars[i]
556 if ch == '"':
557 self.pos = i + 1
558 return self.w_empty_string # surprisingly common
559
560 cache = True
561 if contextmap is not None:
562 # keep some statistics about the usefulness of the string cache on
563 # the contextmap
564 # the intuition about the contextmap is as follows:
565 # often there are string values stored in dictionaries that can
566 # never be usefully cached, like unique ids of objects. Then the
567 # strings *in those fields* of all objects should never be cached.
568 # However, the content of other fields can still be useful to
569 # cache.
570 contextmap.decoded_strings += 1
571 if not contextmap.should_cache_strings():
572 cache = False
573 if len(self.s) < self.MIN_SIZE_FOR_STRING_CACHE:
574 cache = False
575
576 if not cache:
577 return self.decode_string_uncached(i)
578
579 strhash, nonascii, i = simd.find_end_of_string(ll_chars, i, len(self.s))
580 ch = ll_chars[i]
581 if ch == '\\':
582 self.pos = i
583 return self.decode_string_escaped(start, nonascii)
584 if ch < '\x20':
585 self._raise_control_char_in_string(ch, start, i)
586 else:
587 assert ch == '"'
588
589 self.pos = i + 1
590
591 length = i - start
592 strhash ^= length
593
594 # check cache first:
595 try:
596 entry = self.cache_values[strhash]
597 except KeyError:
598 w_res = self._create_string_wrapped(start, i, nonascii)
599 # only add *some* strings to the cache, because keeping them all is
600 # way too expensive. first we check if the contextmap has caching
601 # disabled completely. if not, we check whether we have recently
602 # seen the same hash already, if yes, we cache the string.
603 if ((contextmap is not None and
604 contextmap.decoded_strings < self.STRING_CACHE_EVALUATION_SIZE) or
605 strhash in self.lru_cache):
606 entry = StringCacheEntry(
607 self.getslice(start, start + length), w_res)
608 self.cache_values[strhash] = entry
609 else:
610 self.lru_cache[self.lru_index] = strhash
611 self.lru_index = (self.lru_index + 1) & self.LRU_MASK
612 return w_res
613 if not entry.compare(ll_chars, start, length):
614 # collision! hopefully rare
615 return self._create_string_wrapped(start, i, nonascii)
616 if contextmap is not None:
617 contextmap.cache_hits += 1
618 return entry.w_uni
619
620 def decode_key_map(self, i, currmap):
621 """ Given the current map currmap of an object, decode the next key at
622 position i. This returns the new map of the object. """
623 newmap = self._decode_key_map(i, currmap)
624 if newmap is None:
625 return None
626 currmap.observe_transition(newmap, self.startmap)
627 return newmap
628
629 def _decode_key_map(self, i, currmap):
630 ll_chars = self.ll_chars
631 # first try to see whether we happen to find currmap.nextmap_first
632 nextmap = currmap.fast_path_key_parse(self, i)
633 if nextmap is not None:
634 return nextmap
635
636 start = i
637 ch = ll_chars[i]
638 if ch != '"':
639 raise DecoderError("Key name must be string at char", i)
640 i += 1
641 w_key = self._decode_key_string(i)
642 return currmap.get_next(w_key, self.s, start, self.pos, self.startmap)
643
644 def _decode_key_string(self, i):
645 """ decode key at position i as a string. Key strings are always
646 cached, since they repeat a lot. """
647 ll_chars = self.ll_chars
648 start = i
649
650 strhash, nonascii, i = simd.find_end_of_string(ll_chars, i, len(self.s))
651
652 ch = ll_chars[i]
653 if ch == '\\':
654 self.pos = i
655 w_key = self.decode_string_escaped(start, nonascii)
656 return w_key
657 if ch < '\x20':
658 self._raise_control_char_in_string(ch, start, i)
659 length = i - start
660 strhash ^= length
661 self.pos = i + 1
662 # check cache first:
663 try:
664 entry = self.cache_keys[strhash]
665 except KeyError:
666 w_res = self._create_string_wrapped(start, i, nonascii)
667 entry = StringCacheEntry(
668 self.getslice(start, start + length), w_res)
669 self.cache_keys[strhash] = entry
670 return w_res
671 if not entry.compare(ll_chars, start, length):
672 # collision! hopefully rare
673 w_res = self._create_string_wrapped(start, i, nonascii)
674 else:
675 w_res = entry.w_uni
676 return w_res
677
678 def decode_key_string(self, i):
679 ll_chars = self.ll_chars
680 ch = ll_chars[i]
681 if ch != '"':
682 self._raise("Key name must be string at char %d", i)
683 i += 1
684 return self._decode_key_string(i)
685
686
687 class StringCacheEntry(object):
688 """ A cache entry, bundling the encoded version of a string as it appears
689 in the input string, and its wrapped decoded variant. """
690 def __init__(self, repr, w_uni):
691 # repr is the escaped string
692 self.repr = repr
693 # uni is the wrapped decoded string
694 self.w_uni = w_uni
695
696 def compare(self, ll_chars, start, length):
697 """ Check whether self.repr occurs at ll_chars[start:start+length] """
698 if length != len(self.repr):
699 return False
700 index = start
701 for c in self.repr:
702 if not ll_chars[index] == c:
703 return False
704 index += 1
705 return True
706
707
708 class MapBase(object):
709 """ A map implementation to speed up parsing of json dicts, and to
710 represent the resulting dicts more compactly and make access faster. """
711
712 # the basic problem we are trying to solve is the following: dicts in
713 # json can either be used as objects, or as dictionaries with arbitrary
714 # string keys. We want to use maps for the former, but not for the
715 # latter. But we don't know in advance which kind of dict is which.
716
717 # Therefore we create "preliminary" maps where we aren't quite sure yet
718 # whether they are really useful maps or not. If we see them used often
719 # enough, we promote them to "useful" maps, which we will actually
720 # instantiate objects with.
721
722 # If we determine that a map is not used often enough, we can turn it
723 # into a "blocked" map, which is a point in the map tree where we will
724 # switch to regular dicts, when we reach that part of the tree.
725
726 # One added complication: We want to keep the number of preliminary maps
727 # bounded to prevent generating tons of useless maps. but also not too
728 # small, to support having a json file that contains many uniform objects
729 # with tons of keys. That's where the idea of "fringe" maps comes into
730 # play. They are maps that sit between known useful nodes and preliminary
731 # nodes in the map transition tree. We bound only the number of fringe
732 # nodes we are considering (to MAX_FRINGE), but not the number of
733 # preliminary maps. When we have too many fringe maps, we remove the least
734 # commonly instantiated fringe map and mark it as blocked.
735
736 # allowed graph edges or nodes in nextmap_all:
737 # USEFUL -------
738 # / \ \
739 # v v v
740 # FRINGE USEFUL BLOCKED
741 # |
742 # v
743 # PRELIMINARY
744 # |
745 # v
746 # PRELIMINARY
747
748 # state transitions:
749 # PRELIMINARY
750 # / | \
751 # | v v
752 # | FRINGE -> USEFUL
753 # | |
754 # \ |
755 # v v
756 # BLOCKED
757
758 # the nextmap_first edge can only be these graph edges:
759 # USEFUL
760 # |
761 # v
762 # USEFUL
763 #
764 # FRINGE
765 # |
766 # v
767 # PRELIMINARY
768 # |
769 # v
770 # PRELIMINARY
771
772 USEFUL = 'u'
773 PRELIMINARY = 'p'
774 FRINGE = 'f' # buffer between PRELIMINARY and USEFUL
775 BLOCKED = 'b'
776
777 # tunable parameters
778 MAX_FRINGE = 40
779 USEFUL_THRESHOLD = 5
780
781 def __init__(self, space):
782 self.space = space
783
784 # a single transition is stored in .nextmap_first
785 self.nextmap_first = None
786
787 # nextmap_all is only initialized after seeing the *second* transition
788 # but then it also contains .nextmap_first
789 self.nextmap_all = None # later dict {key: nextmap}
790
791 # keep some statistics about every map: how often it was instantiated
792 # and how many non-blocked leaves the map transition tree has, starting
793 # from self
794 self.instantiation_count = 0
795 self.number_of_leaves = 1
796
797 def _check_invariants(self):
798 if self.nextmap_all:
799 for next in self.nextmap_all.itervalues():
800 next._check_invariants()
801 elif self.nextmap_first:
802 self.nextmap_first._check_invariants()
803
804 def get_next(self, w_key, string, start, stop, terminator):
805 """ Returns the next map, given a wrapped key w_key, the json input
806 string with positions start and stop, as well as a terminator.
807
808 Returns None if the key already appears somewhere in the map chain.
809 """
810 from pypy.objspace.std.dictmultiobject import unicode_hash, unicode_eq
811 if isinstance(self, JSONMap):
812 assert not self.state == MapBase.BLOCKED
813 nextmap_first = self.nextmap_first
814 if (nextmap_first is not None and
815 nextmap_first.w_key.eq_w(w_key)):
816 return nextmap_first
817
818 assert stop >= 0
819 assert start >= 0
820
821 if nextmap_first is None:
822 # first transition ever seen, don't initialize nextmap_all
823 next = self._make_next_map(w_key, string[start:stop])
824 if next is None:
825 return None
826 self.nextmap_first = next
827 else:
828 if self.nextmap_all is None:
829 # 2nd transition ever seen
830 self.nextmap_all = objectmodel.r_dict(unicode_eq, unicode_hash,
831 force_non_null=True, simple_hash_eq=True)
832 self.nextmap_all[nextmap_first.w_key] = nextmap_first
833 else:
834 next = self.nextmap_all.get(w_key, None)
835 if next is not None:
836 return next
837 # if we are at this point we didn't find the transition yet, so
838 # create a new one
839 next = self._make_next_map(w_key, string[start:stop])
840 if next is None:
841 return None
842 self.nextmap_all[w_key] = next
843
844 # one new leaf has been created
845 self.change_number_of_leaves(1)
846
847 terminator.register_potential_fringe(next)
848 return next
849
850 def change_number_of_leaves(self, difference):
851 """ add difference to .number_of_leaves of self and its parents """
852 if not difference:
853 return
854 parent = self
855 while isinstance(parent, JSONMap):
856 parent.number_of_leaves += difference
857 parent = parent.prev
858 parent.number_of_leaves += difference # terminator
859
860 def fast_path_key_parse(self, decoder, position):
861 """ Fast path when parsing the next key: We speculate that we will
862 always see a commonly seen next key, and use strcmp (implemented in
863 key_repr_cmp) to check whether that is the case. """
864 nextmap_first = self.nextmap_first
865 if nextmap_first:
866 ll_chars = decoder.ll_chars
867 assert isinstance(nextmap_first, JSONMap)
868 if nextmap_first.key_repr_cmp(ll_chars, position):
869 decoder.pos = position + len(nextmap_first.key_repr)
870 return nextmap_first
871 return None
872
873 def observe_transition(self, newmap, terminator):
874 """ observe a transition from self to newmap.
875 This does a few things, including updating the self size estimate with
876 the knowledge that one object transitioned from self to newmap.
877 also it potentially decides that self should move to state USEFUL."""
878 newmap.instantiation_count += 1
879 if isinstance(self, JSONMap) and self.state == MapBase.FRINGE:
880 if self.is_useful():
881 self.mark_useful(terminator)
882
883 def _make_next_map(self, w_key, key_repr):
884 # Check whether w_key is already part of the self.prev chain
885 # to prevent strangeness in the json dict implementation.
886 # This is slow, but it should be rare to call this function.
887 check = self
888 while isinstance(check, JSONMap):
889 if check.w_key._utf8 == w_key._utf8:
890 return None
891 check = check.prev
892 return JSONMap(self.space, self, w_key, key_repr)
893
894 def fill_dict(self, dict_w, values_w):
895 """ recursively fill the dictionary dict_w in the correct order,
896 reading from values_w."""
897 raise NotImplementedError("abstract base")
898
899 def _all_dot(self, output):
900 identity = objectmodel.compute_unique_id(self)
901 output.append('%s [shape=box%s];' % (identity, self._get_dot_text()))
902 if self.nextmap_all:
903 for w_key, value in self.nextmap_all.items():
904 assert isinstance(value, JSONMap)
905 if value is self.nextmap_first:
906 color = ", color=blue"
907 else:
908 color = ""
909 output.append('%s -> %s [label="%s"%s];' % (
910 identity, objectmodel.compute_unique_id(value), value.w_key._utf8, color))
911 value._all_dot(output)
912 elif self.nextmap_first is not None:
913 value = self.nextmap_first
914 output.append('%s -> %s [label="%s", color=blue];' % (
915 identity, objectmodel.compute_unique_id(value), value.w_key._utf8))
916 value._all_dot(output)
917
918
919 def _get_dot_text(self):
920 return ", label=base"
921
922 def view(self):
923 from dotviewer import graphclient
924 import pytest
925 r = ["digraph G {"]
926 self._all_dot(r)
927 r.append("}")
928 p = pytest.ensuretemp("jsonmap").join("temp.dot")
929 p.write("\n".join(r))
930 graphclient.display_dot_file(str(p))
931
932
933 class Terminator(MapBase):
934 """ The root node of the map transition tree. """
935 def __init__(self, space):
936 MapBase.__init__(self, space)
937 # a set of all map nodes that are currently in the FRINGE state
938 self.current_fringe = {}
939
940 def register_potential_fringe(self, prelim):
941 """ add prelim to the fringe, if its prev is either a Terminator or
942 useful. """
943 prev = prelim.prev
944 if (isinstance(prev, Terminator) or
945 isinstance(prev, JSONMap) and prev.state == MapBase.USEFUL):
946 assert prelim.state == MapBase.PRELIMINARY
947 prelim.state = MapBase.FRINGE
948
949 if len(self.current_fringe) > MapBase.MAX_FRINGE:
950 self.cleanup_fringe()
951 self.current_fringe[prelim] = None
952
953 def remove_from_fringe(self, former_fringe):
954 """ Remove former_fringe from self.current_fringe. """
955 assert former_fringe.state in (MapBase.USEFUL, MapBase.BLOCKED)
956 del self.current_fringe[former_fringe]
957
958 def cleanup_fringe(self):
959 """ remove the least-instantiated fringe map and block it."""
960 min_fringe = None
961 min_avg = 1e200
962 for f in self.current_fringe:
963 assert f.state == MapBase.FRINGE
964 avg = f.average_instantiation()
965 if avg < min_avg:
966 min_avg = avg
967 min_fringe = f
968 assert min_fringe
969 min_fringe.mark_blocked(self)
970
971 def fill_dict(self, dict_w, values_w):
972 """ recursively fill the dictionary dict_w in the correct order,
973 reading from values_w."""
974 return 0
975
976 def _check_invariants(self):
977 for fringe in self.current_fringe:
978 assert fringe.state == MapBase.FRINGE
979
980 class JSONMap(MapBase):
981 """ A map implementation to speed up parsing """
982
983 def __init__(self, space, prev, w_key, key_repr):
984 MapBase.__init__(self, space)
985
986 self.prev = prev
987 self.w_key = w_key
988 self.key_repr = key_repr
989
990 self.state = MapBase.PRELIMINARY
991
992 # key decoding stats
993 self.decoded_strings = 0
994 self.cache_hits = 0
995
996 # for jsondict support
997 self.key_to_index = None
998 self.keys_in_order = None
999 self.strategy_instance = None
1000
1001 def __repr__(self):
1002 return "<JSONMap key_repr=%s #instantiation=%s #leaves=%s prev=%r>" % (
1003 self.key_repr, self.instantiation_count, self.number_of_leaves, self.prev)
1004
1005 def _get_terminator(self): # only for _check_invariants
1006 while isinstance(self, JSONMap):
1007 self = self.prev
1008 assert isinstance(self, Terminator)
1009 return self
1010
1011 def _check_invariants(self):
1012 assert self.state in (
1013 MapBase.USEFUL,
1014 MapBase.PRELIMINARY,
1015 MapBase.FRINGE,
1016 MapBase.BLOCKED,
1017 )
1018
1019 prev = self.prev
1020 if isinstance(prev, JSONMap):
1021 prevstate = prev.state
1022 else:
1023 prevstate = MapBase.USEFUL
1024
1025 if prevstate == MapBase.USEFUL:
1026 assert self.state != MapBase.PRELIMINARY
1027 elif prevstate == MapBase.PRELIMINARY:
1028 assert self.state == MapBase.PRELIMINARY
1029 elif prevstate == MapBase.FRINGE:
1030 assert self.state == MapBase.PRELIMINARY
1031 else:
1032 # if prevstate is BLOCKED, we shouldn't have recursed here!
1033 assert False, "should be unreachable"
1034
1035 if self.state == MapBase.BLOCKED:
1036 assert self.nextmap_first is None
1037 assert self.nextmap_all is None
1038 elif self.state == MapBase.FRINGE:
1039 assert self in self._get_terminator().current_fringe
1040
1041 MapBase._check_invariants(self)
1042
1043 def mark_useful(self, terminator):
1044 """ mark self as useful, and also the most commonly instantiated
1045 children, recursively """
1046 was_fringe = self.state == MapBase.FRINGE
1047 assert self.state in (MapBase.FRINGE, MapBase.PRELIMINARY)
1048 self.state = MapBase.USEFUL
1049 if was_fringe:
1050 terminator.remove_from_fringe(self)
1051 # find the most commonly instantiated child, store it into
1052 # nextmap_first and mark it useful, recursively
1053 maxchild = self.nextmap_first
1054 if self.nextmap_all is not None:
1055 for child in self.nextmap_all.itervalues():
1056 if child.instantiation_count > maxchild.instantiation_count:
1057 maxchild = child
1058 if maxchild is not None:
1059 maxchild.mark_useful(terminator)
1060 if self.nextmap_all:
1061 for child in self.nextmap_all.itervalues():
1062 if child is not maxchild:
1063 terminator.register_potential_fringe(child)
1064 self.nextmap_first = maxchild
1065
1066 def mark_blocked(self, terminator):
1067 """ mark self and recursively all its children as blocked."""
1068 was_fringe = self.state == MapBase.FRINGE
1069 self.state = MapBase.BLOCKED
1070 if was_fringe:
1071 terminator.remove_from_fringe(self)
1072 if self.nextmap_all:
1073 for next in self.nextmap_all.itervalues():
1074 next.mark_blocked(terminator)
1075 elif self.nextmap_first:
1076 self.nextmap_first.mark_blocked(terminator)
1077 self.nextmap_first = None
1078 self.nextmap_all = None
1079 self.change_number_of_leaves(-self.number_of_leaves + 1)
1080
1081 def is_state_blocked(self):
1082 return self.state == MapBase.BLOCKED
1083
1084 def is_state_useful(self):
1085 return self.state == MapBase.USEFUL
1086
1087 def average_instantiation(self):
1088 """ the number of instantiations, divided by the number of leaves. We
1089 want to favor nodes that have either a high instantiation count, or few
1090 leaves below it. """
1091 return self.instantiation_count / float(self.number_of_leaves)
1092
1093 def is_useful(self):
1094 return self.average_instantiation() > self.USEFUL_THRESHOLD
1095
1096 def should_cache_strings(self):
1097 """ return whether strings parsed in the context of this map should be
1098 cached. """
1099 # we should cache if either we've seen few strings so far (less than
1100 # STRING_CACHE_EVALUATION_SIZE), or if we've seen many, and the cache
1101 # hit rate has been high enough
1102 return not (self.decoded_strings > JSONDecoder.STRING_CACHE_EVALUATION_SIZE and
1103 self.cache_hits * JSONDecoder.STRING_CACHE_USEFULNESS_FACTOR < self.decoded_strings)
1104
1105 def key_repr_cmp(self, ll_chars, i):
1106 # XXX should we use "real" memcmp (here in particular, and in other
1107 # places in RPython in general)?
1108 for j, c in enumerate(self.key_repr):
1109 if ll_chars[i] != c:
1110 return False
1111 i += 1
1112 return True
1113
1114 def fill_dict(self, dict_w, values_w):
1115 index = self.prev.fill_dict(dict_w, values_w)
1116 dict_w[self.w_key] = values_w[index]
1117 return index + 1
1118
1119 # _____________________________________________________
1120 # methods for JsonDictStrategy
1121
1122 @jit.elidable
1123 def get_index(self, w_key):
1124 from pypy.objspace.std.unicodeobject import W_UnicodeObject
1125 assert isinstance(w_key, W_UnicodeObject)
1126 return self.get_key_to_index().get(w_key, -1)
1127
1128 def get_key_to_index(self):
1129 from pypy.objspace.std.dictmultiobject import unicode_hash, unicode_eq
1130 key_to_index = self.key_to_index
1131 if key_to_index is None:
1132 key_to_index = self.key_to_index = objectmodel.r_dict(unicode_eq, unicode_hash,
1133 force_non_null=True, simple_hash_eq=True)
1134 # compute depth
1135 curr = self
1136 depth = 0
1137 while True:
1138 depth += 1
1139 curr = curr.prev
1140 if not isinstance(curr, JSONMap):
1141 break
1142
1143 curr = self
1144 while depth:
1145 depth -= 1
1146 key_to_index[curr.w_key] = depth
1147 curr = curr.prev
1148 if not isinstance(curr, JSONMap):
1149 break
1150 return key_to_index
1151
1152 def get_keys_in_order(self):
1153 keys_in_order = self.keys_in_order
1154 if keys_in_order is None:
1155 key_to_index = self.get_key_to_index()
1156 keys_in_order = self.keys_in_order = [None] * len(key_to_index)
1157 for w_key, index in key_to_index.iteritems():
1158 keys_in_order[index] = w_key
1159 return keys_in_order
1160
1161 # _____________________________________________________
1162
1163 def _get_dot_text(self):
1164 if self.nextmap_all is None:
1165 l = int(self.nextmap_first is not None)
1166 else:
1167 l = len(self.nextmap_all)
1168 extra = ""
1169 if self.decoded_strings:
1170 extra = "\\n%s/%s (%s%%)" % (self.cache_hits, self.decoded_strings, self.cache_hits/float(self.decoded_strings))
1171 res = ', label="#%s\\nchildren: %s%s"' % (self.instantiation_count, l, extra)
1172 if self.state == MapBase.BLOCKED:
1173 res += ", fillcolor=lightsalmon"
1174 if self.state == MapBase.FRINGE:
1175 res += ", fillcolor=lightgray"
1176 if self.state == MapBase.PRELIMINARY:
1177 res += ", fillcolor=lightslategray"
1178 return res
1179
1180 @jit.dont_look_inside
1181 def loads(space, w_s, w_errorcls=None):
1182 s = space.text_w(w_s)
1183 decoder = JSONDecoder(space, s)
1184 try:
1185 w_res = decoder.decode_any(0)
1186 i = decoder.skip_whitespace(decoder.pos)
1187 if i < len(s):
1188 start = i
1189 raise DecoderError('Extra data', start)
1190 return w_res
1191 except DecoderError as e:
1192 if w_errorcls is None:
1193 w_errorcls = space.w_ValueError
1194 w_e = space.call_function(w_errorcls, space.newtext(e.msg), w_s,
1195 space.newint(e.pos))
1196 raise OperationError(w_errorcls, w_e)
1197 finally:
1198 decoder.close()
1199