Debian Codegraph @

pypy/objspace/std/celldict.py

raw symbols SCIP
1 """ A very simple cell dict implementation using a version tag. The dictionary
2 maps keys to objects. If a specific key is changed a lot, a level of
3 indirection is introduced to make the version tag change less often.
4 """
5 import weakref
6
7 from rpython.rlib import jit, rerased, objectmodel
8
9 from pypy.interpreter.baseobjspace import W_Root
10 from pypy.interpreter.error import OperationError
11 from pypy.objspace.std.dictmultiobject import (
12 DictStrategy, ObjectDictStrategy, _never_equal_to_string,
13 create_iterator_classes, UnicodeDictStrategy,
14 W_ModuleDictObject,
15 W_DictObject)
16 from pypy.objspace.std.typeobject import (
17 MutableCell, IntMutableCell, ObjectMutableCell, write_cell, unwrap_cell)
18
19
20 class VersionTag(object):
21 pass
22
23
24 def _wrapkey(space, key):
25 return space.newtext(key)
26
27
28 class ModuleDictStrategy(DictStrategy):
29
30 erase, unerase = rerased.new_erasing_pair("modulecell")
31 erase = staticmethod(erase)
32 unerase = staticmethod(unerase)
33
34 _immutable_fields_ = ["version?"]
35
36 def __init__(self, space):
37 self.space = space
38 self.version = VersionTag()
39 self.caches = None
40
41 def get_empty_storage(self):
42 return self.erase({})
43
44 def mutated(self):
45 self.version = VersionTag()
46
47 def getdictvalue_no_unwrapping(self, w_dict, key):
48 # NB: it's important to promote self here, so that self.version is a
49 # no-op due to the quasi-immutable field
50 self = jit.promote(self)
51 return self._getdictvalue_no_unwrapping_pure(self.version, w_dict, key)
52
53 @jit.elidable_promote('0,1,2')
54 def _getdictvalue_no_unwrapping_pure(self, version, w_dict, key):
55 return self.unerase(w_dict.dstorage).get(key, None)
56
57 def try_unwrap_key(self, space, w_key):
58 if space.is_w(space.type(w_key), space.w_text):
59 try:
60 return space.text_w(w_key)
61 except OperationError as e:
62 if e.match(space, space.w_UnicodeEncodeError):
63 return None
64 raise
65 return None
66
67 def setitem(self, w_dict, w_key, w_value):
68 space = self.space
69 key = self.try_unwrap_key(space, w_key)
70 if key is not None:
71 self.setitem_str(w_dict, key, w_value)
72 else:
73 self.switch_to_object_strategy(w_dict)
74 w_dict.setitem(w_key, w_value)
75
76 def setitem_str(self, w_dict, key, w_value):
77 cell = self.getdictvalue_no_unwrapping(w_dict, key)
78 return self._setitem_str_cell_known(cell, w_dict, key, w_value)
79
80 def _setitem_str_cell_known(self, cell, w_dict, key, w_value):
81 w_value = write_cell(self.space, cell, w_value)
82 if w_value is None:
83 return
84 self.mutated()
85 self.unerase(w_dict.dstorage)[key] = w_value
86 if self.caches is None:
87 return
88 cache = self.caches.get(key, None)
89 if cache:
90 cache.cell = w_value
91
92 def setdefault(self, w_dict, w_key, w_default):
93 space = self.space
94 key = self.try_unwrap_key(space, w_key)
95 if key is not None:
96 cell = self.getdictvalue_no_unwrapping(w_dict, key)
97 w_result = unwrap_cell(self.space, cell)
98 if w_result is not None:
99 return w_result
100 self._setitem_str_cell_known(cell, w_dict, key, w_default)
101 return w_default
102 else:
103 self.switch_to_object_strategy(w_dict)
104 return w_dict.setdefault(w_key, w_default)
105
106 def delitem(self, w_dict, w_key):
107 space = self.space
108 w_key_type = space.type(w_key)
109 key = self.try_unwrap_key(space, w_key)
110 if key is not None:
111 dict_w = self.unerase(w_dict.dstorage)
112 try:
113 del dict_w[key]
114 except KeyError:
115 raise
116 else:
117 if self.caches:
118 cache = self.caches.get(key, None)
119 if cache:
120 cache.cell = None
121 self.mutated()
122 elif _never_equal_to_string(space, w_key_type):
123 raise KeyError
124 else:
125 self.switch_to_object_strategy(w_dict)
126 w_dict.delitem(w_key)
127
128 def length(self, w_dict):
129 return len(self.unerase(w_dict.dstorage))
130
131 def getitem(self, w_dict, w_key):
132 space = self.space
133 w_lookup_type = space.type(w_key)
134 key = self.try_unwrap_key(space, w_key)
135 if key is not None:
136 return self.getitem_str(w_dict, key)
137 elif _never_equal_to_string(space, w_lookup_type):
138 return None
139 else:
140 self.switch_to_object_strategy(w_dict)
141 return w_dict.getitem(w_key)
142
143 def getitem_str(self, w_dict, key):
144 cell = self.getdictvalue_no_unwrapping(w_dict, key)
145 return unwrap_cell(self.space, cell)
146
147 def w_keys(self, w_dict):
148 space = self.space
149 l = self.unerase(w_dict.dstorage).keys()
150 return space.newlist_text(l)
151
152 def values(self, w_dict):
153 iterator = self.unerase(w_dict.dstorage).itervalues
154 return [unwrap_cell(self.space, cell) for cell in iterator()]
155
156 def items(self, w_dict):
157 space = self.space
158 iterator = self.unerase(w_dict.dstorage).iteritems
159 return [space.newtuple2(_wrapkey(space, key), unwrap_cell(self.space, cell))
160 for key, cell in iterator()]
161
162 def clear(self, w_dict):
163 self.unerase(w_dict.dstorage).clear()
164 self.mutated()
165
166 def popitem(self, w_dict):
167 space = self.space
168 d = self.unerase(w_dict.dstorage)
169 key, cell = d.popitem()
170 self.mutated()
171 return _wrapkey(space, key), unwrap_cell(self.space, cell)
172
173 def switch_to_object_strategy(self, w_dict):
174 space = self.space
175 d = self.unerase(w_dict.dstorage)
176 strategy = space.fromcache(ObjectDictStrategy)
177 d_new = strategy.unerase(strategy.get_empty_storage())
178 for key, cell in d.iteritems():
179 d_new[_wrapkey(space, key)] = unwrap_cell(self.space, cell)
180 if self.caches is not None:
181 for cache in self.caches.itervalues():
182 cache.cell = None
183 cache.valid = False
184 self.caches = None
185 w_dict.set_strategy(strategy)
186 w_dict.dstorage = strategy.erase(d_new)
187
188 def getiterkeys(self, w_dict):
189 return self.unerase(w_dict.dstorage).iterkeys()
190
191 def getitervalues(self, w_dict):
192 return self.unerase(w_dict.dstorage).itervalues()
193
194 def getiteritems_with_hash(self, w_dict):
195 return objectmodel.iteritems_with_hash(self.unerase(w_dict.dstorage))
196
197 def getiterreversed(self, w_dict):
198 return objectmodel.reversed_dict(self.unerase(w_dict.dstorage))
199
200 wrapkey = _wrapkey
201
202 def wrapvalue(space, value):
203 return unwrap_cell(space, value)
204
205 def copy(self, w_dict):
206 strategy = self.space.fromcache(UnicodeDictStrategy)
207 str_dict = strategy.unerase(strategy.get_empty_storage())
208
209 d = self.unerase(w_dict.dstorage)
210 for key, cell in d.iteritems():
211 str_dict[self.space.newtext(key)] = unwrap_cell(self.space, cell)
212 return W_DictObject(strategy.space, strategy, strategy.erase(str_dict))
213
214 def get_global_cache(self, w_dict, key):
215 space = w_dict.space
216 if self.caches is None:
217 cache = None
218 self.caches = {}
219 else:
220 cache = self.caches.get(key, None)
221 if cache is None:
222 cell = self.getdictvalue_no_unwrapping(w_dict, key)
223 cache = GlobalCache(cell)
224 if (not space.config.objspace.honor__builtins__ and
225 cell is None and
226 w_dict is not space.builtin.w_dict):
227 w_builtin_dict = space.builtin.w_dict
228 assert isinstance(w_builtin_dict, W_ModuleDictObject)
229 builtin_strategy = w_builtin_dict.mstrategy
230 if isinstance(builtin_strategy, ModuleDictStrategy):
231 cell = builtin_strategy.getdictvalue_no_unwrapping(
232 w_builtin_dict, key)
233 # logic: if the global is not defined but the builtin is,
234 # cache it. otherwise don't cache the builtin ever
235 if cell is not None:
236 builtincache = builtin_strategy.get_global_cache(
237 w_builtin_dict, key)
238 cache.builtincache = builtincache
239 self.caches[key] = cache
240 return cache
241
242 def remove_cell(w_dict, space, name):
243 from pypy.objspace.std.dictmultiobject import W_DictMultiObject
244 if isinstance(w_dict, W_DictMultiObject):
245 strategy = w_dict.get_strategy()
246 if isinstance(strategy, ModuleDictStrategy):
247 w_value = strategy.getitem_str(w_dict, name)
248 dict_w = strategy.unerase(w_dict.dstorage)
249 strategy.mutated()
250 dict_w[name] = w_value # store without cell
251 # nothing to do, not a W_DictMultiObject or wrong strategy
252
253
254 create_iterator_classes(ModuleDictStrategy)
255
256
257
258 # ____________________________________________________________
259 # global caching
260
261 class GlobalCache(object):
262 def __init__(self, cell):
263 # works like this: self.cell is always the result of
264 # getdictvalue_no_unwrapping on the equivalent key.
265 # this means it is None if the key doesn't exist, a w_value if there is
266 # no cell, or a Cell
267
268 # if the module dict actually switches to a different strategy, then
269 # cell is set to None, and valid to False
270 self.cell = cell
271 self.valid = True
272 self.ref = weakref.ref(self)
273 self.builtincache = None
274
275 @objectmodel.always_inline
276 def getvalue(self, space):
277 return unwrap_cell(space, self.cell)
278
279 def LOAD_GLOBAL_cached(self, nameindex, next_instr):
280 # indirection for the benefit of looking like py2
281 w_value = _LOAD_GLOBAL_cached(self, nameindex, next_instr)
282 self.pushvalue(w_value)
283
284 @objectmodel.always_inline
285 def _LOAD_GLOBAL_cached(self, nameindex, next_instr):
286 pycode = self.pycode
287 if jit.we_are_jitted() or (
288 self.debugdata is not None and
289 self.debugdata.w_globals is not pycode.w_globals):
290 varname = self.getname_u(nameindex)
291 return _load_global_fallback(self, varname)
292 cache_wref = pycode._globals_caches[nameindex]
293 if cache_wref is not None:
294 cache = cache_wref()
295 if cache:
296 w_value = cache.getvalue(self.space)
297 if w_value is not None:
298 return w_value
299 if cache.valid:
300 # the cache is valid. this means it's not in the globals
301 # and we check the builtins next
302 builtincache = cache.builtincache
303 if builtincache is not None:
304 w_value = builtincache.getvalue(self.space)
305 if w_value is not None:
306 return w_value
307 varname = self.getname_u(nameindex)
308 w_value = self.get_builtin().getdictvalue(
309 self.space, varname)
310 if w_value is not None:
311 return w_value
312 else:
313 self._load_global_failed(self.space.newtext(varname))
314 # either no cache or an invalid cache
315 w_globals = pycode.w_globals
316 varname = self.getname_u(nameindex)
317 if isinstance(w_globals, W_ModuleDictObject):
318 cache = w_globals.get_global_cache(varname)
319 if cache is not None:
320 assert cache.valid and cache.ref is not None
321 pycode._globals_caches[nameindex] = cache.ref
322 return _load_global_fallback(self, varname)
323
324 @objectmodel.dont_inline
325 def _load_global_fallback(self, varname):
326 return self._load_global(varname)
327
328 def STORE_GLOBAL_cached(self, nameindex, next_instr):
329 w_newvalue = self.popvalue()
330 if jit.we_are_jitted() or self.getdebug() is not None:
331 varname = self.getname_u(nameindex)
332 self.space.setitem_str(self.get_w_globals(), varname, w_newvalue)
333 return
334 pycode = self.pycode
335 cache_wref = pycode._globals_caches[nameindex]
336 if cache_wref is not None:
337 cache = cache_wref()
338 if cache and cache.valid:
339 w_value = write_cell(self.space, cache.cell, w_newvalue)
340 if w_value is None:
341 return
342
343 varname = self.getname_u(nameindex)
344 w_globals = self.pycode.w_globals
345 self.space.setitem_str(w_globals, varname, w_newvalue)
346 if isinstance(w_globals, W_ModuleDictObject):
347 # the following can never be true, becaus W_ModuleDictObject can't be
348 # user-subclassed, but let's be safe
349 assert not w_globals.user_overridden_class
350 cache = w_globals.get_global_cache(varname)
351 if cache is not None:
352 assert cache.valid and cache.ref is not None
353 pycode._globals_caches[nameindex] = cache.ref
354