Debian Codegraph @

rpython/rlib/rerased.py

raw symbols SCIP
1 """ Contains a mechanism for turning any class instance and any integer into a
2 pointer-like thing. Gives full control over pointer tagging, i.e. there won't
3 be tag checks everywhere in the C code.
4
5 Usage: erasestuff, unerasestuff = new_erasing_pair('stuff')
6
7 An erasestuff(x) object contains a reference to 'x'. Nothing can be done with
8 this object, except calling unerasestuff(), which returns 'x' again. The point
9 is that all erased objects can be mixed together, whether they are instances,
10 lists, strings, etc. As a special case, an erased object can also be an
11 integer fitting into 31/63 bits, with erase_int() and unerase_int().
12
13 Warning: some care is needed to make sure that you call the unerase function
14 corresponding to the original creator's erase function. Otherwise, segfault.
15 """
16
17 import sys
18 from collections import defaultdict
19
20 from rpython.annotator import model as annmodel
21 from rpython.rtyper.extregistry import ExtRegistryEntry
22 from rpython.rtyper.llannotation import lltype_to_annotation
23 from rpython.rtyper.lltypesystem import lltype, llmemory
24 from rpython.rtyper.lltypesystem.lloperation import llop
25 from rpython.rlib.rarithmetic import is_valid_int
26 from rpython.rlib.debug import ll_assert
27 from rpython.rlib.objectmodel import we_are_translated, specialize
28 from rpython.rlib import jit
29
30
31 def erase_int(x):
32 assert is_valid_int(x)
33 res = 2 * x + 1
34 if res > sys.maxint or res < -sys.maxint - 1:
35 raise OverflowError
36 return Erased(x, _identity_for_ints)
37
38 def unerase_int(y):
39 assert y._identity is _identity_for_ints
40 assert is_valid_int(y._x)
41 return y._x
42
43
44 class ErasingPairIdentity(object):
45
46 def __init__(self, name):
47 self.name = name
48
49 def __repr__(self):
50 return 'ErasingPairIdentity(%r)' % self.name
51
52 def __deepcopy__(self, memo):
53 return self
54
55 class IdentityDesc(object):
56 def __init__(self, bookkeeper):
57 self.bookkeeper = bookkeeper
58 self.s_input = annmodel.s_ImpossibleValue
59 self.reflowpositions = {}
60
61 def enter_tunnel(self, s_obj):
62 s_obj = annmodel.unionof(self.s_input, s_obj)
63 if s_obj != self.s_input:
64 self.s_input = s_obj
65 for position in self.reflowpositions:
66 self.bookkeeper.annotator.reflowfromposition(position)
67
68 def leave_tunnel(self):
69 self.reflowpositions[self.bookkeeper.position_key] = True
70 return self.s_input
71
72 def _get_desc(bk, identity):
73 try:
74 descs = bk._erasing_pairs_descs
75 except AttributeError:
76 descs = bk._erasing_pairs_descs = defaultdict(lambda: IdentityDesc(bk))
77 return descs[identity]
78
79 _identity_for_ints = ErasingPairIdentity("int")
80
81
82 def new_erasing_pair(name):
83 identity = ErasingPairIdentity(name)
84
85 def erase(x):
86 assert not isinstance(x, Erased)
87 return Erased(x, identity)
88
89 def unerase(y):
90 assert y._identity is identity
91 return y._x
92
93 class Entry(ExtRegistryEntry):
94 _about_ = erase
95
96 def compute_result_annotation(self, s_obj):
97 desc = _get_desc(self.bookkeeper, identity)
98 desc.enter_tunnel(s_obj)
99 return _some_erased()
100
101 def specialize_call(self, hop):
102 bk = hop.rtyper.annotator.bookkeeper
103 desc = _get_desc(bk, identity)
104 hop.exception_cannot_occur()
105 return _rtype_erase(hop, desc.s_input)
106
107 class Entry(ExtRegistryEntry):
108 _about_ = unerase
109
110 def compute_result_annotation(self, s_obj):
111 assert _some_erased().contains(s_obj)
112 desc = _get_desc(self.bookkeeper, identity)
113 return desc.leave_tunnel()
114
115 def specialize_call(self, hop):
116 hop.exception_cannot_occur()
117 if hop.r_result.lowleveltype is lltype.Void:
118 return hop.inputconst(lltype.Void, None)
119 [v] = hop.inputargs(hop.args_r[0])
120 return _rtype_unerase(hop, v)
121
122 return erase, unerase
123
124 def new_static_erasing_pair(name):
125 erase, unerase = new_erasing_pair(name)
126 return staticmethod(erase), staticmethod(unerase)
127
128 @specialize.arg(0)
129 @jit.dont_look_inside
130 def try_cast_erased(Class, erased):
131 if we_are_translated():
132 from rpython.rtyper.rclass import OBJECTPTR, ll_isinstance
133 from rpython.rtyper.annlowlevel import cast_base_ptr_to_instance
134 from rpython.rlib.rgc import _is_rpy_instance, _get_llcls_from_cls
135 if _is_rpy_instance(erased):
136 objptr = lltype.cast_opaque_ptr(OBJECTPTR, erased)
137 if objptr.typeptr: # may be NULL, e.g. in rdict's dummykeyobj
138 clsptr = _get_llcls_from_cls(Class)
139 if ll_isinstance(objptr, clsptr):
140 return cast_base_ptr_to_instance(Class, objptr)
141 return None
142 else:
143 if isinstance(erased._x, Class):
144 return erased._x
145 return None
146
147 # ---------- implementation-specific ----------
148
149 class Erased(object):
150 def __init__(self, x, identity):
151 self._x = x
152 self._identity = identity
153
154 def __repr__(self):
155 return "Erased(%r, %r)" % (self._x, self._identity)
156
157 def _convert_const_ptr(self, r_self):
158 value = self
159 if value._identity is _identity_for_ints:
160 config = r_self.rtyper.annotator.translator.config
161 assert config.translation.taggedpointers, "need to enable tagged pointers to use erase_int"
162 return lltype.cast_int_to_ptr(r_self.lowleveltype, value._x * 2 + 1)
163 bk = r_self.rtyper.annotator.bookkeeper
164 s_obj = _get_desc(bk, value._identity).s_input
165 r_obj = r_self.rtyper.getrepr(s_obj)
166 if r_obj.lowleveltype is lltype.Void:
167 return lltype.nullptr(r_self.lowleveltype.TO)
168 v = r_obj.convert_const(value._x)
169 return lltype.cast_opaque_ptr(r_self.lowleveltype, v)
170
171
172 class Entry(ExtRegistryEntry):
173 _about_ = erase_int
174
175 def compute_result_annotation(self, s_obj):
176 config = self.bookkeeper.annotator.translator.config
177 assert config.translation.taggedpointers, "need to enable tagged pointers to use erase_int"
178 assert annmodel.SomeInteger().contains(s_obj)
179 return _some_erased()
180
181 def specialize_call(self, hop):
182 return _rtype_erase_int(hop)
183
184 class Entry(ExtRegistryEntry):
185 _about_ = unerase_int
186
187 def compute_result_annotation(self, s_obj):
188 assert _some_erased().contains(s_obj)
189 return annmodel.SomeInteger()
190
191 def specialize_call(self, hop):
192 [v] = hop.inputargs(hop.args_r[0])
193 assert isinstance(hop.s_result, annmodel.SomeInteger)
194 return _rtype_unerase_int(hop, v)
195
196 def ll_unerase_int(gcref):
197 x = llop.cast_ptr_to_int(lltype.Signed, gcref)
198 ll_assert((x&1) != 0, "unerased_int(): not an integer")
199 return x >> 1
200
201
202 class Entry(ExtRegistryEntry):
203 _type_ = Erased
204
205 def compute_annotation(self):
206 desc = _get_desc(self.bookkeeper, self.instance._identity)
207 s_obj = self.bookkeeper.immutablevalue(self.instance._x)
208 desc.enter_tunnel(s_obj)
209 return _some_erased()
210
211 # annotation and rtyping support
212
213 def _some_erased():
214 return lltype_to_annotation(llmemory.GCREF)
215
216 def _rtype_erase(hop, s_obj):
217 hop.exception_cannot_occur()
218 r_obj = hop.rtyper.getrepr(s_obj)
219 if r_obj.lowleveltype is lltype.Void:
220 return hop.inputconst(llmemory.GCREF,
221 lltype.nullptr(llmemory.GCREF.TO))
222 [v_obj] = hop.inputargs(r_obj)
223 return hop.genop('cast_opaque_ptr', [v_obj],
224 resulttype=llmemory.GCREF)
225
226 def _rtype_unerase(hop, s_obj):
227 [v] = hop.inputargs(hop.args_r[0])
228 return hop.genop('cast_opaque_ptr', [v], resulttype=hop.r_result)
229
230 def _rtype_unerase_int(hop, v):
231 hop.exception_cannot_occur()
232 return hop.gendirectcall(ll_unerase_int, v)
233
234 def _rtype_erase_int(hop):
235 [v_value] = hop.inputargs(lltype.Signed)
236 c_one = hop.inputconst(lltype.Signed, 1)
237 hop.exception_is_here()
238 v2 = hop.genop('int_add_ovf', [v_value, v_value],
239 resulttype = lltype.Signed)
240 v2p1 = hop.genop('int_add', [v2, c_one],
241 resulttype = lltype.Signed)
242 v_instance = hop.genop('cast_int_to_ptr', [v2p1],
243 resulttype=llmemory.GCREF)
244 return v_instance