Debian Codegraph @

pypy/module/_weakref/interp__weakref.py

raw symbols SCIP
1 import py
2 from pypy.interpreter.baseobjspace import W_Root
3 from pypy.interpreter.error import oefmt
4 from pypy.interpreter.gateway import interp2app, ObjSpace
5 from pypy.interpreter.typedef import TypeDef, GetSetProperty
6 from pypy.interpreter.executioncontext import AsyncAction, report_error
7 from pypy.objspace.std.util import generic_alias_class_getitem
8 from rpython.rlib import jit, rgc
9 from rpython.rlib.rshrinklist import AbstractShrinkList
10 from rpython.rlib.objectmodel import specialize
11 from rpython.rlib.rweakref import dead_ref
12 import weakref
13
14
15 class WRefShrinkList(AbstractShrinkList):
16 def must_keep(self, wref):
17 return wref() is not None
18
19
20 class WeakrefLifeline(W_Root):
21 typedef = None
22
23 cached_weakref = None
24 cached_proxy = None
25 other_refs_weak = None
26 has_callbacks = False
27
28 def __init__(self, space):
29 self.space = space
30
31 def append_wref_to(self, w_ref):
32 if self.other_refs_weak is None:
33 self.other_refs_weak = WRefShrinkList()
34 self.other_refs_weak.append(weakref.ref(w_ref))
35
36 @specialize.arg(1)
37 def traverse(self, callback, arg=None):
38 if self.cached_weakref is not None:
39 arg = callback(self, self.cached_weakref, arg)
40 if self.cached_proxy is not None:
41 arg = callback(self, self.cached_proxy, arg)
42 if self.other_refs_weak is not None:
43 for ref_w_ref in self.other_refs_weak.items():
44 arg = callback(self, ref_w_ref, arg)
45 return arg
46
47 def _clear_wref(self, wref, _):
48 w_ref = wref()
49 if w_ref is not None:
50 w_ref.clear()
51
52 def clear_all_weakrefs(self):
53 """Clear all weakrefs. This is called when an app-level object has
54 a __del__, just before the app-level __del__ method is called.
55 """
56 self.traverse(WeakrefLifeline._clear_wref)
57 # Note that for no particular reason other than convenience,
58 # weakref callbacks are not invoked eagerly here. They are
59 # invoked by self.__del__() anyway.
60
61 @jit.dont_look_inside
62 def get_or_make_weakref(self, w_subtype, w_obj):
63 space = self.space
64 w_weakreftype = space.gettypeobject(W_Weakref.typedef)
65 #
66 if space.is_w(w_weakreftype, w_subtype):
67 if self.cached_weakref is not None:
68 w_cached = self.cached_weakref()
69 if w_cached is not None:
70 return w_cached
71 w_ref = W_Weakref(space, w_obj, None)
72 self.cached_weakref = weakref.ref(w_ref)
73 else:
74 # subclass: cannot cache
75 w_ref = space.allocate_instance(W_Weakref, w_subtype)
76 W_Weakref.__init__(w_ref, space, w_obj, None)
77 self.append_wref_to(w_ref)
78 return w_ref
79
80 @jit.dont_look_inside
81 def get_or_make_proxy(self, w_obj):
82 space = self.space
83 if self.cached_proxy is not None:
84 w_cached = self.cached_proxy()
85 if w_cached is not None:
86 return w_cached
87 if space.is_true(space.callable(w_obj)):
88 w_proxy = W_CallableProxy(space, w_obj, None)
89 else:
90 w_proxy = W_Proxy(space, w_obj, None)
91 self.cached_proxy = weakref.ref(w_proxy)
92 return w_proxy
93
94 def get_any_weakref(self, space):
95 if self.cached_weakref is not None:
96 w_ref = self.cached_weakref()
97 if w_ref is not None:
98 return w_ref
99 if self.other_refs_weak is not None:
100 w_weakreftype = space.gettypeobject(W_Weakref.typedef)
101 for wref in self.other_refs_weak.items():
102 w_ref = wref()
103 if (w_ref is not None and space.isinstance_w(w_ref, w_weakreftype)):
104 return w_ref
105 return space.w_None
106
107 def enable_callbacks(self):
108 if not self.has_callbacks:
109 self.space.finalizer_queue.register_finalizer(self)
110 self.has_callbacks = True
111
112 @jit.dont_look_inside
113 def make_weakref_with_callback(self, w_subtype, w_obj, w_callable):
114 space = self.space
115 w_ref = space.allocate_instance(W_Weakref, w_subtype)
116 W_Weakref.__init__(w_ref, space, w_obj, w_callable)
117 self.append_wref_to(w_ref)
118 self.enable_callbacks()
119 return w_ref
120
121 @jit.dont_look_inside
122 def make_proxy_with_callback(self, w_obj, w_callable):
123 space = self.space
124 if space.is_true(space.callable(w_obj)):
125 w_proxy = W_CallableProxy(space, w_obj, w_callable)
126 else:
127 w_proxy = W_Proxy(space, w_obj, w_callable)
128 self.append_wref_to(w_proxy)
129 self.enable_callbacks()
130 return w_proxy
131
132 def _finalize_(self):
133 """This is called at the end, if enable_callbacks() was invoked.
134 It activates the callbacks.
135 """
136 if self.other_refs_weak is None:
137 return
138 #
139 # If this is set, then we're in the 'gc.disable()' mode. In that
140 # case, don't invoke the callbacks now.
141 if self.space.user_del_action.gc_disabled(self):
142 return
143 #
144 items = self.other_refs_weak.items()
145 self.other_refs_weak = None
146 for i in range(len(items)-1, -1, -1):
147 w_ref = items[i]()
148 if w_ref is not None and w_ref.w_callable is not None:
149 try:
150 w_ref.activate_callback()
151 except Exception as e:
152 report_error(self.space, e,
153 "weakref callback ", w_ref.w_callable)
154 w_ref.w_callable = None
155
156
157 # ____________________________________________________________
158
159
160 class W_WeakrefBase(W_Root):
161 exact_class_applevel_name = 'weakref-or-proxy'
162
163 def __init__(self, space, w_obj, w_callable):
164 assert w_callable is not space.w_None # should be really None
165 self.space = space
166 assert w_obj is not None
167 self.w_obj_weak = weakref.ref(w_obj)
168 self.w_callable = w_callable
169
170 @jit.dont_look_inside
171 def dereference(self):
172 w_obj = self.w_obj_weak()
173 return w_obj
174
175 def clear(self):
176 self.w_obj_weak = dead_ref
177
178 def activate_callback(self):
179 self.space.call_function(self.w_callable, self)
180
181 def descr__repr__(self, space):
182 w_obj = self.dereference()
183 if w_obj is None:
184 state = '; dead'
185 else:
186 typename = space.type(w_obj).getname(space)
187 objname = w_obj.getname(space)
188 if objname and objname != '?':
189 state = "; to '%s' (%s)" % (typename, objname)
190 else:
191 state = "; to '%s'" % (typename,)
192 return self.getrepr(space, self.typedef.name, state)
193
194
195 class W_Weakref(W_WeakrefBase):
196 def __init__(self, space, w_obj, w_callable):
197 W_WeakrefBase.__init__(self, space, w_obj, w_callable)
198 self.w_hash = None
199
200 def _cleanup_(self):
201 # When a prebuilt weakref is frozen inside a translation, if
202 # this weakref has got an already-cached w_hash, then throw it
203 # away. That's because the hash value will change after
204 # translation. It will be recomputed the first time we ask for
205 # it. Note that such a frozen weakref, if not dead, will point
206 # to a frozen object, so it will never die.
207 self.w_hash = None
208
209 def descr__init__weakref(self, space, w_obj, w_callable=None):
210 pass
211
212 def descr_hash(self):
213 if self.w_hash is not None:
214 return self.w_hash
215 w_obj = self.dereference()
216 if w_obj is None:
217 raise oefmt(self.space.w_TypeError, "weak object has gone away")
218 self.w_hash = self.space.hash(w_obj)
219 return self.w_hash
220
221 def descr_call(self):
222 w_obj = self.dereference()
223 if w_obj is None:
224 return self.space.w_None
225 return w_obj
226
227 def compare(self, space, w_ref2, invert):
228 if not isinstance(w_ref2, W_Weakref):
229 return space.w_NotImplemented
230 ref1 = self
231 ref2 = w_ref2
232 w_obj1 = ref1.dereference()
233 w_obj2 = ref2.dereference()
234 if w_obj1 is None or w_obj2 is None:
235 w_res = space.is_(ref1, ref2)
236 else:
237 w_res = space.eq(w_obj1, w_obj2)
238 if invert:
239 w_res = space.not_(w_res)
240 return w_res
241
242 def descr__eq__(self, space, w_ref2):
243 return self.compare(space, w_ref2, invert=False)
244
245 def descr__ne__(self, space, w_ref2):
246 return self.compare(space, w_ref2, invert=True)
247
248 def descr_callback(self, space):
249 return self.w_callable
250
251 def getlifeline(space, w_obj):
252 lifeline = w_obj.getweakref()
253 if lifeline is None:
254 lifeline = WeakrefLifeline(space)
255 w_obj.setweakref(space, lifeline)
256 return lifeline
257
258
259 def descr__new__weakref(space, w_subtype, w_obj, w_callable=None,
260 __args__=None):
261 if __args__.arguments_w:
262 raise oefmt(space.w_TypeError, "__new__ expected at most 2 arguments")
263 lifeline = getlifeline(space, w_obj)
264 if space.is_none(w_callable):
265 return lifeline.get_or_make_weakref(w_subtype, w_obj)
266 else:
267 return lifeline.make_weakref_with_callback(w_subtype, w_obj, w_callable)
268
269 W_Weakref.typedef = TypeDef("weakref.ReferenceType",
270 __doc__ = """A weak reference to an object 'obj'. A 'callback' can be given,
271 which is called with 'obj' as an argument when it is about to be finalized.""",
272 __new__ = interp2app(descr__new__weakref),
273 __init__ = interp2app(W_Weakref.descr__init__weakref),
274 __eq__ = interp2app(W_Weakref.descr__eq__),
275 __ne__ = interp2app(W_Weakref.descr__ne__),
276 __hash__ = interp2app(W_Weakref.descr_hash),
277 __call__ = interp2app(W_Weakref.descr_call),
278 __repr__ = interp2app(W_WeakrefBase.descr__repr__),
279 __callback__ = GetSetProperty(W_Weakref.descr_callback),
280 __class_getitem__ = interp2app(
281 generic_alias_class_getitem, as_classmethod=True),
282 )
283
284
285 def _weakref_count(lifeline, wref, count):
286 if wref() is not None:
287 count += 1
288 return count
289
290 def getweakrefcount(space, w_obj):
291 """Return the number of weak references to 'obj'."""
292 lifeline = w_obj.getweakref()
293 if lifeline is None:
294 return space.newint(0)
295 else:
296 result = lifeline.traverse(_weakref_count, 0)
297 return space.newint(result)
298
299 def _get_weakrefs(lifeline, wref, result):
300 w_ref = wref()
301 if w_ref is not None:
302 result.append(w_ref)
303 return result
304
305 def getweakrefs(space, w_obj):
306 """Return a list of all weak reference objects that point to 'obj'."""
307 result = []
308 lifeline = w_obj.getweakref()
309 if lifeline is not None:
310 lifeline.traverse(_get_weakrefs, result)
311 return space.newlist(result)
312
313 #_________________________________________________________________
314 # Proxy
315
316 class W_AbstractProxy(W_WeakrefBase):
317 pass
318
319 class W_Proxy(W_AbstractProxy):
320 def descr__hash__(self, space):
321 raise oefmt(space.w_TypeError, "unhashable type")
322
323 class W_CallableProxy(W_AbstractProxy):
324 def descr__call__(self, space, __args__):
325 w_obj = force(space, self)
326 return space.call_args(w_obj, __args__)
327
328 def descr__hash__(self, space):
329 raise oefmt(space.w_TypeError, "unhashable type")
330
331 def proxy(space, w_obj, w_callable=None):
332 """Create a proxy object that weakly references 'obj'.
333 'callback', if given, is called with the proxy as an argument when 'obj'
334 is about to be finalized."""
335 lifeline = getlifeline(space, w_obj)
336 if space.is_none(w_callable):
337 return lifeline.get_or_make_proxy(w_obj)
338 else:
339 return lifeline.make_proxy_with_callback(w_obj, w_callable)
340
341 def descr__new__proxy(space, w_subtype, w_obj, w_callable=None):
342 raise oefmt(space.w_TypeError, "cannot create 'weakproxy' instances")
343
344 def descr__new__callableproxy(space, w_subtype, w_obj, w_callable=None):
345 raise oefmt(space.w_TypeError,
346 "cannot create 'weakcallableproxy' instances")
347
348
349 def force(space, proxy):
350 if not isinstance(proxy, W_AbstractProxy):
351 return proxy
352 w_obj = proxy.dereference()
353 if w_obj is None:
354 raise oefmt(space.w_ReferenceError,
355 "weakly referenced object no longer exists")
356 return w_obj
357
358 proxy_typedef_dict = {}
359 callable_proxy_typedef_dict = {}
360 special_ops = {'repr': True, 'hash': True}
361
362 for opname, _, arity, special_methods in ObjSpace.MethodTable:
363 if opname in special_ops or not special_methods:
364 continue
365 nonspaceargs = ", ".join(["w_obj%s" % i for i in range(arity)])
366 code = "def func(space, %s):\n '''%s'''\n" % (nonspaceargs, opname)
367 assert arity >= len(special_methods)
368 forcing_count = len(special_methods)
369 if opname.startswith('inplace_'):
370 assert arity == 2
371 forcing_count = arity
372 for i in range(forcing_count):
373 code += " w_obj%s = force(space, w_obj%s)\n" % (i, i)
374 code += " return space.%s(%s)" % (opname, nonspaceargs)
375 exec py.code.Source(code).compile()
376
377 func.func_name = opname
378 if len(special_methods) == 2 and special_methods[1].startswith("__r"):
379 proxy_typedef_dict[special_methods[0]] = interp2app(func)
380 callable_proxy_typedef_dict[special_methods[0]] = interp2app(func)
381
382 # HACK: need to call the space method with arguments in the reverse
383 # order!
384 code = code.replace("(w_obj0, w_obj1)", "(w_obj1, w_obj0)")
385 code = code.replace("func", "rfunc")
386
387 exec py.code.Source(code).compile()
388 rfunc.func_name = special_methods[1][2:-2]
389
390 proxy_typedef_dict[special_methods[1]] = interp2app(rfunc)
391 callable_proxy_typedef_dict[special_methods[1]] = interp2app(rfunc)
392 elif opname in ["lt", "le", "gt", "ge", "eq", "ne"]:
393 proxy_typedef_dict[special_methods[0]] = interp2app(func)
394 else:
395 for special_method in special_methods:
396 proxy_typedef_dict[special_method] = interp2app(func)
397 callable_proxy_typedef_dict[special_method] = interp2app(func)
398
399 # __bytes__ is not yet a space operation
400 def proxy_bytes(space, w_obj):
401 w_obj = force(space, w_obj)
402 return space.call_method(w_obj, '__bytes__')
403 proxy_typedef_dict['__bytes__'] = interp2app(proxy_bytes)
404 callable_proxy_typedef_dict['__bytes__'] = interp2app(proxy_bytes)
405
406 # neither is __reversed__
407 def proxy_reversed(space, w_obj):
408 w_obj = force(space, w_obj)
409 return space.call_method(w_obj, '__reversed__')
410 proxy_typedef_dict['__reversed__'] = interp2app(proxy_reversed)
411 callable_proxy_typedef_dict['__reversed__'] = interp2app(proxy_reversed)
412
413 # __next__ needs a special error message when the referent is not an iterator
414 def proxy_iternext(space, w_obj):
415 w_obj = force(space, w_obj)
416 if not space.lookup(w_obj, '__next__'):
417 raise oefmt(space.w_TypeError,
418 "Weakref proxy referenced a non-iterator")
419 return space.next(w_obj)
420 proxy_typedef_dict['__next__'] = interp2app(proxy_iternext)
421 callable_proxy_typedef_dict['__next__'] = interp2app(proxy_iternext)
422
423 W_Proxy.typedef = TypeDef("weakref.ProxyType",
424 __new__ = interp2app(descr__new__proxy),
425 __hash__ = interp2app(W_Proxy.descr__hash__),
426 __repr__ = interp2app(W_WeakrefBase.descr__repr__),
427 **proxy_typedef_dict)
428 W_Proxy.typedef.acceptable_as_base_class = False
429
430 W_CallableProxy.typedef = TypeDef("weakref.CallableProxyType",
431 __new__ = interp2app(descr__new__callableproxy),
432 __hash__ = interp2app(W_CallableProxy.descr__hash__),
433 __repr__ = interp2app(W_WeakrefBase.descr__repr__),
434 __call__ = interp2app(W_CallableProxy.descr__call__),
435 **callable_proxy_typedef_dict)
436 W_CallableProxy.typedef.acceptable_as_base_class = False