Debian Codegraph @

pypy/objspace/std/mapdict.py

raw symbols SCIP
1 import weakref, sys
2
3 from rpython.rlib import jit, objectmodel, debug, rerased
4 from rpython.rlib.rarithmetic import intmask, r_uint, LONG_BIT
5 from rpython.rlib.longlong2float import longlong2float, float2longlong
6 from rpython.rlib.rweakref import dead_ref
7
8 from pypy.interpreter.baseobjspace import W_Root
9 from pypy.interpreter.typedef import _share_methods
10 from pypy.objspace.std.dictmultiobject import (
11 W_DictMultiObject, DictStrategy, ObjectDictStrategy, BaseKeyIterator,
12 BaseValueIterator, BaseItemIterator, _never_equal_to_string,
13 W_DictObject, UnicodeDictStrategy
14 )
15 from pypy.objspace.std.typeobject import MutableCell
16
17
18 # this file implements the various features of subclassing of builtin types
19 # (including object): a dict, weakrefs, slots, etc
20 # https://www.pypy.org/posts/2010/11/efficiently-implementing-python-objects-3838329944323946932.html
21 # the various mixins are combined together in
22 # pypy.interpreter.typedef.get_unique_interplevel_subclass
23
24
25 erase_item, unerase_item = rerased.new_erasing_pair("mapdict storage item")
26 erase_map, unerase_map = rerased.new_erasing_pair("map")
27 erase_list, unerase_list = rerased.new_erasing_pair("mapdict storage list")
28 erase_unboxed, unerase_unboxed = rerased.new_erasing_pair("mapdict unwrapped storage")
29
30 ALLOW_UNBOXING_INTS = LONG_BIT == 64
31
32 # ____________________________________________________________
33 # attribute shapes
34
35 NUM_DIGITS = 4
36 NUM_DIGITS_POW2 = 1 << NUM_DIGITS
37 # note: we use "x * NUM_DIGITS_POW2" instead of "x << NUM_DIGITS" because
38 # we want to propagate knowledge that the result cannot be negative
39
40 # the maximum number of attributes stored in mapdict (afterwards just use a
41 # dict)
42 LIMIT_MAP_ATTRIBUTES = 80
43
44
45 class AbstractAttribute(object):
46 _immutable_fields_ = ['terminator']
47 _attrs_ = ['terminator', 'space', 'cache_attrs']
48 cache_attrs = None
49
50 def __init__(self, space, terminator):
51 self.space = space
52 assert isinstance(terminator, Terminator)
53 self.terminator = terminator
54
55 def read(self, obj, name, attrkind):
56 attr = self.find_map_attr(name, attrkind)
57 if attr is None:
58 return self.terminator._read_terminator(obj, name, attrkind)
59 if (
60 jit.isconstant(attr) and
61 jit.isconstant(obj) and
62 not attr.ever_mutated
63 ):
64 return attr._pure_direct_read(obj)
65 else:
66 return attr._direct_read(obj)
67
68 def write(self, obj, name, attrkind, w_value):
69 attr = self.find_map_attr(name, attrkind)
70 if attr is None:
71 return self.terminator._write_terminator(obj, name, attrkind, w_value)
72 if not attr.ever_mutated:
73 attr.ever_mutated = True
74 attr._direct_write(obj, w_value)
75 return True
76
77 def delete(self, obj, name, attrkind):
78 return None
79
80 @jit.elidable
81 def find_map_attr(self, name, attrkind):
82 # attr cache
83 assert isinstance(name, str) # utf8-encoded
84 space = self.space
85 cache = space.fromcache(MapAttrCache)
86 SHIFT2 = r_uint.BITS - space.config.objspace.std.methodcachesizeexp
87 SHIFT1 = SHIFT2 - 5
88 attrs_as_int = objectmodel.current_object_addr_as_int(self)
89 # ^^^Note: see comment in typeobject.py for
90 # _pure_lookup_where_with_method_cache()
91
92 # unrolled hash computation for 2-tuple
93 c1 = 0x345678
94 c2 = 1000003
95 hash_name = objectmodel.compute_hash(name)
96 hash_selector = intmask((c2 * ((c2 * c1) ^ hash_name)) ^ attrkind)
97 product = intmask(attrs_as_int * hash_selector)
98 attr_hash = (r_uint(product) ^ (r_uint(product) << SHIFT1)) >> SHIFT2
99 # ^^^Note2: same comment too
100 cached_attr = cache.attrs[attr_hash]
101 if cached_attr is self:
102 cached_name = cache.names[attr_hash]
103 cached_index = cache.indexes[attr_hash]
104 if cached_name == name and cached_index == attrkind:
105 attr = cache.cached_attrs[attr_hash]
106 if space.config.objspace.std.withmethodcachecounter:
107 cache.hits[name] = cache.hits.get(name, 0) + 1
108 return attr
109 attr = self._find_map_attr(name, attrkind)
110 if space._side_effects_ok():
111 cache.attrs[attr_hash] = self
112 cache.names[attr_hash] = name
113 cache.indexes[attr_hash] = attrkind
114 cache.cached_attrs[attr_hash] = attr
115 if space.config.objspace.std.withmethodcachecounter:
116 cache.misses[name] = cache.misses.get(name, 0) + 1
117 return attr
118
119 def _find_map_attr(self, name, attrkind):
120 while isinstance(self, PlainAttribute):
121 if attrkind == self.attrkind and name == self.name:
122 return self
123 self = self.back
124 return None
125
126 def copy(self, obj):
127 raise NotImplementedError("abstract base class")
128
129 def storage_needed(self):
130 """ number of storage slots needed to represent the content of an
131 instance that uses self as its map """
132 raise NotImplementedError("abstract base class")
133
134 def num_attributes(self):
135 """ number of attributes represented by self. """
136 raise NotImplementedError("abstract base class")
137
138 def get_terminator(self):
139 return self.terminator
140
141 def set_terminator(self, obj, terminator):
142 raise NotImplementedError("abstract base class")
143
144 def search(self, attrtype):
145 return None
146
147 @jit.elidable
148 def _get_new_attr(self, name, attrkind, unbox_type):
149 cache = self.cache_attrs
150 if cache is None:
151 cache = self.cache_attrs = {}
152 key = (name, attrkind)
153 holder = cache.get(key, None)
154 if holder is None:
155 holder = cache[key] = CachedAttributeHolder(name, attrkind, self, unbox_type)
156 return holder
157
158 def add_attr(self, obj, name, attrkind, w_value):
159 space = self.space
160 unbox_type = self._pick_unbox_type(w_value)
161 number_to_readd, holder = self._find_branch_to_move_into(name, attrkind, unbox_type)
162 attr = holder.pick_attr(unbox_type)
163 if not number_to_readd:
164 attr._switch_map_and_write_increase_storage1(obj, w_value)
165 else:
166 # we found the attributes further up, need to save the previous
167 # values of the attributes we passed. this is the complicated case,
168 # use _reorder_and_add for it.
169 self._reorder_and_add(obj, number_to_readd, attr, w_value)
170
171 @jit.elidable
172 def _find_branch_to_move_into(self, name, attrkind, unbox_type):
173 # walk up the map chain to find an ancestor with lower order that
174 # already has the current name as a child inserted
175 current_order = sys.maxint
176 number_to_readd = 0
177 current = self
178 key = (name, attrkind)
179 while True:
180 holder = None
181 if current.cache_attrs is not None:
182 holder = current.cache_attrs.get(key, None)
183 if holder is None or holder.order > current_order:
184 # we reached the top, so we didn't find it anywhere,
185 # just add it to the top attribute
186 if not isinstance(current, PlainAttribute):
187 return 0, self._get_new_attr(name, attrkind, unbox_type)
188
189 else:
190 return number_to_readd, holder
191 # if not found try parent
192 number_to_readd += 1
193 current_order = current.order
194 current = current.back
195
196 def _pick_unbox_type(self, w_value):
197 if self.terminator.allow_unboxing:
198 if ALLOW_UNBOXING_INTS and type(w_value) is self.space.IntObjectCls:
199 return self.space.IntObjectCls
200 elif type(w_value) is self.space.FloatObjectCls:
201 return self.space.FloatObjectCls
202 return None
203
204 @jit.look_inside_iff(lambda self, obj, number_to_readd, attr, w_value:
205 jit.isconstant(self) and
206 jit.isconstant(attr) and
207 jit.isconstant(number_to_readd))
208 def _reorder_and_add(self, obj, number_to_readd, attr, w_value):
209 # the idea is as follows: the subtrees of any map are ordered by
210 # insertion. the invariant is that subtrees that are inserted later
211 # must not contain the name of the attribute of any earlier inserted
212 # attribute anywhere
213 # m______
214 # inserted first / \ ... \ further attributes
215 # attrname a 0/ 1\ n\
216 # m a must not appear here anywhere
217 #
218 # when inserting a new attribute in an object we check whether any
219 # parent of lower order has seen that attribute yet. if yes, we follow
220 # that branch. if not, we normally append that attribute. When we
221 # follow a prior branch, we necessarily remove some attributes to be
222 # able to do that. They need to be re-added, which has to follow the
223 # reordering procedure recusively.
224
225 # we store the to-be-readded attribute in the stack, with the map and
226 # the value paired up
227 stack = [erase_map(None)] * (self.num_attributes() * 2)
228 stack_index = 0
229 while True:
230 # we found the attributes further up, need to save the
231 # previous values of the attributes we passed
232 if number_to_readd:
233 current = self
234 for i in range(number_to_readd):
235 assert isinstance(current, PlainAttribute)
236 w_self_value = current._prim_direct_read(obj)
237 stack[stack_index] = erase_map(current)
238 stack[stack_index + 1] = erase_item(w_self_value)
239 stack_index += 2
240 current = current.back
241 obj._mapdict_pop_attribute(current)
242 attr._switch_map_and_write_increase_storage1(obj, w_value)
243
244 if not stack_index:
245 assert stack is not None
246 return
247
248 # readd the current top of the stack
249 stack_index -= 2
250 next_map = unerase_map(stack[stack_index])
251 w_value = unerase_item(stack[stack_index + 1])
252 name = next_map.name
253 attrkind = next_map.attrkind
254 self = obj._get_mapdict_map()
255 unbox_type = self._pick_unbox_type(w_value)
256 number_to_readd, holder = self._find_branch_to_move_into(name, attrkind, unbox_type)
257 attr = holder.pick_attr(unbox_type)
258
259 def materialize_r_dict(self, space, obj, dict_w):
260 raise NotImplementedError("abstract base class")
261
262 def materialize_str_dict(self, space, obj, str_dict):
263 raise NotImplementedError("abstract base class")
264
265 def remove_dict_entries(self, obj):
266 raise NotImplementedError("abstract base class")
267
268 def repr(self):
269 return "<%s>" % (self.__class__.__name__,)
270
271 def __repr__(self):
272 return self.repr()
273
274 def view(self):
275 from dotviewer import graphclient
276 import pytest
277 from rpython.translator.tool.make_dot import DotGen
278 dotgen = DotGen('resop')
279 seen = set()
280 self._dot(dotgen, seen, color="green")
281 p = pytest.ensuretemp("mapdict").join("temp.dot")
282 p.write(dotgen.generate(target=None))
283 graphclient.display_dot_file(str(p))
284
285 def _dotlabel(self):
286 return [self.__class__.__name__]
287
288 def _dot(self, dotgen, seen, color="white"):
289 if self in seen:
290 return
291 seen.add(self)
292 dotgen.emit_node(str(id(self)), shape="box", label="\\l".join(self._dotlabel() + ['']), fillcolor=color)
293 if hasattr(self, 'back'):
294 dotgen.emit_edge(str(id(self)), str(id(self.back)), "back")
295 self.back._dot(dotgen, seen)
296 if self.cache_attrs is None:
297 return
298 for (attrname, kind), holder in self.cache_attrs.iteritems():
299 label = [attrname, attrkind_name(kind), str(holder.typ)]
300 dotgen.emit_edge(str(id(self)), str(id(holder.attr)), " ".join(label))
301 holder.attr._dot(dotgen, seen)
302
303
304 class Terminator(AbstractAttribute):
305 _immutable_fields_ = ['w_cls', 'allow_unboxing?']
306
307 def __init__(self, space, w_cls):
308 AbstractAttribute.__init__(self, space, self)
309 self.w_cls = w_cls
310 self.allow_unboxing = True
311
312 def _read_terminator(self, obj, name, attrkind):
313 return None
314
315 def _write_terminator(self, obj, name, attrkind, w_value):
316 obj._get_mapdict_map().add_attr(obj, name, attrkind, w_value)
317 if attrkind == DICT and obj._get_mapdict_map().num_attributes() >= LIMIT_MAP_ATTRIBUTES:
318 space = self.space
319 w_dict = obj.getdict(space)
320 assert isinstance(w_dict, W_DictMultiObject)
321 strategy = w_dict.get_strategy()
322 assert isinstance(strategy, MapDictStrategy)
323 strategy.switch_to_text_strategy(w_dict)
324 return True
325
326 def copy(self, obj):
327 result = Object()
328 result.space = self.space
329 result._mapdict_init_empty(self)
330 return result
331
332 def storage_needed(self):
333 return 0
334
335 def num_attributes(self):
336 return 0
337
338 def set_terminator(self, obj, terminator):
339 result = Object()
340 result.space = self.space
341 result._mapdict_init_empty(terminator)
342 return result
343
344 def remove_dict_entries(self, obj):
345 return self.copy(obj)
346
347 def _dotlabel(self):
348 res = [self.__class__.__name__, str(self.w_cls)]
349 if self.allow_unboxing:
350 res.append("allow unboxing")
351 return res
352
353 def repr(self):
354 return "<%s w_cls=%s>" % (self.__class__.__name__, self.w_cls)
355
356 class DictTerminator(Terminator):
357 _immutable_fields_ = ['devolved_dict_terminator']
358 def __init__(self, space, w_cls):
359 Terminator.__init__(self, space, w_cls)
360 self.devolved_dict_terminator = DevolvedDictTerminator(space, w_cls)
361
362 def materialize_r_dict(self, space, obj, dict_w):
363 return self._make_devolved(space)
364
365 def materialize_str_dict(self, space, obj, dict_w):
366 return self._make_devolved(space)
367
368 def _make_devolved(self, space):
369 result = Object()
370 result.space = space
371 result._mapdict_init_empty(self.devolved_dict_terminator)
372 return result
373
374
375 class NoDictTerminator(Terminator):
376 def _write_terminator(self, obj, name, attrkind, w_value):
377 if attrkind == DICT:
378 return False
379 return Terminator._write_terminator(self, obj, name, attrkind, w_value)
380
381
382 class DevolvedDictTerminator(Terminator):
383 def _read_terminator(self, obj, name, attrkind):
384 if attrkind == DICT:
385 space = self.space
386 w_dict = obj.getdict(space)
387 return space.finditem_str(w_dict, name)
388 return Terminator._read_terminator(self, obj, name, attrkind)
389
390 def _write_terminator(self, obj, name, attrkind, w_value):
391 if attrkind == DICT:
392 space = self.space
393 w_dict = obj.getdict(space)
394 space.setitem_str(w_dict, name, w_value)
395 return True
396 return Terminator._write_terminator(self, obj, name, attrkind, w_value)
397
398 def delete(self, obj, name, attrkind):
399 from pypy.interpreter.error import OperationError
400 if attrkind == DICT:
401 space = self.space
402 w_dict = obj.getdict(space)
403 try:
404 space.delitem(w_dict, space.newtext(name))
405 except OperationError as ex:
406 if not ex.match(space, space.w_KeyError):
407 raise
408 return Terminator.copy(self, obj)
409 return Terminator.delete(self, obj, name, attrkind)
410
411 def remove_dict_entries(self, obj):
412 assert 0, "should be unreachable"
413
414 def set_terminator(self, obj, terminator):
415 if not isinstance(terminator, DevolvedDictTerminator):
416 assert isinstance(terminator, DictTerminator)
417 terminator = terminator.devolved_dict_terminator
418 return Terminator.set_terminator(self, obj, terminator)
419
420 class PlainAttribute(AbstractAttribute):
421 _immutable_fields_ = ['name', 'attrkind', 'storageindex', '_num_attributes', 'back', 'ever_mutated?', 'order']
422
423 def __init__(self, name, attrkind, back, order):
424 AbstractAttribute.__init__(self, back.space, back.terminator)
425 self.name = name
426 self.attrkind = attrkind
427 self.storageindex = back.storage_needed()
428 self._num_attributes = back.num_attributes() + 1
429 self.back = back
430 self.ever_mutated = False
431 self.order = order
432
433 def _copy_attr(self, obj, new_obj):
434 w_value = self._prim_direct_read(obj)
435 new_obj._get_mapdict_map().add_attr(new_obj, self.name, self.attrkind, w_value)
436
437 def _direct_read(self, obj):
438 return unerase_item(obj._mapdict_read_storage(self.storageindex))
439
440 _prim_direct_read = _direct_read
441
442 @jit.elidable
443 def _pure_direct_read(self, obj):
444 return unerase_item(obj._mapdict_read_storage(self.storageindex))
445
446 def _direct_write(self, obj, w_value):
447 obj._mapdict_write_storage(self.storageindex, erase_item(w_value))
448
449 def _switch_map_and_write_increase_storage1(self, obj, w_value):
450 """ switches map and writes w_value as the newest attribute value to
451 obj. this is the "regular" case, were storage can only increase by at
452 most one, not decrease or any other funny nonsense. """
453 if self.storage_needed() > obj._mapdict_storage_length():
454 obj._set_mapdict_increase_storage1(self, erase_item(w_value))
455 return
456 # the order is important here: first change the map, then the storage,
457 # for the benefit of the special subclasses
458 obj._set_mapdict_map(self)
459 self._direct_write(obj, w_value)
460
461 def delete(self, obj, name, attrkind):
462 if attrkind == self.attrkind and name == self.name:
463 # ok, attribute is deleted
464 if not self.ever_mutated:
465 self.ever_mutated = True
466 return self.back.copy(obj)
467 new_obj = self.back.delete(obj, name, attrkind)
468 if new_obj is not None:
469 self._copy_attr(obj, new_obj)
470 return new_obj
471
472 def copy(self, obj):
473 new_obj = self.back.copy(obj)
474 self._copy_attr(obj, new_obj)
475 return new_obj
476
477 def storage_needed(self):
478 return self.storageindex + 1
479
480 def num_attributes(self):
481 return self._num_attributes
482
483 def set_terminator(self, obj, terminator):
484 new_obj = self.back.set_terminator(obj, terminator)
485 self._copy_attr(obj, new_obj)
486 return new_obj
487
488 def search(self, attrtype):
489 if self.attrkind == attrtype:
490 return self
491 return self.back.search(attrtype)
492
493 def materialize_r_dict(self, space, obj, dict_w):
494 new_obj = self.back.materialize_r_dict(space, obj, dict_w)
495 if self.attrkind == DICT:
496 w_attr = space.newtext(self.name)
497 dict_w[w_attr] = self._prim_direct_read(obj)
498 else:
499 self._copy_attr(obj, new_obj)
500 return new_obj
501
502 def materialize_str_dict(self, space, obj, str_dict):
503 new_obj = self.back.materialize_str_dict(space, obj, str_dict)
504 if self.attrkind == DICT:
505 w_key = space.newtext(self.name)
506 str_dict[w_key] = self._prim_direct_read(obj)
507 else:
508 self._copy_attr(obj, new_obj)
509 return new_obj
510
511 def remove_dict_entries(self, obj):
512 new_obj = self.back.remove_dict_entries(obj)
513 if self.attrkind != DICT:
514 self._copy_attr(obj, new_obj)
515 return new_obj
516
517 def _dotlabel(self):
518 res = [self.name, attrkind_name(self.attrkind),
519 "order: %s" % self.order,
520 "storage index: %s" % self.storageindex]
521 if not self.ever_mutated:
522 res.append("immutable")
523 return res
524
525 def repr(self):
526 return "<PlainAttribute %s %s %s%s %s>" % (
527 self.name, attrkind_name(self.attrkind), self.storageindex,
528 " immutable" if not self.ever_mutated else "",
529 self.back.repr())
530
531
532 class UnboxedPlainAttribute(PlainAttribute):
533 _immutable_fields_ = ["listindex", "firstunwrapped", "typ"]
534 def __init__(self, name, attrkind, back, order, typ):
535 AbstractAttribute.__init__(self, back.space, back.terminator)
536 # don't call PlainAttribute.__init__, that runs into weird problems
537 self.name = name
538 self.attrkind = attrkind
539 self.back = back
540 self.ever_mutated = False
541 self.order = order
542 # here, storageindex is where the list of floats is stored
543 # and listindex is where in the list the actual value goes
544 self.firstunwrapped = False
545 self._compute_storageindex_listindex()
546 self._num_attributes = back.num_attributes() + 1
547 self.typ = typ
548
549 def _compute_storageindex_listindex(self):
550 attr = self.back
551 storageindex = -1
552 while isinstance(attr, PlainAttribute):
553 if isinstance(attr, UnboxedPlainAttribute):
554 storageindex = attr.storageindex
555 listindex = attr.listindex + 1
556 break
557 attr = attr.back
558 else:
559 storageindex = self.back.storage_needed()
560 listindex = 0
561 self.firstunwrapped = True
562 self.storageindex = storageindex
563 self.listindex = listindex
564
565 def storage_needed(self):
566 if self.firstunwrapped:
567 return self.storageindex + 1
568 return self.back.storage_needed()
569
570
571 def _unbox(self, w_value):
572 space = self.space
573 assert type(w_value) is self.typ
574 if type(w_value) is space.IntObjectCls:
575 return space.int_w(w_value)
576 else:
577 return float2longlong(space.float_w(w_value))
578
579 def _box(self, val):
580 space = self.space
581 if self.typ is space.IntObjectCls:
582 return space.newint(val)
583 else:
584 return space.newfloat(longlong2float(val))
585
586 def _convert_to_boxed(self, obj):
587 new_obj = obj._get_mapdict_map().copy(obj)
588 map = new_obj.map
589 obj._set_mapdict_storage_and_map(new_obj.storage, map)
590 return map
591
592 def _direct_read(self, obj):
593 w_res = self._prim_direct_read(obj)
594 if self.terminator.allow_unboxing == False:
595 # oops, some other object using the same class isn't type stable!
596 # stop using unboxing altogether to not get too many variants of maps
597 self._convert_to_boxed(obj)
598 return w_res
599
600 def _prim_direct_read(self, obj):
601 return self._box(unerase_unboxed(obj._mapdict_read_storage(self.storageindex))[self.listindex])
602
603 def _pure_direct_read(self, obj):
604 # somewhat tricky! note that _direct_read isn't really elidable (it has
605 # potential side effects, and the boxes aren't always the same)
606 # but _pure_unboxed_read is elidable, and we can let the jit see the
607 # boxing
608 return self._box(self._pure_unboxed_read(obj))
609
610 @jit.elidable
611 def _pure_unboxed_read(self, obj):
612 return unerase_unboxed(obj._mapdict_read_storage(self.storageindex))[self.listindex]
613
614 def _direct_write(self, obj, w_value):
615 if type(w_value) is self.typ:
616 val = self._unbox(w_value)
617 unboxed = unerase_unboxed(obj._mapdict_read_storage(self.storageindex))
618 unboxed[self.listindex] = val
619 return
620 # type change not supposed to happen. according to the principle
621 # of type freezing, we just give up, and will never unbox anything
622 # from that class again
623 self.terminator.allow_unboxing = False
624 map = self._convert_to_boxed(obj)
625 # now obj won't have any UnboxedPlainAttribute in its chain any
626 # more, because allow_unboxing is False
627 map.write(obj, self.name, self.attrkind, w_value)
628
629 def _switch_map_and_write_increase_storage1(self, obj, w_value):
630 val = self._unbox(w_value)
631 if self.firstunwrapped:
632 unboxed = erase_unboxed(debug.make_sure_not_resized([val]))
633 if self.storage_needed() > obj._mapdict_storage_length():
634 obj._set_mapdict_increase_storage1(self, unboxed)
635 return
636
637 obj._set_mapdict_map(self)
638 obj._mapdict_write_storage(self.storageindex, unboxed)
639 else:
640 unboxed = unerase_unboxed(obj._mapdict_read_storage(self.storageindex))
641 obj._set_mapdict_map(self)
642 assert len(unboxed) == self.listindex
643 jit.record_exact_value(len(unboxed), self.listindex)
644 assert len(unboxed) == self.listindex
645 unboxed = unboxed + [val]
646 obj._mapdict_write_storage(self.storageindex, erase_unboxed(unboxed))
647
648 def _dotlabel(self):
649 res = ["unboxed",
650 self.name, attrkind_name(self.attrkind),
651 "order: %s" % self.order,
652 "storage index: %s" % self.storageindex,
653 "list index: %s" % self.listindex]
654 if not self.ever_mutated:
655 res.append("immutable")
656 if self.firstunwrapped:
657 res.append("first unwrapped")
658 return res
659
660 def repr(self):
661 return "<UnboxedPlainAttribute %s %s %s %s%s %s>" % (
662 self.name, attrkind_name(self.attrkind), self.storageindex,
663 self.listindex,
664 " immutable" if not self.ever_mutated else "",
665 self.back.repr())
666
667
668 class CachedAttributeHolder(object):
669 _immutable_fields_ = ['attr?', 'typ?']
670
671 def __init__(self, name, attrkind, back, unbox_type):
672 self.order = len(back.cache_attrs) if back.cache_attrs else 0
673 if unbox_type is None:
674 attr = PlainAttribute(name, attrkind, back, self.order)
675 else:
676 attr = UnboxedPlainAttribute(name, attrkind, back, self.order, unbox_type)
677 self.attr = attr
678 self.typ = unbox_type
679
680 def pick_attr(self, unbox_type):
681 if self.typ is None or self.typ is unbox_type:
682 return self.attr
683 self.typ = None
684 # this will never be traced, because the previous assignment
685 # invalidates a quasi-immutable field
686 self.attr.terminator.allow_unboxing = False
687 name = self.attr.name
688 attrkind = self.attr.attrkind
689 back = self.attr.back
690 attr = self.attr = PlainAttribute(name, attrkind, back, self.order)
691 return attr
692
693
694 class MapAttrCache(object):
695 def __init__(self, space):
696 SIZE = 1 << space.config.objspace.std.methodcachesizeexp
697 self.attrs = [None] * SIZE
698 self.names = [None] * SIZE
699 self.indexes = [INVALID] * SIZE
700 self.cached_attrs = [None] * SIZE
701 if space.config.objspace.std.withmethodcachecounter:
702 self.hits = {}
703 self.misses = {}
704
705 def clear(self):
706 for i in range(len(self.attrs)):
707 self.attrs[i] = None
708 for i in range(len(self.names)):
709 self.names[i] = None
710 self.indexes[i] = INVALID
711 for i in range(len(self.cached_attrs)):
712 self.cached_attrs[i] = None
713
714 def _cleanup_(self):
715 self.clear()
716
717 # ____________________________________________________________
718 # object implementation
719
720 DICT = 0
721 SPECIAL = 1
722 INVALID = 2
723 SLOTS_STARTING_FROM = 3
724
725 def attrkind_name(attrkind):
726 if attrkind == DICT:
727 return "DICT"
728 if attrkind == SPECIAL:
729 return "SPECIAL"
730 if attrkind == INVALID:
731 return "INVALID"
732 return str(attrkind)
733
734 # a little bit of a mess of mixin classes that implement various pieces of
735 # objspace user object functionality in terms of mapdict
736
737 class BaseUserClassMapdict:
738 # everything that's needed to use mapdict for a user subclass at all.
739 # This immediately makes slots possible.
740
741 # assumes presence of _get_mapdict_map, _set_mapdict_map
742 # _mapdict_init_empty, _mapdict_read_storage,
743 # _mapdict_write_storage, _mapdict_storage_length,
744 # _set_mapdict_storage_and_map
745
746 # _____________________________________________
747 # objspace interface
748
749 # class access
750
751 def getclass(self, space):
752 return self._get_mapdict_map().terminator.w_cls
753
754 def setclass(self, space, w_cls):
755 new_obj = self._get_mapdict_map().set_terminator(self, w_cls.terminator)
756 self._set_mapdict_storage_and_map(new_obj.storage, new_obj.map)
757
758 def user_setup(self, space, w_subtype):
759 assert (not self.typedef.hasdict or
760 isinstance(w_subtype.terminator, NoDictTerminator))
761 self._mapdict_init_empty(w_subtype.terminator)
762
763
764 # methods needed for slots
765
766 def getslotvalue(self, slotindex):
767 attrkind = SLOTS_STARTING_FROM + slotindex
768 return self._get_mapdict_map().read(self, "slot", attrkind)
769
770 def setslotvalue(self, slotindex, w_value):
771 attrkind = SLOTS_STARTING_FROM + slotindex
772 self._get_mapdict_map().write(self, "slot", attrkind, w_value)
773
774 def delslotvalue(self, slotindex):
775 attrkind = SLOTS_STARTING_FROM + slotindex
776 new_obj = self._get_mapdict_map().delete(self, "slot", attrkind)
777 if new_obj is None:
778 return False
779 self._set_mapdict_storage_and_map(new_obj.storage, new_obj.map)
780 return True
781
782
783 class MapdictWeakrefSupport(object):
784 # stuff used by the _weakref implementation
785
786 def getweakref(self):
787 from pypy.module._weakref.interp__weakref import WeakrefLifeline
788 lifeline = self._get_mapdict_map().read(self, "weakref", SPECIAL)
789 if lifeline is None:
790 return None
791 assert isinstance(lifeline, WeakrefLifeline)
792 return lifeline
793 getweakref._cannot_really_call_random_things_ = True
794
795 def setweakref(self, space, weakreflifeline):
796 from pypy.module._weakref.interp__weakref import WeakrefLifeline
797 assert isinstance(weakreflifeline, WeakrefLifeline)
798 self._get_mapdict_map().write(self, "weakref", SPECIAL, weakreflifeline)
799 setweakref._cannot_really_call_random_things_ = True
800
801 def delweakref(self):
802 self._get_mapdict_map().write(self, "weakref", SPECIAL, None)
803 delweakref._cannot_really_call_random_things_ = True
804
805
806 class MapdictHPySupport(object):
807 # methods used by hpy to attach the raw storage to an instance of an
808 # hpy-defined subclass
809
810 def _hpy_get_raw_storage(self, space):
811 # XXX move this logic to pypy.module._hpy_universal
812 from pypy.module._hpy_universal.interp_type import storage_get_raw_data, HPyStorageHolder
813 from rpython.rtyper.lltypesystem import rffi
814 holder = self._get_mapdict_map().read(self, "hpy", SPECIAL)
815 if holder is None:
816 return rffi.cast(rffi.VOIDP, 0)
817 assert isinstance(holder, HPyStorageHolder)
818 return storage_get_raw_data(holder.storage)
819
820 def _hpy_get_gc_storage(self, space):
821 # XXX move this logic to pypy.module._hpy_universal
822 from pypy.module._hpy_universal.interp_type import HPyStorageHolder
823 from rpython.rtyper.lltypesystem import rffi
824 holder = self._get_mapdict_map().read(self, "hpy", SPECIAL)
825 assert isinstance(holder, HPyStorageHolder)
826 return holder.storage
827
828 def _hpy_set_raw_storage(self, space, storage):
829 from pypy.module._hpy_universal.interp_type import HPyStorageHolder
830 from rpython.rtyper.lltypesystem import lltype
831 # XXX for now the HPyStorageHolder indirection is because all the
832 # mapdict fields are W_Root instances. we could lift this restriction
833 # with some work and save an indirection
834 holder = self._get_mapdict_map().read(self, "hpy", SPECIAL)
835 if holder is None:
836 holder = HPyStorageHolder()
837 self._get_mapdict_map().write(self, "hpy", SPECIAL, holder)
838 assert isinstance(holder, HPyStorageHolder)
839 holder.storage = storage
840
841
842 class MapdictDictSupport(object):
843
844 # objspace interface for dictionary operations
845
846 def getdictvalue(self, space, attrname):
847 return self._get_mapdict_map().read(self, attrname, DICT)
848
849 def setdictvalue(self, space, attrname, w_value):
850 return self._get_mapdict_map().write(self, attrname, DICT, w_value)
851
852 def deldictvalue(self, space, attrname):
853 new_obj = self._get_mapdict_map().delete(self, attrname, DICT)
854 if new_obj is None:
855 return False
856 self._set_mapdict_storage_and_map(new_obj.storage, new_obj.map)
857 return True
858
859 def getdict(self, space):
860 return _obj_getdict(self, space)
861
862 def setdict(self, space, w_dict):
863 _obj_setdict(self, space, w_dict)
864
865 # a couple of helpers for the classes above, factored out to reduce
866 # the translated code size
867
868 @objectmodel.dont_inline
869 def _obj_getdict(self, space):
870 terminator = self._get_mapdict_map().terminator
871 assert isinstance(terminator, DictTerminator) or isinstance(terminator, DevolvedDictTerminator)
872 w_dict = self._get_mapdict_map().read(self, "dict", SPECIAL)
873 if w_dict is not None:
874 assert isinstance(w_dict, W_DictMultiObject)
875 return w_dict
876
877 strategy = space.fromcache(MapDictStrategy)
878 storage = strategy.erase(self)
879 w_dict = W_DictObject(space, strategy, storage)
880 flag = self._get_mapdict_map().write(self, "dict", SPECIAL, w_dict)
881 assert flag
882 return w_dict
883
884 @objectmodel.dont_inline
885 def _obj_setdict(self, space, w_dict):
886 from pypy.interpreter.error import oefmt
887 terminator = self._get_mapdict_map().terminator
888 assert isinstance(terminator, DictTerminator) or isinstance(terminator, DevolvedDictTerminator)
889 if not space.isinstance_w(w_dict, space.w_dict):
890 raise oefmt(space.w_TypeError, "setting dictionary to a non-dict")
891 assert isinstance(w_dict, W_DictMultiObject)
892 w_olddict = self.getdict(space)
893 assert isinstance(w_olddict, W_DictMultiObject)
894 # The old dict has got 'self' as dstorage, but we are about to
895 # change self's ("dict", SPECIAL) attribute to point to the
896 # new dict. If the old dict was using the MapDictStrategy, we
897 # have to force it now: otherwise it would remain an empty
898 # shell that continues to delegate to 'self'.
899 if type(w_olddict.get_strategy()) is MapDictStrategy:
900 w_olddict.get_strategy().switch_to_object_strategy(w_olddict)
901 flag = self._get_mapdict_map().write(self, "dict", SPECIAL, w_dict)
902 assert flag
903
904 class MapdictStorageMixin(object):
905 def _get_mapdict_map(self):
906 return jit.promote(self.map)
907 def _set_mapdict_map(self, map):
908 self.map = map
909
910 def _mapdict_init_empty(self, map):
911 self._set_mapdict_map(map)
912 self.storage = None
913
914 def _mapdict_read_storage(self, storageindex):
915 assert storageindex >= 0
916 return self.storage[storageindex]
917
918 def _mapdict_write_storage(self, storageindex, value):
919 self.storage[storageindex] = value
920
921 def _mapdict_storage_length(self):
922 """ return the size of the storage. """
923 # we don't overallocate since a while any more
924 return self.map.storage_needed()
925
926 def _mapdict_pop_attribute(self, map):
927 current_map = self.map
928 assert isinstance(current_map, PlainAttribute)
929 assert current_map.back is map
930 if isinstance(current_map, UnboxedPlainAttribute) and not current_map.firstunwrapped:
931 unboxed_list = unerase_unboxed(self._mapdict_read_storage(current_map.storageindex))
932 assert len(unboxed_list) == current_map.listindex + 1
933 unboxed_list = unboxed_list[:current_map.listindex]
934 self._mapdict_write_storage(current_map.storageindex, erase_unboxed(unboxed_list))
935 else:
936 storage_needed = map.storage_needed()
937 assert storage_needed == len(self.storage) - 1
938 self.storage = self.storage[:storage_needed]
939 self._set_mapdict_map(map)
940
941 @jit.look_inside_iff(lambda self, map, value: jit.isconstant(map))
942 def _set_mapdict_increase_storage1(self, map, value):
943 """ increase storage size by 1, adding value """
944 current_map = self._get_mapdict_map()
945 len_storage = current_map.storage_needed()
946 if not len_storage:
947 assert map.storage_needed() == 1
948 new_storage = [value]
949 else:
950 new_storage = [erase_item(None)] * map.storage_needed()
951 old_storage = self.storage
952 assert len(old_storage) == len_storage
953 assert map.storage_needed() == len_storage + 1
954 for i in range(len_storage):
955 new_storage[i] = old_storage[i]
956 new_storage[len_storage] = value
957 new_storage = debug.make_sure_not_resized(new_storage)
958 self._set_mapdict_map(map)
959 self.storage = new_storage
960
961 def _set_mapdict_storage_and_map(self, storage, map):
962 """ store a new complete storage list, and also a new map """
963 self.storage = storage
964 self._set_mapdict_map(map)
965
966 class ObjectWithoutDict(W_Root):
967 # only used for tests
968 objectmodel.import_from_mixin(MapdictStorageMixin)
969
970 objectmodel.import_from_mixin(BaseUserClassMapdict)
971 objectmodel.import_from_mixin(MapdictWeakrefSupport)
972
973 @objectmodel.not_rpython # make sure it doesn't get accidentally translated
974 def getclass(self, space):
975 return self._get_mapdict_map().terminator.w_cls
976
977
978 class Object(W_Root):
979 # used for tests, and to have a fake object that can be used to back
980 # instance dictionaries. also for the result of delete, copy, etc
981 objectmodel.import_from_mixin(MapdictStorageMixin)
982
983 _share_methods(BaseUserClassMapdict, Object)
984 _share_methods(MapdictWeakrefSupport, Object)
985 _share_methods(MapdictDictSupport, Object)
986
987 assert Object.getclass.im_func is BaseUserClassMapdict.getclass.im_func
988
989
990 SUBCLASSES_NUM_FIELDS = 5
991
992 def _make_storage_mixin_size_n(n=SUBCLASSES_NUM_FIELDS):
993 from rpython.rlib import unroll
994 rangen = unroll.unrolling_iterable(range(n))
995 nmin1 = n - 1
996 rangenmin1 = unroll.unrolling_iterable(range(nmin1))
997 valnmin1 = "_value%s" % nmin1
998 class subcls(object):
999 def _get_mapdict_map(self):
1000 return jit.promote(self.map)
1001 def _set_mapdict_map(self, map):
1002 self.map = map
1003 def _mapdict_init_empty(self, map):
1004 self.map = map
1005 for i in rangen:
1006 setattr(self, "_value%s" % i, erase_item(None))
1007
1008 def _has_storage_list(self):
1009 return self.map.storage_needed() > n
1010
1011 def _mapdict_get_storage_list(self):
1012 erased = getattr(self, valnmin1)
1013 return unerase_list(erased)
1014
1015 def _mapdict_read_storage(self, storageindex):
1016 assert storageindex >= 0
1017 if storageindex < nmin1:
1018 for i in rangenmin1:
1019 if storageindex == i:
1020 return getattr(self, "_value%s" % i)
1021 if self._has_storage_list():
1022 return self._mapdict_get_storage_list()[storageindex - nmin1]
1023 erased = getattr(self, valnmin1)
1024 return erased
1025
1026 def _mapdict_write_storage(self, storageindex, value):
1027 assert storageindex >= 0
1028 if storageindex < nmin1:
1029 for i in rangenmin1:
1030 if storageindex == i:
1031 setattr(self, "_value%s" % i, value)
1032 return
1033 if self._has_storage_list():
1034 self._mapdict_get_storage_list()[storageindex - nmin1] = value
1035 else:
1036 setattr(self, valnmin1, value)
1037
1038 def _mapdict_storage_length(self):
1039 if self._has_storage_list():
1040 return self.map.storage_needed()
1041 return n
1042
1043 def _set_mapdict_storage_and_map(self, storage, map):
1044 self._set_mapdict_map(map)
1045 len_storage = len(storage) if storage is not None else 0
1046 for i in rangenmin1:
1047 if i < len_storage:
1048 erased = storage[i]
1049 else:
1050 erased = erase_item(None)
1051 setattr(self, "_value%s" % i, erased)
1052 has_storage_list = self._has_storage_list()
1053 if len_storage < n:
1054 assert not has_storage_list
1055 erased = erase_item(None)
1056 elif len_storage == n:
1057 assert not has_storage_list
1058 erased = storage[nmin1]
1059 elif not has_storage_list:
1060 # storage is longer than self.map.storage_needed() only due to
1061 # overallocation
1062 erased = storage[nmin1]
1063 # in theory, we should be ultra-paranoid and check all entries,
1064 # but checking just one should catch most problems anyway:
1065 assert unerase_item(storage[n]) is None
1066 else:
1067 storage_list = storage[nmin1:]
1068 erased = erase_list(storage_list)
1069 setattr(self, "_value%s" % nmin1, erased)
1070
1071 def _mapdict_pop_attribute(self, map):
1072 current_map = self.map
1073 assert isinstance(current_map, PlainAttribute)
1074 assert current_map.back is map
1075 if isinstance(current_map, UnboxedPlainAttribute) and not current_map.firstunwrapped:
1076 unboxed_list = unerase_unboxed(self._mapdict_read_storage(current_map.storageindex))
1077 assert len(unboxed_list) == current_map.listindex + 1
1078 unboxed_list = unboxed_list[:current_map.listindex]
1079 self._mapdict_write_storage(current_map.storageindex, erase_unboxed(unboxed_list))
1080 else:
1081 storage_needed = map.storage_needed()
1082 if storage_needed < n:
1083 for i in rangen:
1084 if i == storage_needed:
1085 erased = erase_item(None)
1086 setattr(self, "_value%s" % i, erased)
1087 break
1088 elif storage_needed == n:
1089 storage_list = self._mapdict_get_storage_list()
1090 setattr(self, "_value%s" % nmin1, storage_list[0])
1091 else:
1092 assert storage_needed > n
1093 storage_list = self._mapdict_get_storage_list()
1094 setattr(self, "_value%s" % nmin1, erase_list(storage_list[:-1]))
1095 self._set_mapdict_map(map)
1096
1097 @jit.look_inside_iff(lambda self, map, value: jit.isconstant(map))
1098 def _set_mapdict_increase_storage1(self, map, value):
1099 storage_needed = map.storage_needed()
1100 prev_storage_size = self.map.storage_needed()
1101 if prev_storage_size == n:
1102 erased = getattr(self, "_value%s" % nmin1)
1103 new_storage = [erased, value]
1104 else:
1105 new_storage = [erase_item(None)] * (storage_needed - nmin1)
1106 curr_storage = self._mapdict_get_storage_list()
1107 for i in range(prev_storage_size - nmin1):
1108 new_storage[i] = curr_storage[i]
1109 new_storage[storage_needed - n] = value
1110 self._set_mapdict_map(map)
1111 erased = erase_list(new_storage)
1112 setattr(self, "_value%s" % nmin1, erased)
1113
1114 subcls.__name__ = "Size%s" % n
1115 return subcls
1116
1117 # ____________________________________________________________
1118 # dict implementation
1119
1120 def get_terminator_for_dicts(space):
1121 return DictTerminator(space, None)
1122
1123 class MapDictStrategy(DictStrategy):
1124
1125 erase, unerase = rerased.new_erasing_pair("map")
1126 erase = staticmethod(erase)
1127 unerase = staticmethod(unerase)
1128
1129 def __init__(self, space):
1130 self.space = space
1131
1132 def get_empty_storage(self):
1133 # mainly used for tests
1134 w_result = Object()
1135 terminator = self.space.fromcache(get_terminator_for_dicts)
1136 w_result._mapdict_init_empty(terminator)
1137 return self.erase(w_result)
1138
1139 def switch_to_object_strategy(self, w_dict):
1140 w_obj = self.unerase(w_dict.dstorage)
1141 strategy = self.space.fromcache(ObjectDictStrategy)
1142 dict_w = strategy.unerase(strategy.get_empty_storage())
1143 w_dict.set_strategy(strategy)
1144 w_dict.dstorage = strategy.erase(dict_w)
1145 assert w_obj.getdict(self.space) is w_dict or w_obj._get_mapdict_map().terminator.w_cls is None
1146 materialize_r_dict(self.space, w_obj, dict_w)
1147
1148 def switch_to_text_strategy(self, w_dict):
1149 w_obj = self.unerase(w_dict.dstorage)
1150 strategy = self.space.fromcache(UnicodeDictStrategy)
1151 str_dict = strategy.unerase(strategy.get_empty_storage())
1152 w_dict.set_strategy(strategy)
1153 w_dict.dstorage = strategy.erase(str_dict)
1154 assert w_obj.getdict(self.space) is w_dict or w_obj._get_mapdict_map().terminator.w_cls is None
1155 materialize_str_dict(self.space, w_obj, str_dict)
1156
1157 def getitem(self, w_dict, w_key):
1158 space = self.space
1159 w_lookup_type = space.type(w_key)
1160 if space.is_w(w_lookup_type, space.w_text):
1161 return self.getitem_str(w_dict, space.text_w(w_key))
1162 elif _never_equal_to_string(space, w_lookup_type):
1163 return None
1164 else:
1165 self.switch_to_object_strategy(w_dict)
1166 return w_dict.getitem(w_key)
1167
1168 def getitem_str(self, w_dict, key):
1169 w_obj = self.unerase(w_dict.dstorage)
1170 return w_obj.getdictvalue(self.space, key)
1171
1172 def setitem_str(self, w_dict, key, w_value):
1173 w_obj = self.unerase(w_dict.dstorage)
1174 flag = w_obj.setdictvalue(self.space, key, w_value)
1175 assert flag
1176
1177 def setitem(self, w_dict, w_key, w_value):
1178 space = self.space
1179 if space.is_w(space.type(w_key), space.w_text):
1180 self.setitem_str(w_dict, self.space.text_w(w_key), w_value)
1181 else:
1182 self.switch_to_object_strategy(w_dict)
1183 w_dict.setitem(w_key, w_value)
1184
1185 def setdefault(self, w_dict, w_key, w_default):
1186 space = self.space
1187 if space.is_w(space.type(w_key), space.w_text):
1188 key = space.text_w(w_key)
1189 w_result = self.getitem_str(w_dict, key)
1190 if w_result is not None:
1191 return w_result
1192 self.setitem_str(w_dict, key, w_default)
1193 return w_default
1194 else:
1195 self.switch_to_object_strategy(w_dict)
1196 return w_dict.setdefault(w_key, w_default)
1197
1198 def delitem(self, w_dict, w_key):
1199 space = self.space
1200 w_key_type = space.type(w_key)
1201 w_obj = self.unerase(w_dict.dstorage)
1202 if space.is_w(w_key_type, space.w_text):
1203 key = self.space.text_w(w_key)
1204 flag = w_obj.deldictvalue(space, key)
1205 if not flag:
1206 raise KeyError
1207 elif _never_equal_to_string(space, w_key_type):
1208 raise KeyError
1209 else:
1210 self.switch_to_object_strategy(w_dict)
1211 w_dict.delitem(w_key)
1212
1213 def length(self, w_dict):
1214 res = 0
1215 curr = self.unerase(w_dict.dstorage)._get_mapdict_map().search(DICT)
1216 while curr is not None:
1217 curr = curr.back
1218 curr = curr.search(DICT)
1219 res += 1
1220 return res
1221
1222 def clear(self, w_dict):
1223 w_obj = self.unerase(w_dict.dstorage)
1224 new_obj = w_obj._get_mapdict_map().remove_dict_entries(w_obj)
1225 w_obj._set_mapdict_storage_and_map(new_obj.storage, new_obj.map)
1226
1227 def popitem(self, w_dict):
1228 curr = self.unerase(w_dict.dstorage)._get_mapdict_map().search(DICT)
1229 if curr is None:
1230 raise KeyError
1231 key = curr.name
1232 w_value = self.getitem_str(w_dict, key)
1233 w_key = self.space.newtext(key)
1234 self.delitem(w_dict, w_key)
1235 return (w_key, w_value)
1236
1237 def copy(self, w_dict):
1238 w_obj = self.unerase(w_dict.dstorage)
1239 curr_map = w_obj._get_mapdict_map()
1240 attrs = []
1241 while True:
1242 curr_map = curr_map.search(DICT)
1243 if curr_map is None:
1244 break
1245 attrs.append(curr_map)
1246 curr_map = curr_map.back
1247
1248 strategy = self.space.fromcache(UnicodeDictStrategy)
1249 str_dict = strategy.unerase(strategy.get_empty_storage())
1250 while attrs:
1251 map = attrs.pop()
1252 str_dict[self.space.newtext(map.name)] = map._prim_direct_read(w_obj)
1253 return W_DictObject(self.space, strategy, strategy.erase(str_dict))
1254
1255 def eq(self, w_dict, space, w_other):
1256 other_strategy = w_other.get_strategy()
1257 if other_strategy is self:
1258 w_self_obj = self.unerase(w_dict.dstorage)
1259 w_other_obj = self.unerase(w_other.dstorage)
1260 selfmap = w_self_obj._get_mapdict_map()
1261 othermap = w_other_obj._get_mapdict_map()
1262 if selfmap is othermap:
1263 w_res = _dict_eq_same_map(selfmap, w_self_obj, w_other_obj)
1264 if w_res is not None:
1265 return w_res
1266 return DictStrategy.eq(self, w_dict, space, w_other)
1267
1268
1269 # XXX could implement a more efficient w_keys based on space.newlist_bytes
1270
1271 def iterkeys(self, w_dict):
1272 return MapDictIteratorKeys(self.space, self, w_dict)
1273 def itervalues(self, w_dict):
1274 return MapDictIteratorValues(self.space, self, w_dict)
1275 def iteritems(self, w_dict):
1276 return MapDictIteratorItems(self.space, self, w_dict)
1277
1278 def iterreversed(self, w_dict):
1279 return MapDictKeyIteratorReversed(self.space, self, w_dict)
1280
1281
1282 def _dict_eq_same_map(map, w_self_obj, w_other_obj):
1283 # can return None to mean "the equality mutated one of the objects"
1284 space = map.space
1285 orig_map = map
1286 curr_map = map
1287 while isinstance(curr_map, PlainAttribute):
1288 if curr_map.attrkind == DICT:
1289 w_attr1 = curr_map._direct_read(w_self_obj)
1290 w_attr2 = curr_map._direct_read(w_other_obj)
1291 if not space.eq_w(w_attr1, w_attr2):
1292 return space.w_False
1293 if (w_self_obj._get_mapdict_map() is not orig_map or
1294 w_other_obj._get_mapdict_map() is not orig_map):
1295 return None
1296 curr_map = curr_map.back
1297 return space.w_True
1298
1299 def make_instance_dict(space):
1300 w_fake_object = Object()
1301 terminator = space.fromcache(get_terminator_for_dicts)
1302 w_fake_object._mapdict_init_empty(terminator)
1303 return w_fake_object.getdict(space)
1304
1305 def materialize_r_dict(space, obj, dict_w):
1306 map = obj._get_mapdict_map()
1307 new_obj = map.materialize_r_dict(space, obj, dict_w)
1308 obj._set_mapdict_storage_and_map(new_obj.storage, new_obj.map)
1309
1310 def materialize_str_dict(space, obj, dict_w):
1311 map = obj._get_mapdict_map()
1312 new_obj = map.materialize_str_dict(space, obj, dict_w)
1313 obj._set_mapdict_storage_and_map(new_obj.storage, new_obj.map)
1314
1315
1316 class IteratorMixin(object):
1317
1318 def _init(self, strategy, w_dict):
1319 w_obj = strategy.unerase(w_dict.dstorage)
1320 self.w_obj = w_obj
1321 curr_map = w_obj._get_mapdict_map()
1322 # We enumerate non-lazily the attributes, and store them in the
1323 # 'attrs' list. We then walk that list in opposite order. This
1324 # gives an ordering that is more natural (roughly corresponding
1325 # to oldest-first) than the one we get in the direct algorithm
1326 # (from leaves to root, looks like backward order). See issue
1327 # #2426: it should improve the performance of code like
1328 # copy.copy().
1329 attrs = []
1330 while True:
1331 curr_map = curr_map.search(DICT)
1332 if curr_map is None:
1333 break
1334 attrs.append(curr_map.name)
1335 curr_map = curr_map.back
1336 self.attrs = attrs
1337
1338
1339 class MapDictIteratorKeys(BaseKeyIterator):
1340 objectmodel.import_from_mixin(IteratorMixin)
1341
1342 def __init__(self, space, strategy, w_dict):
1343 BaseKeyIterator.__init__(self, space, strategy, w_dict)
1344 self._init(strategy, w_dict)
1345
1346 def next_key_entry(self):
1347 assert isinstance(self.w_dict.get_strategy(), MapDictStrategy)
1348 attrs = self.attrs
1349 if len(attrs) > 0:
1350 attr = attrs.pop()
1351 w_attr = self.space.newtext(attr)
1352 return w_attr
1353 return None
1354
1355
1356 class MapDictIteratorValues(BaseValueIterator):
1357 objectmodel.import_from_mixin(IteratorMixin)
1358
1359 def __init__(self, space, strategy, w_dict):
1360 BaseValueIterator.__init__(self, space, strategy, w_dict)
1361 self._init(strategy, w_dict)
1362
1363 def next_value_entry(self):
1364 assert isinstance(self.w_dict.get_strategy(), MapDictStrategy)
1365 attrs = self.attrs
1366 if len(attrs) > 0:
1367 attr = attrs.pop()
1368 return self.w_obj.getdictvalue(self.space, attr)
1369 return None
1370
1371
1372 class MapDictIteratorItems(BaseItemIterator):
1373 objectmodel.import_from_mixin(IteratorMixin)
1374
1375 def __init__(self, space, strategy, w_dict):
1376 BaseItemIterator.__init__(self, space, strategy, w_dict)
1377 self._init(strategy, w_dict)
1378
1379 def next_item_entry(self):
1380 assert isinstance(self.w_dict.get_strategy(), MapDictStrategy)
1381 attrs = self.attrs
1382 if len(attrs) > 0:
1383 attr = attrs.pop()
1384 w_attr = self.space.newtext(attr)
1385 return w_attr, self.w_obj.getdictvalue(self.space, attr)
1386 return None, None
1387
1388 class MapDictKeyIteratorReversed(BaseKeyIterator):
1389 def __init__(self, space, strategy, w_dict):
1390 BaseKeyIterator.__init__(self, space, strategy, w_dict)
1391 w_obj = strategy.unerase(w_dict.dstorage)
1392 self.w_obj = w_obj
1393 curr_map = w_obj._get_mapdict_map()
1394 attrs = []
1395 while True:
1396 curr_map = curr_map.search(DICT)
1397 if curr_map is None:
1398 break
1399 attrs.append(curr_map.name)
1400 curr_map = curr_map.back
1401 attrs.reverse()
1402 self.attrs = attrs
1403
1404 def next_key_entry(self):
1405 assert isinstance(self.w_dict.get_strategy(), MapDictStrategy)
1406 attrs = self.attrs
1407 if len(attrs) > 0:
1408 attr = attrs.pop()
1409 w_attr = self.space.newtext(attr)
1410 return w_attr
1411 return None
1412
1413 # ____________________________________________________________
1414 # Magic caching
1415
1416 class CacheEntry(object):
1417 version_tag = None
1418 w_method = None # for callmethod
1419 success_counter = 0
1420 failure_counter = 0
1421 valid_for_store = True
1422 attr_to_add = None
1423
1424 @objectmodel.specialize.arg(2)
1425 def is_valid_for_obj(self, w_obj, store=False):
1426 map = w_obj._get_mapdict_map()
1427 return self.is_valid_for_map(map, store)
1428
1429 @objectmodel.specialize.arg(2)
1430 @objectmodel.always_inline
1431 def is_valid_for_map(self, map, store=False):
1432 if store and not self.valid_for_store:
1433 return False
1434 return self._is_valid_for_map(map)
1435
1436 @objectmodel.always_inline
1437 def _is_valid_for_map(self, map):
1438 # note that 'map' can be None here
1439 mymap = self.map_wref()
1440 if mymap is not None and mymap is map:
1441 version_tag = map.terminator.w_cls.version_tag()
1442 if version_tag is self.version_tag:
1443 # everything matches, it's incredibly fast
1444 if map.space.config.objspace.std.withmethodcachecounter:
1445 self.success_counter += 1
1446 return True
1447 return False
1448
1449 _invalid_cache_entry_map = objectmodel.instantiate(AbstractAttribute)
1450 _invalid_cache_entry_map.terminator = None
1451 INVALID_CACHE_ENTRY = CacheEntry()
1452 INVALID_CACHE_ENTRY.map_wref = weakref.ref(_invalid_cache_entry_map)
1453 # different from any real map ^^^
1454 INVALID_CACHE_ENTRY.valid_for_store = False
1455
1456 def init_mapdict_cache(pycode):
1457 num_entries = len(pycode.co_names_w)
1458 pycode._mapdict_caches = [INVALID_CACHE_ENTRY] * num_entries
1459
1460 @jit.dont_look_inside
1461 def _fill_cache(pycode, nameindex, map, version_tag, attr, w_method=None, valid_for_store=False, attr_to_add=None):
1462 if not pycode.space._side_effects_ok():
1463 return
1464 entry = pycode._mapdict_caches[nameindex]
1465 if entry is INVALID_CACHE_ENTRY:
1466 entry = CacheEntry()
1467 pycode._mapdict_caches[nameindex] = entry
1468 entry.map_wref = weakref.ref(map)
1469 if attr:
1470 entry.attr_wref = weakref.ref(attr)
1471 else:
1472 entry.attr_wref = dead_ref
1473 entry.version_tag = version_tag
1474 entry.w_method = w_method
1475 entry.valid_for_store = valid_for_store
1476 if pycode.space.config.objspace.std.withmethodcachecounter:
1477 entry.failure_counter += 1
1478
1479 @objectmodel.always_inline
1480 def LOAD_ATTR_caching(pycode, w_obj, nameindex):
1481 # this whole mess is to make the interpreter quite a bit faster; it's not
1482 # used if we_are_jitted().
1483 entry = pycode._mapdict_caches[nameindex]
1484 map = w_obj._get_mapdict_map()
1485 if entry.is_valid_for_map(map) and entry.w_method is None:
1486 # everything matches, it's incredibly fast
1487 attr = entry.attr_wref()
1488 if attr is not None:
1489 return attr._direct_read(w_obj)
1490 return LOAD_ATTR_slowpath(pycode, w_obj, nameindex, map)
1491
1492 @objectmodel.dont_inline
1493 def LOAD_ATTR_slowpath(pycode, w_obj, nameindex, map):
1494 space = pycode.space
1495 w_name = pycode.co_names_w[nameindex]
1496 if map is not None:
1497 w_type = map.terminator.w_cls
1498 w_descr = w_type.getattribute_if_not_from_object()
1499 if w_descr is not None:
1500 return space._handle_getattribute(w_descr, w_obj, w_name)
1501 version_tag = w_type.version_tag()
1502 if version_tag is not None:
1503 name = space.text_w(w_name)
1504 # We need to care for obscure cases in which the w_descr is
1505 # a MutableCell, which may change without changing the version_tag
1506 _, w_descr = w_type._pure_lookup_where_with_method_cache(
1507 name, version_tag)
1508 #
1509 attrname, attrkind = ("", INVALID)
1510 if w_descr is None:
1511 attrname, attrkind = (name, DICT) # common case: no such attr in the class
1512 elif isinstance(w_descr, MutableCell):
1513 pass # we have a MutableCell in the class: give up
1514 elif space.is_data_descr(w_descr):
1515 # we have a data descriptor, which means the dictionary value
1516 # (if any) has no relevance.
1517 from pypy.interpreter.typedef import Member
1518 if isinstance(w_descr, Member) and space.issubtype_w(w_type, w_descr.w_cls):
1519 # it is a slot that belongs to this type -- easy case
1520 attrname, attrkind = ("slot", SLOTS_STARTING_FROM + w_descr.index)
1521 elif not space.type(w_descr).is_heaptype():
1522 # There is a non-data descriptor in the class. This would mean
1523 # we use the dict entry, however, the class of w_descr could be
1524 # changed to add a __get__/__set__ without the cache noticing,
1525 # so we can only use the cache if w_descr is an instance of an
1526 # immutable type. see
1527 # test_load_attr_bug_class_name_turns_into_descriptor
1528 attrname = name
1529 attrkind = DICT
1530 #
1531 if attrkind != INVALID:
1532 attr = map.find_map_attr(attrname, attrkind)
1533 if attr is not None:
1534 # Note that if map.terminator is a DevolvedDictTerminator
1535 # or the class provides its own dict, not using mapdict, then:
1536 # map.find_map_attr will always return None if attrkind==DICT.
1537 _fill_cache(pycode, nameindex, map, version_tag, attr,
1538 valid_for_store=w_type.setattr_if_not_from_object() is None)
1539 return attr._direct_read(w_obj)
1540 if space.config.objspace.std.withmethodcachecounter:
1541 INVALID_CACHE_ENTRY.failure_counter += 1
1542 return space.getattr(w_obj, w_name)
1543
1544 def LOAD_METHOD_mapdict(f, nameindex, w_obj):
1545 pycode = f.getcode()
1546 entry = pycode._mapdict_caches[nameindex]
1547 if entry.is_valid_for_obj(w_obj):
1548 w_method = entry.w_method
1549 if w_method is not None:
1550 f.pushvalue(w_method)
1551 f.pushvalue(w_obj)
1552 return True
1553 return False
1554
1555 def LOAD_METHOD_mapdict_fill_cache_method(space, pycode, name, nameindex,
1556 w_obj, w_type, w_method):
1557 # if the layout has a dict itself, then mapdict is not used for normal
1558 # attributes. Then the cache won't be able to spot changes to the dict.
1559 # Thus we don't cache. see test_bug_builtin_types_callmethod
1560 if w_type.layout.typedef.hasdict:
1561 return
1562
1563 if w_method is None or isinstance(w_method, MutableCell):
1564 # don't cache the MutableCell XXX could be fixed
1565 return
1566 version_tag = w_type.version_tag()
1567 assert version_tag is not None
1568 map = w_obj._get_mapdict_map()
1569 if map is None or isinstance(map.terminator, DevolvedDictTerminator):
1570 return
1571 _fill_cache(pycode, nameindex, map, version_tag, None, w_method)
1572
1573 @objectmodel.always_inline
1574 def STORE_ATTR_caching(pycode, w_obj, nameindex, w_value):
1575 entry = pycode._mapdict_caches[nameindex]
1576 map = w_obj._get_mapdict_map()
1577 entry_valid = entry.is_valid_for_map(map, store=True) and entry.w_method is None
1578 if entry_valid:
1579 attr = entry.attr_wref()
1580 if attr is not None:
1581 if not attr.ever_mutated:
1582 attr.ever_mutated = True
1583 attr._direct_write(w_obj, w_value)
1584 return
1585 return STORE_ATTR_slowpath(pycode, w_obj, nameindex, map, w_value, entry)
1586
1587 def STORE_ATTR_slowpath(pycode, w_obj, nameindex, map, w_value, entry):
1588 space = pycode.space
1589
1590 w_name = pycode.co_names_w[nameindex]
1591 if map is not None:
1592 w_type = map.terminator.w_cls
1593 version_tag = w_type.version_tag()
1594 # there is still a (not inlined) fast path for stores that add a new
1595 # attribute
1596 if entry.valid_for_store and version_tag is entry.version_tag:
1597 entry_map = entry.map_wref()
1598 attr_to_add = entry.attr_wref()
1599 if (entry_map is not None and
1600 isinstance(entry_map, PlainAttribute) and
1601 attr_to_add is entry_map
1602 and entry_map.back is map):
1603 if isinstance(attr_to_add, UnboxedPlainAttribute):
1604 typsafe = type(w_value) is attr_to_add.typ
1605 else:
1606 typsafe = True
1607 if typsafe:
1608 if space.config.objspace.std.withmethodcachecounter:
1609 entry.success_counter += 1
1610 attr_to_add._switch_map_and_write_increase_storage1(w_obj, w_value)
1611 return
1612 w_descr = w_type.setattr_if_not_from_object()
1613 if w_descr:
1614 return space.get_and_call_function(w_descr, w_obj, w_name, w_value)
1615 return
1616 if version_tag is not None:
1617 name = space.text_w(w_name)
1618 _, w_descr = w_type._pure_lookup_where_with_method_cache(
1619 name, version_tag)
1620 attrname, attrkind = ("", INVALID)
1621 if w_descr is None:
1622 attrname, attrkind = (name, DICT) # common case: no such attr in the class
1623 elif isinstance(w_descr, MutableCell):
1624 pass # we have a MutableCell in the class: give up
1625 elif space.is_data_descr(w_descr):
1626 from pypy.interpreter.typedef import Member
1627 if isinstance(w_descr, Member) and space.issubtype_w(w_type, w_descr.w_cls):
1628 # it is a slot that belongs to this type -- easy case
1629 attrname, attrkind = ("slot", SLOTS_STARTING_FROM + w_descr.index)
1630 if attrkind != INVALID:
1631 attr = map.find_map_attr(attrname, attrkind)
1632 if attr is not None:
1633 if w_type.getattribute_if_not_from_object() is None:
1634 _fill_cache(pycode, nameindex, map, version_tag, attr,
1635 valid_for_store=True)
1636 if not attr.ever_mutated:
1637 attr.ever_mutated = True
1638 attr._direct_write(w_obj, w_value)
1639 return
1640 if attr is None and attrkind == DICT and isinstance(map.terminator, DictTerminator):
1641 # do the write
1642 map.terminator._write_terminator(w_obj, name, attrkind, w_value)
1643 mapnew = w_obj._get_mapdict_map()
1644 # the next condition checks whether any attribute reordering happened
1645 if isinstance(mapnew, PlainAttribute) and mapnew.back is map:
1646 assert mapnew.name == name and mapnew.attrkind == attrkind
1647 if w_type.getattribute_if_not_from_object() is None:
1648 _fill_cache(pycode, nameindex, mapnew, version_tag, mapnew,
1649 valid_for_store=True)
1650 return
1651
1652 space.setattr(w_obj, w_name, w_value)