Debian Codegraph @

rpython/rtyper/rmodel.py

raw symbols SCIP
1 from rpython.annotator import model as annmodel, unaryop, binaryop, description
2 from rpython.flowspace.model import Constant
3 from rpython.rtyper.error import TyperError, MissingRTypeOperation
4 from rpython.rtyper.lltypesystem import lltype
5 from rpython.rtyper.lltypesystem.lltype import Void, Bool, LowLevelType, Ptr
6 from rpython.tool.pairtype import pairtype, extendabletype, pair
7
8 # initialization states for Repr instances
9
10 class setupstate(object):
11 NOTINITIALIZED = 0
12 INPROGRESS = 1
13 BROKEN = 2
14 FINISHED = 3
15 DELAYED = 4
16
17 class Repr(object):
18 """ An instance of Repr is associated with each instance of SomeXxx.
19 It defines the chosen representation for the SomeXxx. The Repr subclasses
20 generally follows the SomeXxx subclass hierarchy, but there are numerous
21 exceptions. For example, the annotator uses SomeIter for any iterator, but
22 we need different representations according to the type of container we are
23 iterating over.
24 """
25 __metaclass__ = extendabletype
26 _initialized = setupstate.NOTINITIALIZED
27 __NOT_RPYTHON__ = True
28
29 def __repr__(self):
30 return '<%s %s>' % (self.__class__.__name__, self.lowleveltype)
31
32 def compact_repr(self):
33 return '%s %s' % (self.__class__.__name__.replace('Repr','R'), self.lowleveltype._short_name())
34
35 def setup(self):
36 """ call _setup_repr() and keep track of the initializiation
37 status to e.g. detect recursive _setup_repr invocations.
38 the '_initialized' attr has four states:
39 """
40 if self._initialized == setupstate.FINISHED:
41 return
42 elif self._initialized == setupstate.BROKEN:
43 raise BrokenReprTyperError(
44 "cannot setup already failed Repr: %r" %(self,))
45 elif self._initialized == setupstate.INPROGRESS:
46 raise AssertionError(
47 "recursive invocation of Repr setup(): %r" %(self,))
48 elif self._initialized == setupstate.DELAYED:
49 raise AssertionError(
50 "Repr setup() is delayed and cannot be called yet: %r" %(self,))
51 assert self._initialized == setupstate.NOTINITIALIZED
52 self._initialized = setupstate.INPROGRESS
53 try:
54 self._setup_repr()
55 except TyperError:
56 self._initialized = setupstate.BROKEN
57 raise
58 else:
59 self._initialized = setupstate.FINISHED
60
61 def _setup_repr(self):
62 "For recursive data structure, which must be initialized in two steps."
63
64 def setup_final(self):
65 """Same as setup(), called a bit later, for effects that are only
66 needed after the typer finished (as opposed to needed for other parts
67 of the typer itself)."""
68 if self._initialized == setupstate.BROKEN:
69 raise BrokenReprTyperError("cannot perform setup_final_touch "
70 "on failed Repr: %r" %(self,))
71 assert self._initialized == setupstate.FINISHED, (
72 "setup_final() on repr with state %s: %r" %
73 (self._initialized, self))
74 self._setup_repr_final()
75
76 def _setup_repr_final(self):
77 pass
78
79 def is_setup_delayed(self):
80 return self._initialized == setupstate.DELAYED
81
82 def set_setup_delayed(self, flag):
83 assert self._initialized in (setupstate.NOTINITIALIZED,
84 setupstate.DELAYED)
85 if flag:
86 self._initialized = setupstate.DELAYED
87 else:
88 self._initialized = setupstate.NOTINITIALIZED
89
90 def set_setup_maybe_delayed(self):
91 if self._initialized == setupstate.NOTINITIALIZED:
92 self._initialized = setupstate.DELAYED
93 return self._initialized == setupstate.DELAYED
94
95 def __getattr__(self, name):
96 # Assume that when an attribute is missing, it's because setup() needs
97 # to be called
98 if not (name[:2] == '__' == name[-2:]):
99 if self._initialized == setupstate.NOTINITIALIZED:
100 self.setup()
101 try:
102 return self.__dict__[name]
103 except KeyError:
104 pass
105 raise AttributeError("%s instance has no attribute %s" % (
106 self.__class__.__name__, name))
107
108 def _freeze_(self):
109 return True
110
111 def convert_desc_or_const(self, desc_or_const):
112 if isinstance(desc_or_const, description.Desc):
113 return self.convert_desc(desc_or_const)
114 elif isinstance(desc_or_const, Constant):
115 return self.convert_const(desc_or_const.value)
116 else:
117 raise TyperError("convert_desc_or_const expects a Desc"
118 "or Constant: %r" % desc_or_const)
119
120 def convert_const(self, value):
121 "Convert the given constant value to the low-level repr of 'self'."
122 if not self.lowleveltype._contains_value(value):
123 raise TyperError("convert_const(self = %r, value = %r)" % (
124 self, value))
125 return value
126
127 def special_uninitialized_value(self):
128 return None
129
130 def get_ll_eq_function(self):
131 """Return an eq(x,y) function to use to compare two low-level
132 values of this Repr.
133 This can return None to mean that simply using '==' is fine.
134 """
135 raise TyperError('no equality function for %r' % self)
136
137 def get_ll_hash_function(self):
138 """Return a hash(x) function for low-level values of this Repr.
139 """
140 raise TyperError('no hashing function for %r' % self)
141
142 def get_ll_fasthash_function(self):
143 """Return a 'fast' hash(x) function for low-level values of this
144 Repr. The function can assume that 'x' is already stored as a
145 key in a dict. get_ll_fasthash_function() should return None if
146 the hash should rather be cached in the dict entry.
147 """
148 return None
149
150 def can_ll_be_null(self, s_value):
151 """Check if the low-level repr can take the value 0/NULL.
152 The annotation s_value is provided as a hint because it may
153 contain more information than the Repr.
154 """
155 return True # conservative
156
157 def get_ll_dummyval_obj(self, rtyper, s_value):
158 """A dummy value is a special low-level value, not otherwise
159 used. It should not be the NULL value even if it is special.
160 This returns either None, or a hashable object that has a
161 (possibly lazy) attribute 'll_dummy_value'.
162 The annotation s_value is provided as a hint because it may
163 contain more information than the Repr.
164 """
165 T = self.lowleveltype
166 if (isinstance(T, lltype.Ptr) and
167 isinstance(T.TO, (lltype.Struct,
168 lltype.Array,
169 lltype.ForwardReference))):
170 return DummyValueBuilder(rtyper, T.TO)
171 else:
172 return None
173
174 def rtype_bltn_list(self, hop):
175 raise TyperError('no list() support for %r' % self)
176
177 def rtype_unichr(self, hop):
178 raise TyperError('no unichr() support for %r' % self)
179
180 # default implementation of some operations
181
182 def rtype_getattr(self, hop):
183 s_attr = hop.args_s[1]
184 if s_attr.is_constant() and isinstance(s_attr.const, str):
185 attr = s_attr.const
186 s_obj = hop.args_s[0]
187 if s_obj.find_method(attr) is None:
188 raise TyperError("no method %s on %r" % (attr, s_obj))
189 else:
190 # implement methods (of a known name) as just their 'self'
191 return hop.inputarg(self, arg=0)
192 else:
193 raise TyperError("getattr() with a non-constant attribute name")
194
195 def rtype_str(self, hop):
196 [v_self] = hop.inputargs(self)
197 return hop.gendirectcall(self.ll_str, v_self)
198
199 def rtype_bool(self, hop):
200 try:
201 vlen = self.rtype_len(hop)
202 except MissingRTypeOperation:
203 if not hop.s_result.is_constant():
204 raise TyperError("rtype_bool(%r) not implemented" % (self,))
205 return hop.inputconst(Bool, hop.s_result.const)
206 else:
207 return hop.genop('int_is_true', [vlen], resulttype=Bool)
208
209 def rtype_isinstance(self, hop):
210 hop.exception_cannot_occur()
211 if hop.s_result.is_constant():
212 return hop.inputconst(lltype.Bool, hop.s_result.const)
213
214 if hop.args_s[1].is_constant() and hop.args_s[1].const in (str, list, unicode):
215 if hop.args_s[0].knowntype not in (str, list, unicode):
216 raise TyperError("isinstance(x, str/list/unicode) expects x to be known"
217 " statically to be a str/list/unicode or None")
218 rstrlist = hop.args_r[0]
219 vstrlist = hop.inputarg(rstrlist, arg=0)
220 cnone = hop.inputconst(rstrlist, None)
221 return hop.genop('ptr_ne', [vstrlist, cnone], resulttype=lltype.Bool)
222 raise TyperError
223
224 def rtype_hash(self, hop):
225 ll_hash = self.get_ll_hash_function()
226 v, = hop.inputargs(self)
227 return hop.gendirectcall(ll_hash, v)
228
229 def rtype_iter(self, hop):
230 r_iter = self.make_iterator_repr()
231 return r_iter.newiter(hop)
232
233 def make_iterator_repr(self, *variant):
234 raise TyperError("%s is not iterable" % (self,))
235
236 def rtype_hint(self, hop):
237 return hop.inputarg(hop.r_result, arg=0)
238
239 # hlinvoke helpers
240
241 def get_r_implfunc(self):
242 raise TyperError("%s has no corresponding implementation function representation" % (self,))
243
244 def get_s_callable(self):
245 raise TyperError("%s is not callable or cannot reconstruct a pbc annotation for itself" % (self,))
246
247 def ll_hash_void(v):
248 return 0
249
250
251 class CanBeNull(object):
252 """A mix-in base class for subclasses of Repr that represent None as
253 'null' and true values as non-'null'.
254 """
255 def rtype_bool(self, hop):
256 if hop.s_result.is_constant():
257 return hop.inputconst(Bool, hop.s_result.const)
258 else:
259 vlist = hop.inputargs(self)
260 return hop.genop('ptr_nonzero', vlist, resulttype=Bool)
261
262
263 class IteratorRepr(Repr):
264 """Base class of Reprs of any kind of iterator."""
265
266 def rtype_iter(self, hop): # iter(iter(x)) <==> iter(x)
267 v_iter, = hop.inputargs(self)
268 return v_iter
269
270 def rtype_method_next(self, hop):
271 return self.rtype_next(hop)
272
273
274 class __extend__(annmodel.SomeIterator):
275 # NOTE: SomeIterator is for iterators over any container, not just list
276 def rtyper_makerepr(self, rtyper):
277 r_container = rtyper.getrepr(self.s_container)
278 if self.variant and self.variant[0] == "enumerate":
279 from rpython.rtyper.rrange import EnumerateIteratorRepr
280 r_baseiter = r_container.make_iterator_repr()
281 return EnumerateIteratorRepr(r_baseiter, self.variant[1])
282 return r_container.make_iterator_repr(*self.variant)
283
284 def rtyper_makekey(self):
285 return self.__class__, self.s_container.rtyper_makekey(), self.variant
286
287
288 class __extend__(annmodel.SomeImpossibleValue):
289 def rtyper_makerepr(self, rtyper):
290 return impossible_repr
291
292 def rtyper_makekey(self):
293 return self.__class__,
294
295 # ____ generic binary operations _____________________________
296
297
298 class __extend__(pairtype(Repr, Repr)):
299
300 def rtype_is_((robj1, robj2), hop):
301 if hop.s_result.is_constant():
302 return inputconst(Bool, hop.s_result.const)
303 roriginal1 = robj1
304 roriginal2 = robj2
305 if robj1.lowleveltype is Void:
306 robj1 = robj2
307 elif robj2.lowleveltype is Void:
308 robj2 = robj1
309 if (not isinstance(robj1.lowleveltype, Ptr) or
310 not isinstance(robj2.lowleveltype, Ptr)):
311 raise TyperError('is of instances of the non-pointers: %r, %r' % (
312 roriginal1, roriginal2))
313 if robj1.lowleveltype != robj2.lowleveltype:
314 raise TyperError('is of instances of different pointer types: %r, %r' % (
315 roriginal1, roriginal2))
316
317 v_list = hop.inputargs(robj1, robj2)
318 return hop.genop('ptr_eq', v_list, resulttype=Bool)
319
320
321 # default implementation for checked getitems
322
323 def rtype_getitem_idx((r_c1, r_o1), hop):
324 return pair(r_c1, r_o1).rtype_getitem(hop)
325
326
327 # ____________________________________________________________
328
329
330 def make_missing_op(rcls, opname):
331 attr = 'rtype_' + opname
332 if not hasattr(rcls, attr):
333 def missing_rtype_operation(self, hop):
334 raise MissingRTypeOperation("unimplemented operation: "
335 "'%s' on %r" % (opname, self))
336 setattr(rcls, attr, missing_rtype_operation)
337
338 for opname in unaryop.UNARY_OPERATIONS:
339 make_missing_op(Repr, opname)
340
341 for opname in binaryop.BINARY_OPERATIONS:
342 make_missing_op(pairtype(Repr, Repr), opname)
343
344 # not in BINARY_OPERATIONS
345 make_missing_op(pairtype(Repr, Repr), 'contains')
346
347 class __extend__(pairtype(Repr, Repr)):
348 def convert_from_to((r_from, r_to), v, llops):
349 return NotImplemented
350
351 # ____________________________________________________________
352
353 class VoidRepr(Repr):
354 lowleveltype = Void
355 def get_ll_eq_function(self): return None
356 def get_ll_hash_function(self): return ll_hash_void
357 get_ll_fasthash_function = get_ll_hash_function
358 def ll_str(self, nothing): raise AssertionError("unreachable code")
359 impossible_repr = VoidRepr()
360
361 class __extend__(pairtype(Repr, VoidRepr)):
362 def convert_from_to((r_from, r_to), v, llops):
363 return inputconst(lltype.Void, None)
364
365 class SimplePointerRepr(Repr):
366 "Convenience Repr for simple ll pointer types with no operation on them."
367
368 def __init__(self, lowleveltype):
369 self.lowleveltype = lowleveltype
370
371 def convert_const(self, value):
372 if value is not None:
373 raise TyperError("%r only supports None as prebuilt constant, "
374 "got %r" % (self, value))
375 return lltype.nullptr(self.lowleveltype.TO)
376
377 # ____________________________________________________________
378
379 def inputconst(reqtype, value):
380 """Return a Constant with the given value, of the requested type,
381 which can be a Repr instance or a low-level type.
382 """
383 if isinstance(reqtype, Repr):
384 value = reqtype.convert_const(value)
385 lltype = reqtype.lowleveltype
386 elif isinstance(reqtype, LowLevelType):
387 lltype = reqtype
388 else:
389 raise TypeError(repr(reqtype))
390 if not lltype._contains_value(value):
391 raise TyperError("inputconst(): expected a %r, got %r" %
392 (lltype, value))
393 c = Constant(value)
394 c.concretetype = lltype
395 return c
396
397 class BrokenReprTyperError(TyperError):
398 """ raised when trying to setup a Repr whose setup
399 has failed already.
400 """
401
402 def mangle(prefix, name):
403 """Make a unique identifier from the prefix and the name. The name
404 is allowed to start with $."""
405 if name.startswith('$'):
406 return '%sinternal_%s' % (prefix, name[1:])
407 else:
408 return '%s_%s' % (prefix, name)
409
410 # __________ utilities __________
411
412 def getgcflavor(classdef):
413 classdesc = classdef.classdesc
414 alloc_flavor = classdesc.get_param('_alloc_flavor_', default='gc')
415 return alloc_flavor
416
417 def externalvsinternal(rtyper, item_repr, gcref=False): # -> external_item_repr, (internal_)item_repr
418 from rpython.rtyper import rclass
419 from rpython.rtyper.lltypesystem import rgcref
420 if rtyper is None or rtyper.annotator.translator.config.translation.gc == "ref":
421 gcref = False # refcounting GC cannot deal with gcrefs
422 if (gcref and isinstance(item_repr.lowleveltype, Ptr) and
423 item_repr.lowleveltype.TO._gckind == 'gc'):
424 return item_repr, rgcref.GCRefRepr.make(item_repr, rtyper.gcrefreprcache)
425 if (isinstance(item_repr, rclass.InstanceRepr) and
426 getattr(item_repr, 'gcflavor', 'gc') == 'gc'):
427 return item_repr, rclass.getinstancerepr(rtyper, None)
428 else:
429 return item_repr, item_repr
430
431
432 class DummyValueBuilder(object):
433
434 def __init__(self, rtyper, TYPE):
435 self.rtyper = rtyper
436 self.TYPE = TYPE
437
438 def _freeze_(self):
439 return True
440
441 def __hash__(self):
442 return hash(self.TYPE)
443
444 def __eq__(self, other):
445 return (isinstance(other, DummyValueBuilder) and
446 self.rtyper is other.rtyper and
447 self.TYPE == other.TYPE)
448
449 def __ne__(self, other):
450 return not (self == other)
451
452 @property
453 def ll_dummy_value(self):
454 TYPE = self.TYPE
455 try:
456 return self.rtyper.cache_dummy_values[TYPE]
457 except KeyError:
458 # generate a dummy ptr to an immortal placeholder struct/array
459 if TYPE._is_varsize():
460 p = lltype.malloc(TYPE, 1, immortal=True)
461 else:
462 p = lltype.malloc(TYPE, immortal=True)
463 self.rtyper.cache_dummy_values[TYPE] = p
464 return p
465
466
467 # logging/warning
468
469 from rpython.tool.ansi_print import AnsiLogger
470
471 log = AnsiLogger("rtyper")
472
473 def warning(msg):
474 log.WARNING(msg)