Debian Codegraph @

rpython/rtyper/lltypesystem/rdict.py

raw symbols SCIP
1 from rpython.tool.pairtype import pairtype
2 from rpython.flowspace.model import Constant
3 from rpython.rtyper.rdict import AbstractDictRepr, AbstractDictIteratorRepr
4 from rpython.rtyper.lltypesystem import lltype, llmemory
5 from rpython.rtyper.lltypesystem.lloperation import llop
6 from rpython.rlib import objectmodel, jit
7 from rpython.rtyper.debug import ll_assert
8 from rpython.rlib.rarithmetic import r_uint, intmask, LONG_BIT
9 from rpython.rtyper import rmodel
10 from rpython.rtyper.error import TyperError
11
12
13 HIGHEST_BIT = r_uint(intmask(1 << (LONG_BIT - 1)))
14 MASK = r_uint(intmask(HIGHEST_BIT - 1))
15
16 # ____________________________________________________________
17 #
18 # generic implementation of RPython dictionary, with parametric DICTKEY and
19 # DICTVALUE types.
20 #
21 # XXX for immutable dicts, the array should be inlined and
22 # resize_counter and everused are not needed.
23 #
24 # struct dictentry {
25 # DICTKEY key;
26 # bool f_valid; # (optional) the entry is filled
27 # bool f_everused; # (optional) the entry is or has ever been filled
28 # DICTVALUE value;
29 # int f_hash; # (optional) key hash, if hard to recompute
30 # }
31 #
32 # struct dicttable {
33 # int num_items;
34 # int resize_counter;
35 # Array *entries;
36 # (Function DICTKEY, DICTKEY -> bool) *fnkeyeq;
37 # (Function DICTKEY -> int) *fnkeyhash;
38 # }
39 #
40 #
41
42 class DictRepr(AbstractDictRepr):
43
44 def __init__(self, rtyper, key_repr, value_repr, dictkey, dictvalue,
45 custom_eq_hash=None, force_non_null=False, fast_hash=False):
46 # fast_hash is ignored (only implemented in rordereddict.py)
47 self.rtyper = rtyper
48 self.DICT = lltype.GcForwardReference()
49 self.lowleveltype = lltype.Ptr(self.DICT)
50 self.custom_eq_hash = custom_eq_hash is not None
51 if not isinstance(key_repr, rmodel.Repr): # not computed yet, done by setup()
52 assert callable(key_repr)
53 self._key_repr_computer = key_repr
54 else:
55 self.external_key_repr, self.key_repr = self.pickkeyrepr(key_repr)
56 if not isinstance(value_repr, rmodel.Repr): # not computed yet, done by setup()
57 assert callable(value_repr)
58 self._value_repr_computer = value_repr
59 else:
60 self.external_value_repr, self.value_repr = self.pickrepr(value_repr)
61 self.dictkey = dictkey
62 self.dictvalue = dictvalue
63 self.dict_cache = {}
64 self._custom_eq_hash_repr = custom_eq_hash
65 self.force_non_null = force_non_null
66 # setup() needs to be called to finish this initialization
67
68 def _externalvsinternal(self, rtyper, item_repr):
69 return rmodel.externalvsinternal(self.rtyper, item_repr)
70
71 def _setup_repr(self):
72 if 'key_repr' not in self.__dict__:
73 key_repr = self._key_repr_computer()
74 self.external_key_repr, self.key_repr = self.pickkeyrepr(key_repr)
75 if 'value_repr' not in self.__dict__:
76 self.external_value_repr, self.value_repr = self.pickrepr(self._value_repr_computer())
77 if isinstance(self.DICT, lltype.GcForwardReference):
78 self.DICTKEY = self.key_repr.lowleveltype
79 self.DICTVALUE = self.value_repr.lowleveltype
80
81 # compute the shape of the DICTENTRY structure
82 entryfields = []
83 entrymeths = {
84 'allocate': lltype.typeMethod(_ll_malloc_entries),
85 'delete': _ll_free_entries,
86 'must_clear_key': (isinstance(self.DICTKEY, lltype.Ptr)
87 and self.DICTKEY._needsgc()),
88 'must_clear_value': (isinstance(self.DICTVALUE, lltype.Ptr)
89 and self.DICTVALUE._needsgc()),
90 }
91
92 # * the key
93 entryfields.append(("key", self.DICTKEY))
94
95 # * if NULL is not a valid ll value for the key or the value
96 # field of the entry, it can be used as a marker for
97 # never-used entries. Otherwise, we need an explicit flag.
98 s_key = self.dictkey.s_value
99 s_value = self.dictvalue.s_value
100 nullkeymarker = not self.key_repr.can_ll_be_null(s_key)
101 nullvaluemarker = not self.value_repr.can_ll_be_null(s_value)
102 if self.force_non_null:
103 if not nullkeymarker:
104 rmodel.warning("%s can be null, but forcing non-null in dict key" % s_key)
105 nullkeymarker = True
106 if not nullvaluemarker:
107 rmodel.warning("%s can be null, but forcing non-null in dict value" % s_value)
108 nullvaluemarker = True
109 dummykeyobj = self.key_repr.get_ll_dummyval_obj(self.rtyper,
110 s_key)
111 dummyvalueobj = self.value_repr.get_ll_dummyval_obj(self.rtyper,
112 s_value)
113
114 # * the state of the entry - trying to encode it as dummy objects
115 if nullkeymarker and dummykeyobj:
116 # all the state can be encoded in the key
117 entrymeths['everused'] = ll_everused_from_key
118 entrymeths['dummy_obj'] = dummykeyobj
119 entrymeths['valid'] = ll_valid_from_key
120 entrymeths['mark_deleted'] = ll_mark_deleted_in_key
121 # the key is overwritten by 'dummy' when the entry is deleted
122 entrymeths['must_clear_key'] = False
123
124 elif nullvaluemarker and dummyvalueobj:
125 # all the state can be encoded in the value
126 entrymeths['everused'] = ll_everused_from_value
127 entrymeths['dummy_obj'] = dummyvalueobj
128 entrymeths['valid'] = ll_valid_from_value
129 entrymeths['mark_deleted'] = ll_mark_deleted_in_value
130 # value is overwritten by 'dummy' when entry is deleted
131 entrymeths['must_clear_value'] = False
132
133 else:
134 # we need a flag to know if the entry was ever used
135 # (we cannot use a NULL as a marker for this, because
136 # the key and value will be reset to NULL to clear their
137 # reference)
138 entryfields.append(("f_everused", lltype.Bool))
139 entrymeths['everused'] = ll_everused_from_flag
140
141 # can we still rely on a dummy obj to mark deleted entries?
142 if dummykeyobj:
143 entrymeths['dummy_obj'] = dummykeyobj
144 entrymeths['valid'] = ll_valid_from_key
145 entrymeths['mark_deleted'] = ll_mark_deleted_in_key
146 # key is overwritten by 'dummy' when entry is deleted
147 entrymeths['must_clear_key'] = False
148 elif dummyvalueobj:
149 entrymeths['dummy_obj'] = dummyvalueobj
150 entrymeths['valid'] = ll_valid_from_value
151 entrymeths['mark_deleted'] = ll_mark_deleted_in_value
152 # value is overwritten by 'dummy' when entry is deleted
153 entrymeths['must_clear_value'] = False
154 else:
155 entryfields.append(("f_valid", lltype.Bool))
156 entrymeths['valid'] = ll_valid_from_flag
157 entrymeths['mark_deleted'] = ll_mark_deleted_in_flag
158
159 # * the value
160 entryfields.append(("value", self.DICTVALUE))
161
162 # * the hash, if needed
163 if self.custom_eq_hash:
164 fasthashfn = None
165 else:
166 fasthashfn = self.key_repr.get_ll_fasthash_function()
167 if getattr(self.key_repr.get_ll_eq_function(),
168 'no_direct_compare', False):
169 entrymeths['no_direct_compare'] = True
170 if fasthashfn is None:
171 entryfields.append(("f_hash", lltype.Signed))
172 entrymeths['hash'] = ll_hash_from_cache
173 else:
174 entrymeths['hash'] = ll_hash_recomputed
175 entrymeths['fasthashfn'] = fasthashfn
176
177 # Build the lltype data structures
178 self.DICTENTRY = lltype.Struct("dictentry", *entryfields)
179 self.DICTENTRYARRAY = lltype.GcArray(self.DICTENTRY,
180 adtmeths=entrymeths)
181 fields = [ ("num_items", lltype.Signed),
182 ("resize_counter", lltype.Signed),
183 ("entries", lltype.Ptr(self.DICTENTRYARRAY)) ]
184 if self.custom_eq_hash:
185 self.r_rdict_eqfn, self.r_rdict_hashfn = self._custom_eq_hash_repr()
186 fields.extend([ ("fnkeyeq", self.r_rdict_eqfn.lowleveltype),
187 ("fnkeyhash", self.r_rdict_hashfn.lowleveltype) ])
188 adtmeths = {
189 'keyhash': ll_keyhash_custom,
190 'keyeq': ll_keyeq_custom,
191 'r_rdict_eqfn': self.r_rdict_eqfn,
192 'r_rdict_hashfn': self.r_rdict_hashfn,
193 'paranoia': True,
194 }
195 else:
196 # figure out which functions must be used to hash and compare
197 ll_keyhash = self.key_repr.get_ll_hash_function()
198 ll_keyeq = self.key_repr.get_ll_eq_function() # can be None
199 ll_keyhash = lltype.staticAdtMethod(ll_keyhash)
200 if ll_keyeq is not None:
201 ll_keyeq = lltype.staticAdtMethod(ll_keyeq)
202 adtmeths = {
203 'keyhash': ll_keyhash,
204 'keyeq': ll_keyeq,
205 'paranoia': False,
206 }
207 adtmeths['KEY'] = self.DICTKEY
208 adtmeths['VALUE'] = self.DICTVALUE
209 adtmeths['allocate'] = lltype.typeMethod(_ll_malloc_dict)
210 self.DICT.become(lltype.GcStruct("dicttable", adtmeths=adtmeths,
211 *fields))
212
213
214 def convert_const(self, dictobj):
215 # get object from bound dict methods
216 #dictobj = getattr(dictobj, '__self__', dictobj)
217 if dictobj is None:
218 return lltype.nullptr(self.DICT)
219 if not isinstance(dictobj, (dict, objectmodel.r_dict)):
220 raise TypeError("expected a dict: %r" % (dictobj,))
221 try:
222 key = Constant(dictobj)
223 return self.dict_cache[key]
224 except KeyError:
225 self.setup()
226 l_dict = ll_newdict_size(self.DICT, len(dictobj))
227 self.dict_cache[key] = l_dict
228 r_key = self.key_repr
229 if r_key.lowleveltype == llmemory.Address:
230 raise TypeError("No prebuilt dicts of address keys")
231 r_value = self.value_repr
232 if isinstance(dictobj, objectmodel.r_dict):
233 if self.r_rdict_eqfn.lowleveltype != lltype.Void:
234 l_fn = self.r_rdict_eqfn.convert_const(dictobj.key_eq)
235 l_dict.fnkeyeq = l_fn
236 if self.r_rdict_hashfn.lowleveltype != lltype.Void:
237 l_fn = self.r_rdict_hashfn.convert_const(dictobj.key_hash)
238 l_dict.fnkeyhash = l_fn
239 any_items = dictobj._dict.items()
240 else:
241 any_items = dictobj.items()
242 if any_items:
243 raise TyperError("found a prebuilt, explicitly non-ordered, "
244 "non-empty dict. it would require additional"
245 " support to rehash it at program start-up")
246 return l_dict
247
248 def rtype_len(self, hop):
249 v_dict, = hop.inputargs(self)
250 return hop.gendirectcall(ll_dict_len, v_dict)
251
252 def rtype_bool(self, hop):
253 v_dict, = hop.inputargs(self)
254 return hop.gendirectcall(ll_dict_bool, v_dict)
255
256 def make_iterator_repr(self, *variant):
257 return DictIteratorRepr(self, *variant)
258
259 def rtype_method_get(self, hop):
260 v_dict, v_key, v_default = hop.inputargs(self, self.key_repr,
261 self.value_repr)
262 hop.exception_cannot_occur()
263 v_res = hop.gendirectcall(ll_get, v_dict, v_key, v_default)
264 return self.recast_value(hop.llops, v_res)
265
266 def rtype_method_setdefault(self, hop):
267 v_dict, v_key, v_default = hop.inputargs(self, self.key_repr,
268 self.value_repr)
269 hop.exception_cannot_occur()
270 v_res = hop.gendirectcall(ll_setdefault, v_dict, v_key, v_default)
271 return self.recast_value(hop.llops, v_res)
272
273 def rtype_method_copy(self, hop):
274 v_dict, = hop.inputargs(self)
275 hop.exception_cannot_occur()
276 return hop.gendirectcall(ll_copy, v_dict)
277
278 def rtype_method_update(self, hop):
279 v_dic1, v_dic2 = hop.inputargs(self, self)
280 hop.exception_cannot_occur()
281 return hop.gendirectcall(ll_update, v_dic1, v_dic2)
282
283 def rtype_method__prepare_dict_update(self, hop):
284 v_dict, v_num = hop.inputargs(self, lltype.Signed)
285 hop.exception_cannot_occur()
286 hop.gendirectcall(ll_prepare_dict_update, v_dict, v_num)
287
288 def _rtype_method_kvi(self, hop, ll_func):
289 v_dic, = hop.inputargs(self)
290 r_list = hop.r_result
291 cLIST = hop.inputconst(lltype.Void, r_list.lowleveltype.TO)
292 hop.exception_cannot_occur()
293 return hop.gendirectcall(ll_func, cLIST, v_dic)
294
295 def rtype_method_keys(self, hop):
296 return self._rtype_method_kvi(hop, ll_dict_keys)
297
298 def rtype_method_values(self, hop):
299 return self._rtype_method_kvi(hop, ll_dict_values)
300
301 def rtype_method_items(self, hop):
302 return self._rtype_method_kvi(hop, ll_dict_items)
303
304 def rtype_bltn_list(self, hop):
305 return self._rtype_method_kvi(hop, ll_dict_keys)
306
307 def rtype_method_iterkeys(self, hop):
308 hop.exception_cannot_occur()
309 return DictIteratorRepr(self, "keys").newiter(hop)
310
311 def rtype_method_itervalues(self, hop):
312 hop.exception_cannot_occur()
313 return DictIteratorRepr(self, "values").newiter(hop)
314
315 def rtype_method_iteritems(self, hop):
316 hop.exception_cannot_occur()
317 return DictIteratorRepr(self, "items").newiter(hop)
318
319 def rtype_method_clear(self, hop):
320 v_dict, = hop.inputargs(self)
321 hop.exception_cannot_occur()
322 return hop.gendirectcall(ll_clear, v_dict)
323
324 def rtype_method_popitem(self, hop):
325 v_dict, = hop.inputargs(self)
326 r_tuple = hop.r_result
327 cTUPLE = hop.inputconst(lltype.Void, r_tuple.lowleveltype)
328 hop.exception_is_here()
329 return hop.gendirectcall(ll_popitem, cTUPLE, v_dict)
330
331 def rtype_method_pop(self, hop):
332 if hop.nb_args == 2:
333 v_args = hop.inputargs(self, self.key_repr)
334 target = ll_pop
335 elif hop.nb_args == 3:
336 v_args = hop.inputargs(self, self.key_repr, self.value_repr)
337 target = ll_pop_default
338 hop.exception_is_here()
339 v_res = hop.gendirectcall(target, *v_args)
340 return self.recast_value(hop.llops, v_res)
341
342 class __extend__(pairtype(DictRepr, rmodel.Repr)):
343
344 def rtype_getitem((r_dict, r_key), hop):
345 v_dict, v_key = hop.inputargs(r_dict, r_dict.key_repr)
346 if not r_dict.custom_eq_hash:
347 hop.has_implicit_exception(KeyError) # record that we know about it
348 hop.exception_is_here()
349 v_res = hop.gendirectcall(ll_dict_getitem, v_dict, v_key)
350 return r_dict.recast_value(hop.llops, v_res)
351
352 def rtype_delitem((r_dict, r_key), hop):
353 v_dict, v_key = hop.inputargs(r_dict, r_dict.key_repr)
354 if not r_dict.custom_eq_hash:
355 hop.has_implicit_exception(KeyError) # record that we know about it
356 hop.exception_is_here()
357 return hop.gendirectcall(ll_dict_delitem, v_dict, v_key)
358
359 def rtype_setitem((r_dict, r_key), hop):
360 v_dict, v_key, v_value = hop.inputargs(r_dict, r_dict.key_repr, r_dict.value_repr)
361 if r_dict.custom_eq_hash:
362 hop.exception_is_here()
363 else:
364 hop.exception_cannot_occur()
365 hop.gendirectcall(ll_dict_setitem, v_dict, v_key, v_value)
366
367 def rtype_contains((r_dict, r_key), hop):
368 v_dict, v_key = hop.inputargs(r_dict, r_dict.key_repr)
369 hop.exception_is_here()
370 return hop.gendirectcall(ll_contains, v_dict, v_key)
371
372 class __extend__(pairtype(DictRepr, DictRepr)):
373 def convert_from_to((r_dict1, r_dict2), v, llops):
374 # check that we don't convert from Dicts with
375 # different key/value types
376 if r_dict1.dictkey is None or r_dict2.dictkey is None:
377 return NotImplemented
378 if r_dict1.dictkey is not r_dict2.dictkey:
379 return NotImplemented
380 if r_dict1.dictvalue is None or r_dict2.dictvalue is None:
381 return NotImplemented
382 if r_dict1.dictvalue is not r_dict2.dictvalue:
383 return NotImplemented
384 return v
385
386 # ____________________________________________________________
387 #
388 # Low-level methods. These can be run for testing, but are meant to
389 # be direct_call'ed from rtyped flow graphs, which means that they will
390 # get flowed and annotated, mostly with SomePtr.
391
392 def ll_everused_from_flag(entries, i):
393 return entries[i].f_everused
394
395 def ll_everused_from_key(entries, i):
396 return bool(entries[i].key)
397
398 def ll_everused_from_value(entries, i):
399 return bool(entries[i].value)
400
401 def ll_valid_from_flag(entries, i):
402 return entries[i].f_valid
403
404 def ll_mark_deleted_in_flag(entries, i):
405 entries[i].f_valid = False
406
407 def ll_valid_from_key(entries, i):
408 ENTRIES = lltype.typeOf(entries).TO
409 dummy = ENTRIES.dummy_obj.ll_dummy_value
410 return entries.everused(i) and entries[i].key != dummy
411
412 def ll_mark_deleted_in_key(entries, i):
413 ENTRIES = lltype.typeOf(entries).TO
414 dummy = ENTRIES.dummy_obj.ll_dummy_value
415 entries[i].key = dummy
416
417 def ll_valid_from_value(entries, i):
418 ENTRIES = lltype.typeOf(entries).TO
419 dummy = ENTRIES.dummy_obj.ll_dummy_value
420 return entries.everused(i) and entries[i].value != dummy
421
422 def ll_mark_deleted_in_value(entries, i):
423 ENTRIES = lltype.typeOf(entries).TO
424 dummy = ENTRIES.dummy_obj.ll_dummy_value
425 entries[i].value = dummy
426
427 def ll_hash_from_cache(entries, i):
428 return entries[i].f_hash
429
430 def ll_hash_recomputed(entries, i):
431 ENTRIES = lltype.typeOf(entries).TO
432 return ENTRIES.fasthashfn(entries[i].key)
433
434 def ll_get_value(d, i):
435 return d.entries[i].value
436
437 def ll_keyhash_custom(d, key):
438 DICT = lltype.typeOf(d).TO
439 return objectmodel.hlinvoke(DICT.r_rdict_hashfn, d.fnkeyhash, key)
440
441 def ll_keyeq_custom(d, key1, key2):
442 DICT = lltype.typeOf(d).TO
443 return objectmodel.hlinvoke(DICT.r_rdict_eqfn, d.fnkeyeq, key1, key2)
444
445 def ll_dict_len(d):
446 return d.num_items
447
448 def ll_dict_bool(d):
449 # check if a dict is True, allowing for None
450 return bool(d) and d.num_items != 0
451
452 def ll_dict_getitem(d, key):
453 i = ll_dict_lookup(d, key, d.keyhash(key))
454 if not i & HIGHEST_BIT:
455 return ll_get_value(d, i)
456 else:
457 raise KeyError
458
459 def ll_dict_setitem(d, key, value):
460 hash = d.keyhash(key)
461 i = ll_dict_lookup(d, key, hash)
462 return _ll_dict_setitem_lookup_done(d, key, value, hash, i)
463
464 # It may be safe to look inside always, it has a few branches though, and their
465 # frequencies needs to be investigated.
466 @jit.look_inside_iff(lambda d, key, value, hash, i: jit.isvirtual(d) and jit.isconstant(key))
467 def _ll_dict_setitem_lookup_done(d, key, value, hash, i):
468 valid = (i & HIGHEST_BIT) == 0
469 i = i & MASK
470 ENTRY = lltype.typeOf(d.entries).TO.OF
471 entry = d.entries[i]
472 if not d.entries.everused(i):
473 # a new entry that was never used before
474 ll_assert(not valid, "valid but not everused")
475 rc = d.resize_counter - 3
476 if rc <= 0: # if needed, resize the dict -- before the insertion
477 ll_dict_resize(d)
478 i = ll_dict_lookup_clean(d, hash) # then redo the lookup for 'key'
479 entry = d.entries[i]
480 rc = d.resize_counter - 3
481 ll_assert(rc > 0, "ll_dict_resize failed?")
482 d.resize_counter = rc
483 if hasattr(ENTRY, 'f_everused'): entry.f_everused = True
484 entry.value = value
485 else:
486 # override an existing or deleted entry
487 entry.value = value
488 if valid:
489 return
490 entry.key = key
491 if hasattr(ENTRY, 'f_hash'): entry.f_hash = hash
492 if hasattr(ENTRY, 'f_valid'): entry.f_valid = True
493 d.num_items += 1
494
495 def ll_dict_insertclean(d, key, value, hash):
496 # Internal routine used by ll_dict_resize() to insert an item which is
497 # known to be absent from the dict. This routine also assumes that
498 # the dict contains no deleted entries. This routine has the advantage
499 # of never calling d.keyhash() and d.keyeq(), so it cannot call back
500 # to user code. ll_dict_insertclean() doesn't resize the dict, either.
501 i = ll_dict_lookup_clean(d, hash)
502 ENTRY = lltype.typeOf(d.entries).TO.OF
503 entry = d.entries[i]
504 entry.value = value
505 entry.key = key
506 if hasattr(ENTRY, 'f_hash'): entry.f_hash = hash
507 if hasattr(ENTRY, 'f_valid'): entry.f_valid = True
508 if hasattr(ENTRY, 'f_everused'): entry.f_everused = True
509 d.num_items += 1
510 d.resize_counter -= 3
511
512 def ll_dict_delitem(d, key):
513 i = ll_dict_lookup(d, key, d.keyhash(key))
514 if i & HIGHEST_BIT:
515 raise KeyError
516 _ll_dict_del(d, i)
517
518 @jit.look_inside_iff(lambda d, i: jit.isvirtual(d) and jit.isconstant(i))
519 def _ll_dict_del(d, i):
520 d.entries.mark_deleted(i)
521 d.num_items -= 1
522 # clear the key and the value if they are GC pointers
523 ENTRIES = lltype.typeOf(d.entries).TO
524 ENTRY = ENTRIES.OF
525 entry = d.entries[i]
526 if ENTRIES.must_clear_key:
527 entry.key = lltype.nullptr(ENTRY.key.TO)
528 if ENTRIES.must_clear_value:
529 entry.value = lltype.nullptr(ENTRY.value.TO)
530 #
531 # The rest is commented out: like CPython we no longer shrink the
532 # dictionary here. It may shrink later if we try to append a number
533 # of new items to it. Unsure if this behavior was designed in
534 # CPython or is accidental. A design reason would be that if you
535 # delete all items in a dictionary (e.g. with a series of
536 # popitem()), then CPython avoids shrinking the table several times.
537 #num_entries = len(d.entries)
538 #if num_entries > DICT_INITSIZE and d.num_items <= num_entries / 4:
539 # ll_dict_resize(d)
540 # A previous xxx: move the size checking and resize into a single
541 # call which is opaque to the JIT when the dict isn't virtual, to
542 # avoid extra branches.
543
544 def ll_dict_resize(d):
545 # make a 'new_size' estimate and shrink it if there are many
546 # deleted entry markers. See CPython for why it is a good idea to
547 # quadruple the dictionary size as long as it's not too big.
548 # (Quadrupling comes from '(d.num_items + d.num_items + 1) * 2'
549 # as long as num_items is not too large.)
550 num_extra = min(d.num_items + 1, 30000)
551 _ll_dict_resize_to(d, num_extra)
552 ll_dict_resize.oopspec = 'dict.resize(d)'
553
554 def _ll_dict_resize_to(d, num_extra):
555 new_estimate = (d.num_items + num_extra) * 2
556 new_size = DICT_INITSIZE
557 while new_size <= new_estimate:
558 new_size *= 2
559 old_entries = d.entries
560 old_size = len(d.entries)
561 d.entries = lltype.typeOf(old_entries).TO.allocate(new_size)
562 d.num_items = 0
563 d.resize_counter = new_size * 2
564 i = 0
565 while i < old_size:
566 if old_entries.valid(i):
567 hash = old_entries.hash(i)
568 entry = old_entries[i]
569 ll_dict_insertclean(d, entry.key, entry.value, hash)
570 i += 1
571 old_entries.delete()
572
573 # ------- a port of CPython's dictobject.c's lookdict implementation -------
574 PERTURB_SHIFT = 5
575
576 @jit.look_inside_iff(lambda d, key, hash: jit.isvirtual(d) and jit.isconstant(key))
577 @jit.oopspec('dict.lookup(d, key, hash)')
578 def ll_dict_lookup(d, key, hash):
579 entries = d.entries
580 ENTRIES = lltype.typeOf(entries).TO
581 direct_compare = not hasattr(ENTRIES, 'no_direct_compare')
582 mask = len(entries) - 1
583 i = r_uint(hash & mask)
584 # do the first try before any looping
585 if entries.valid(i):
586 checkingkey = entries[i].key
587 if direct_compare and checkingkey == key:
588 return i # found the entry
589 if d.keyeq is not None and entries.hash(i) == hash:
590 # correct hash, maybe the key is e.g. a different pointer to
591 # an equal object
592 found = d.keyeq(checkingkey, key)
593 if d.paranoia:
594 if (entries != d.entries or
595 not entries.valid(i) or entries[i].key != checkingkey):
596 # the compare did major nasty stuff to the dict: start over
597 return ll_dict_lookup(d, key, hash)
598 if found:
599 return i # found the entry
600 freeslot = -1
601 elif entries.everused(i):
602 freeslot = intmask(i)
603 else:
604 return i | HIGHEST_BIT # pristine entry -- lookup failed
605
606 # In the loop, a deleted entry (everused and not valid) is by far
607 # (factor of 100s) the least likely outcome, so test for that last.
608 perturb = r_uint(hash)
609 while 1:
610 # compute the next index using unsigned arithmetic
611 i = (i << 2) + i + perturb + 1
612 i = i & mask
613 # keep 'i' as a signed number here, to consistently pass signed
614 # arguments to the small helper methods.
615 if not entries.everused(i):
616 if freeslot == -1:
617 freeslot = intmask(i)
618 return r_uint(freeslot) | HIGHEST_BIT
619 elif entries.valid(i):
620 checkingkey = entries[i].key
621 if direct_compare and checkingkey == key:
622 return i
623 if d.keyeq is not None and entries.hash(i) == hash:
624 # correct hash, maybe the key is e.g. a different pointer to
625 # an equal object
626 found = d.keyeq(checkingkey, key)
627 if d.paranoia:
628 if (entries != d.entries or
629 not entries.valid(i) or entries[i].key != checkingkey):
630 # the compare did major nasty stuff to the dict:
631 # start over
632 return ll_dict_lookup(d, key, hash)
633 if found:
634 return i # found the entry
635 elif freeslot == -1:
636 freeslot = intmask(i)
637 perturb >>= PERTURB_SHIFT
638
639 def ll_dict_lookup_clean(d, hash):
640 # a simplified version of ll_dict_lookup() which assumes that the
641 # key is new, and the dictionary doesn't contain deleted entries.
642 # It only finds the next free slot for the given hash.
643 entries = d.entries
644 mask = len(entries) - 1
645 i = r_uint(hash & mask)
646 perturb = r_uint(hash)
647 while entries.everused(i):
648 i = (i << 2) + i + perturb + 1
649 i = i & mask
650 perturb >>= PERTURB_SHIFT
651 return i
652
653 # ____________________________________________________________
654 #
655 # Irregular operations.
656
657 DICT_INITSIZE = 8
658
659 def ll_newdict(DICT):
660 d = DICT.allocate()
661 d.entries = DICT.entries.TO.allocate(DICT_INITSIZE)
662 d.num_items = 0
663 d.resize_counter = DICT_INITSIZE * 2
664 return d
665 DictRepr.ll_newdict = staticmethod(ll_newdict)
666
667 def ll_newdict_size(DICT, length_estimate):
668 length_estimate = (length_estimate // 2) * 3
669 n = DICT_INITSIZE
670 while n < length_estimate:
671 n *= 2
672 d = DICT.allocate()
673 d.entries = DICT.entries.TO.allocate(n)
674 d.num_items = 0
675 d.resize_counter = n * 2
676 return d
677
678 # rpython.memory.lldict uses a dict based on Struct and Array
679 # instead of GcStruct and GcArray, which is done by using different
680 # 'allocate' and 'delete' adtmethod implementations than the ones below
681 def _ll_malloc_dict(DICT):
682 return lltype.malloc(DICT)
683 def _ll_malloc_entries(ENTRIES, n):
684 return lltype.malloc(ENTRIES, n, zero=True)
685 def _ll_free_entries(entries):
686 pass
687
688
689 # ____________________________________________________________
690 #
691 # Iteration.
692
693 class DictIteratorRepr(AbstractDictIteratorRepr):
694
695 def __init__(self, r_dict, variant="keys"):
696 self.r_dict = r_dict
697 self.variant = variant
698 self.lowleveltype = lltype.Ptr(lltype.GcStruct('dictiter',
699 ('dict', r_dict.lowleveltype),
700 ('index', lltype.Signed)))
701 self.ll_dictiter = ll_dictiter
702 self._ll_dictnext = _ll_dictnext
703
704
705 def ll_dictiter(ITERPTR, d):
706 iter = lltype.malloc(ITERPTR.TO)
707 iter.dict = d
708 iter.index = 0
709 return iter
710
711 @jit.look_inside_iff(lambda iter: jit.isvirtual(iter)
712 and (iter.dict is None or
713 jit.isvirtual(iter.dict)))
714 @jit.oopspec("dictiter.next(iter)")
715 def _ll_dictnext(iter):
716 dict = iter.dict
717 if dict:
718 entries = dict.entries
719 index = iter.index
720 assert index >= 0
721 entries_len = len(entries)
722 while index < entries_len:
723 nextindex = index + 1
724 if entries.valid(index):
725 iter.index = nextindex
726 return index
727 index = nextindex
728 # clear the reference to the dict and prevent restarts
729 iter.dict = lltype.nullptr(lltype.typeOf(iter).TO.dict.TO)
730 raise StopIteration
731
732 # _____________________________________________________________
733 # methods
734
735 def ll_get(dict, key, default):
736 i = ll_dict_lookup(dict, key, dict.keyhash(key))
737 if not i & HIGHEST_BIT:
738 return ll_get_value(dict, i)
739 else:
740 return default
741
742 def ll_setdefault(dict, key, default):
743 hash = dict.keyhash(key)
744 i = ll_dict_lookup(dict, key, hash)
745 if not i & HIGHEST_BIT:
746 return ll_get_value(dict, i)
747 else:
748 _ll_dict_setitem_lookup_done(dict, key, default, hash, i)
749 return default
750
751 def ll_copy(dict):
752 DICT = lltype.typeOf(dict).TO
753 dictsize = len(dict.entries)
754 d = DICT.allocate()
755 d.entries = DICT.entries.TO.allocate(dictsize)
756 d.num_items = dict.num_items
757 d.resize_counter = dict.resize_counter
758 if hasattr(DICT, 'fnkeyeq'): d.fnkeyeq = dict.fnkeyeq
759 if hasattr(DICT, 'fnkeyhash'): d.fnkeyhash = dict.fnkeyhash
760 i = 0
761 while i < dictsize:
762 d_entry = d.entries[i]
763 entry = dict.entries[i]
764 ENTRY = lltype.typeOf(d.entries).TO.OF
765 d_entry.key = entry.key
766 if hasattr(ENTRY, 'f_valid'): d_entry.f_valid = entry.f_valid
767 if hasattr(ENTRY, 'f_everused'): d_entry.f_everused = entry.f_everused
768 d_entry.value = entry.value
769 if hasattr(ENTRY, 'f_hash'): d_entry.f_hash = entry.f_hash
770 i += 1
771 return d
772 ll_copy.oopspec = 'dict.copy(dict)'
773
774 def ll_clear(d):
775 if (len(d.entries) == DICT_INITSIZE and
776 d.resize_counter == DICT_INITSIZE * 2):
777 return
778 old_entries = d.entries
779 d.entries = lltype.typeOf(old_entries).TO.allocate(DICT_INITSIZE)
780 d.num_items = 0
781 d.resize_counter = DICT_INITSIZE * 2
782 old_entries.delete()
783 ll_clear.oopspec = 'dict.clear(d)'
784
785 def ll_update(dic1, dic2):
786 if dic1 == dic2:
787 return
788 ll_prepare_dict_update(dic1, dic2.num_items)
789 entries = dic2.entries
790 d2len = len(entries)
791 i = 0
792 while i < d2len:
793 if entries.valid(i):
794 entry = entries[i]
795 hash = entries.hash(i)
796 key = entry.key
797 value = entry.value
798 j = ll_dict_lookup(dic1, key, hash)
799 _ll_dict_setitem_lookup_done(dic1, key, value, hash, j)
800 i += 1
801 ll_update.oopspec = 'dict.update(dic1, dic2)'
802
803 def ll_prepare_dict_update(d, num_extra):
804 # Prescale 'd' for 'num_extra' items, assuming that most items don't
805 # collide. If this assumption is false, 'd' becomes too large by at
806 # most 'num_extra'. The logic is based on:
807 # (d.resize_counter - 1) // 3 = room left in d
808 # so, if num_extra == 1, we need d.resize_counter > 3
809 # if num_extra == 2, we need d.resize_counter > 6 etc.
810 # Note however a further hack: if num_extra <= d.num_items,
811 # we avoid calling _ll_dict_resize_to here. This is to handle
812 # the case where dict.update() actually has a lot of collisions.
813 # If num_extra is much greater than d.num_items the conditional_call
814 # will trigger anyway, which is really the goal.
815 x = num_extra - d.num_items
816 jit.conditional_call(d.resize_counter <= x * 3,
817 _ll_dict_resize_to, d, num_extra)
818
819 # this is an implementation of keys(), values() and items()
820 # in a single function.
821 # note that by specialization on func, three different
822 # and very efficient functions are created.
823
824 def recast(P, v):
825 # XXX this function is a terrible hack
826 if P is llmemory.GCREF:
827 return lltype.cast_opaque_ptr(llmemory.GCREF, v)
828 if isinstance(P, lltype.Ptr):
829 return lltype.cast_pointer(P, v)
830 else:
831 return v
832
833 def _make_ll_keys_values_items(kind):
834 def ll_kvi(LIST, dic, EXTERNAL_ELEM=None):
835 res = LIST.ll_newlist(dic.num_items)
836 entries = dic.entries
837 dlen = len(entries)
838 items = res.ll_items()
839 ELEM = lltype.typeOf(items).TO.OF
840 i = 0
841 p = 0
842 while i < dlen:
843 if entries.valid(i):
844 if ELEM is not lltype.Void:
845 entry = entries[i]
846 if kind == 'items':
847 r = lltype.malloc(EXTERNAL_ELEM.TO)
848 r.item0 = recast(EXTERNAL_ELEM.TO.item0, entry.key)
849 r.item1 = recast(EXTERNAL_ELEM.TO.item1, entry.value)
850 items[p] = recast(ELEM, r)
851 elif kind == 'keys':
852 items[p] = recast(ELEM, entry.key)
853 elif kind == 'values':
854 items[p] = recast(ELEM, entry.value)
855 p += 1
856 i += 1
857 assert p == res.ll_length()
858 return res
859 ll_kvi.oopspec = 'dict.%s(dic)' % kind
860 return ll_kvi
861
862 ll_dict_keys = _make_ll_keys_values_items('keys')
863 ll_dict_values = _make_ll_keys_values_items('values')
864 ll_dict_items = _make_ll_keys_values_items('items')
865
866 def ll_contains(d, key):
867 i = ll_dict_lookup(d, key, d.keyhash(key))
868 return not i & HIGHEST_BIT
869
870 POPITEMINDEX = lltype.Struct('PopItemIndex', ('nextindex', lltype.Signed))
871 global_popitem_index = lltype.malloc(POPITEMINDEX, zero=True, immortal=True)
872
873 def _ll_getnextitem(dic):
874 entries = dic.entries
875 ENTRY = lltype.typeOf(entries).TO.OF
876 dmask = len(entries) - 1
877 if hasattr(ENTRY, 'f_hash'):
878 if entries.valid(0):
879 return 0
880 base = entries[0].f_hash
881 else:
882 base = global_popitem_index.nextindex
883 counter = 0
884 while counter <= dmask:
885 i = (base + counter) & dmask
886 counter += 1
887 if entries.valid(i):
888 break
889 else:
890 raise KeyError
891 if hasattr(ENTRY, 'f_hash'):
892 entries[0].f_hash = base + counter
893 else:
894 global_popitem_index.nextindex = base + counter
895 return i
896
897 def ll_popitem(ELEM, dic):
898 i = _ll_getnextitem(dic)
899 entry = dic.entries[i]
900 r = lltype.malloc(ELEM.TO)
901 r.item0 = recast(ELEM.TO.item0, entry.key)
902 r.item1 = recast(ELEM.TO.item1, entry.value)
903 _ll_dict_del(dic, r_uint(i))
904 return r
905
906 def ll_pop(dic, key):
907 i = ll_dict_lookup(dic, key, dic.keyhash(key))
908 if not i & HIGHEST_BIT:
909 value = ll_get_value(dic, r_uint(i))
910 _ll_dict_del(dic, r_uint(i))
911 return value
912 else:
913 raise KeyError
914
915 def ll_pop_default(dic, key, dfl):
916 try:
917 return ll_pop(dic, key)
918 except KeyError:
919 return dfl