Debian Codegraph @

rpython/rlib/rweakref.py

raw symbols SCIP
1 """
2 Weakref support in RPython. Basic regular weakrefs without callbacks
3 are supported. This file contains the following additions:
4 a form of WeakKeyDictionary, and a limited version of WeakValueDictionary.
5 """
6
7 import weakref
8 from rpython.annotator.model import UnionError
9
10
11 # Basic regular weakrefs are supported in RPython.
12 # Note that if 'translation.rweakref' is False, they will
13 # still work, but be implemented as a strong reference.
14 # This case is useful for developing new GCs, for example.
15
16 ref = weakref.ref
17
18
19 def has_weakref_support():
20 return True # returns False if --no-translation-rweakref
21
22 class Dummy:
23 pass
24 dead_ref = weakref.ref(Dummy())
25 for i in range(5):
26 if dead_ref() is not None:
27 import gc; gc.collect()
28 assert dead_ref() is None # a known-to-be-dead weakref object
29
30
31 class RWeakValueDictionary(object):
32 """A dictionary containing weak values."""
33
34 def __init__(self, keyclass, valueclass):
35 """'keyclass' can be an RPython class or a type like 'int' or 'str'.
36 On the other hand, 'valueclass' must be an RPython class.
37 """
38 self._dict = weakref.WeakValueDictionary()
39 self._keyclass = keyclass
40 self._valueclass = valueclass
41
42 def get(self, key):
43 assert isinstance(key, self._keyclass)
44 return self._dict.get(key, None)
45
46 def set(self, key, value):
47 assert isinstance(key, self._keyclass)
48 if value is None:
49 self._dict.pop(key, None)
50 else:
51 assert isinstance(value, self._valueclass)
52 self._dict[key] = value
53
54
55 class RWeakKeyDictionary(object):
56 """A dictionary containing weak keys.
57 Keys and values must be instances.
58 Prebuilt RWeakKeyDictionaries must be empty.
59 """
60
61 def __init__(self, keyclass, valueclass):
62 self._dict = weakref.WeakKeyDictionary()
63 self._keyclass = keyclass
64 self._valueclass = valueclass
65
66 def get(self, key):
67 """Get the value associated to 'key', or None by default."""
68 assert isinstance(key, self._keyclass)
69 return self._dict.get(key, None)
70
71 def set(self, key, value):
72 """Set the key/value pair (or delete it if value is None)."""
73 assert isinstance(key, self._keyclass)
74 if value is None:
75 self._dict.pop(key, None)
76 else:
77 assert isinstance(value, self._valueclass)
78 self._dict[key] = value
79
80 def length(self):
81 """Mostly for debugging. Slow, don't use in real code."""
82 return len(self._dict)
83
84
85 # ____________________________________________________________
86
87 from rpython.rtyper import extregistry
88 from rpython.annotator import model as annmodel
89 from rpython.tool.pairtype import pairtype
90
91 class Entry(extregistry.ExtRegistryEntry):
92 _about_ = has_weakref_support
93
94 def compute_result_annotation(self):
95 translator = self.bookkeeper.annotator.translator
96 res = translator.config.translation.rweakref
97 return self.bookkeeper.immutablevalue(res)
98
99 def specialize_call(self, hop):
100 from rpython.rtyper.lltypesystem import lltype
101 hop.exception_cannot_occur()
102 return hop.inputconst(lltype.Bool, hop.s_result.const)
103
104
105 class SomeWeakValueDict(annmodel.SomeObject):
106 knowntype = RWeakValueDictionary
107
108 def __init__(self, s_key, valueclassdef):
109 self.s_key = s_key
110 self.valueclassdef = valueclassdef
111
112 def can_be_none(self):
113 return True
114
115 def noneify(self):
116 return self
117
118 def rtyper_makerepr(self, rtyper):
119 from rpython.rlib import _rweakvaldict
120 return _rweakvaldict.WeakValueDictRepr(rtyper,
121 rtyper.getrepr(self.s_key))
122
123 def rtyper_makekey(self):
124 return self.__class__, self.s_key.rtyper_makekey(), self.valueclassdef
125
126 def method_get(self, s_key):
127 return annmodel.SomeInstance(self.valueclassdef, can_be_None=True)
128
129 def method_set(self, s_key, s_value):
130 s_oldvalue = self.method_get(s_key)
131 assert s_oldvalue.contains(s_value)
132
133 class __extend__(pairtype(SomeWeakValueDict, SomeWeakValueDict)):
134 def union((s_wvd1, s_wvd2)):
135 if s_wvd1.valueclassdef is not s_wvd2.valueclassdef:
136 raise UnionError(s_wvd1, s_wvd2, "not the same class!")
137 s_key = annmodel.unionof(s_wvd1.s_key, s_wvd2.s_key)
138 return SomeWeakValueDict(s_key, s_wvd1.valueclassdef)
139
140 class Entry(extregistry.ExtRegistryEntry):
141 _about_ = RWeakValueDictionary
142
143 def compute_result_annotation(self, s_keyclass, s_valueclass):
144 assert s_keyclass.is_constant()
145 s_key = self.bookkeeper.valueoftype(s_keyclass.const)
146 return SomeWeakValueDict(
147 s_key,
148 _getclassdef(s_valueclass))
149
150 def specialize_call(self, hop):
151 from rpython.rlib import _rweakvaldict
152 return _rweakvaldict.specialize_make_weakdict(hop)
153
154 class Entry(extregistry.ExtRegistryEntry):
155 _type_ = RWeakValueDictionary
156
157 def compute_annotation(self):
158 bk = self.bookkeeper
159 x = self.instance
160 return SomeWeakValueDict(
161 bk.valueoftype(x._keyclass),
162 bk.getuniqueclassdef(x._valueclass))
163
164 def _getclassdef(s_instance):
165 assert isinstance(s_instance, annmodel.SomePBC)
166 assert s_instance.is_constant()
167 [desc] = s_instance.descriptions
168 return desc.getuniqueclassdef()
169
170 # ____________________________________________________________
171
172 class SomeWeakKeyDict(annmodel.SomeObject):
173 knowntype = RWeakKeyDictionary
174
175 def __init__(self, keyclassdef, valueclassdef):
176 self.keyclassdef = keyclassdef
177 self.valueclassdef = valueclassdef
178
179 def rtyper_makerepr(self, rtyper):
180 from rpython.rlib import _rweakkeydict
181 return _rweakkeydict.WeakKeyDictRepr(rtyper)
182
183 def rtyper_makekey(self):
184 return self.__class__, self.keyclassdef, self.valueclassdef
185
186 def method_get(self, s_key):
187 assert isinstance(s_key, annmodel.SomeInstance)
188 assert s_key.classdef.issubclass(self.keyclassdef)
189 return annmodel.SomeInstance(self.valueclassdef, can_be_None=True)
190
191 def method_set(self, s_key, s_value):
192 s_oldvalue = self.method_get(s_key)
193 assert s_oldvalue.contains(s_value)
194
195 def method_length(self):
196 return annmodel.SomeInteger(nonneg=True)
197
198 class __extend__(pairtype(SomeWeakKeyDict, SomeWeakKeyDict)):
199 def union((s_wkd1, s_wkd2)):
200 if s_wkd1.keyclassdef is not s_wkd2.keyclassdef:
201 raise UnionError(s_wkd1, s_wkd2, "not the same key class!")
202 if s_wkd1.valueclassdef is not s_wkd2.valueclassdef:
203 raise UnionError(s_wkd1, s_wkd2, "not the same value class!")
204 return SomeWeakKeyDict(s_wkd1.keyclassdef, s_wkd1.valueclassdef)
205
206 class Entry(extregistry.ExtRegistryEntry):
207 _about_ = RWeakKeyDictionary
208
209 def compute_result_annotation(self, s_keyclass, s_valueclass):
210 return SomeWeakKeyDict(_getclassdef(s_keyclass),
211 _getclassdef(s_valueclass))
212
213 def specialize_call(self, hop):
214 from rpython.rlib import _rweakkeydict
215 return _rweakkeydict.specialize_make_weakdict(hop)
216
217 class Entry(extregistry.ExtRegistryEntry):
218 _type_ = RWeakKeyDictionary
219
220 def compute_annotation(self):
221 bk = self.bookkeeper
222 x = self.instance
223 return SomeWeakKeyDict(bk.getuniqueclassdef(x._keyclass),
224 bk.getuniqueclassdef(x._valueclass))