Debian Codegraph @

rpython/rlib/objectmodel.py

raw symbols SCIP
1 """
2 This file defines utilities for manipulating objects in an
3 RPython-compliant way.
4 """
5
6 from __future__ import absolute_import
7
8 import sys
9 import types
10 import math
11 import inspect
12 from collections import OrderedDict
13
14 from rpython.tool.sourcetools import rpython_wrapper, func_with_new_name
15 from rpython.rtyper.extregistry import ExtRegistryEntry
16 from rpython.flowspace.specialcase import register_flow_sc
17 from rpython.flowspace.model import Constant
18
19 # specialize is a decorator factory for attaching _annspecialcase_
20 # attributes to functions: for example
21 #
22 # f._annspecialcase_ = 'specialize:memo' can be expressed with:
23 # @specialize.memo()
24 # def f(...
25 #
26 # f._annspecialcase_ = 'specialize:arg(0)' can be expressed with:
27 # @specialize.arg(0)
28 # def f(...
29 #
30
31
32 class _Specialize(object):
33 def memo(self):
34 """ Specialize the function based on argument values. All arguments
35 have to be either constants or PBCs (i.e. instances of classes with a
36 _freeze_ method returning True). The function call is replaced by
37 just its result, or in case several PBCs are used, by some fast
38 look-up of the result.
39 """
40 def decorated_func(func):
41 func._annspecialcase_ = 'specialize:memo'
42 return func
43 return decorated_func
44
45 def arg(self, *args):
46 """ Specialize the function based on the values of given positions
47 of arguments. They must be compile-time constants in order to work.
48
49 There will be a copy of provided function for each combination
50 of given arguments on positions in args (that can lead to
51 exponential behavior!).
52 """
53 def decorated_func(func):
54 func._annspecialcase_ = 'specialize:arg' + self._wrap(args)
55 return func
56
57 return decorated_func
58
59 def arg_or_var(self, *args):
60 """ Same as arg, but additionally allow for a 'variable' annotation,
61 that would simply be a situation where designated arg is not
62 a constant
63 """
64 def decorated_func(func):
65 func._annspecialcase_ = 'specialize:arg_or_var' + self._wrap(args)
66 return func
67
68 return decorated_func
69
70 def argtype(self, *args):
71 """ Specialize function based on types of arguments on given positions.
72
73 There will be a copy of provided function for each combination
74 of given arguments on positions in args (that can lead to
75 exponential behavior!).
76 """
77 def decorated_func(func):
78 func._annspecialcase_ = 'specialize:argtype' + self._wrap(args)
79 return func
80
81 return decorated_func
82
83 def ll(self):
84 """ This is version of argtypes that cares about low-level types
85 (so it'll get additional copies for two different types of pointers
86 for example). Same warnings about exponential behavior apply.
87 """
88 def decorated_func(func):
89 func._annspecialcase_ = 'specialize:ll'
90 return func
91
92 return decorated_func
93
94 def ll_and_arg(self, *args):
95 """ This is like ll(), and additionally like arg(...).
96 """
97 def decorated_func(func):
98 func._annspecialcase_ = 'specialize:ll_and_arg' + self._wrap(args)
99 return func
100
101 return decorated_func
102
103 def call_location(self):
104 """ Specializes the function for each call site.
105 """
106 def decorated_func(func):
107 func._annspecialcase_ = "specialize:call_location"
108 return func
109
110 return decorated_func
111
112 def _wrap(self, args):
113 return "("+','.join([repr(arg) for arg in args]) +")"
114
115 specialize = _Specialize()
116
117 NOT_CONSTANT = object() # to use in enforceargs()
118
119 def enforceargs(*types_, **kwds):
120 """ Decorate a function with forcing of RPython-level types on arguments.
121 None means no enforcing.
122
123 When not translated, the type of the actual arguments is checked against
124 the enforced types every time the function is called. You can disable the
125 typechecking by passing ``typecheck=False`` to @enforceargs.
126 """
127 typecheck = kwds.pop('typecheck', True)
128 if types_ and kwds:
129 raise TypeError('Cannot mix positional arguments and keywords')
130
131 if not typecheck:
132 def decorator(f):
133 f._annenforceargs_ = types_
134 return f
135 return decorator
136 #
137 def decorator(f):
138 def get_annotation(t):
139 from rpython.annotator.signature import annotation
140 from rpython.annotator.model import SomeObject
141 if isinstance(t, SomeObject):
142 return t
143 return annotation(t)
144
145 def get_type_descr_of_argument(arg):
146 # we don't want to check *all* the items in list/dict: we assume
147 # they are already homogeneous, so we only check the first
148 # item. The case of empty list/dict is handled inside typecheck()
149 if isinstance(arg, list):
150 return [get_type_descr_of_argument(arg[0])]
151 elif isinstance(arg, dict):
152 key, value = next(arg.iteritems())
153 return {get_type_descr_of_argument(key): get_type_descr_of_argument(value)}
154 else:
155 return type(arg)
156
157 def typecheck(*args):
158 from rpython.annotator.model import SomeList, SomeDict, SomeChar,\
159 SomeInteger
160 for i, (s_expected, arg) in enumerate(zip(s_types, args)):
161 if s_expected is None:
162 continue
163 # special case: if we expect a list or dict and the argument
164 # is an empty list/dict, the typecheck always pass
165 if isinstance(s_expected, SomeList) and arg == []:
166 continue
167 if isinstance(s_expected, SomeDict) and arg == {}:
168 continue
169 if isinstance(s_expected, SomeChar) and (
170 isinstance(arg, str) and len(arg) == 1): # a char
171 continue
172 if (isinstance(s_expected, SomeInteger) and
173 isinstance(arg, s_expected.knowntype)):
174 continue
175 #
176 s_argtype = get_annotation(get_type_descr_of_argument(arg))
177 if not s_expected.contains(s_argtype):
178 msg = "%s argument %r must be of type %s" % (
179 f.__name__, srcargs[i], types[i])
180 raise TypeError(msg)
181 #
182 template = """
183 def {name}({arglist}):
184 if not we_are_translated():
185 typecheck({arglist}) # rpython.rlib.objectmodel
186 return {original}({arglist})
187 """
188 result = rpython_wrapper(f, template,
189 typecheck=typecheck,
190 we_are_translated=we_are_translated)
191 #
192 srcargs, srcvarargs, srckeywords, defaults = inspect.getargspec(f)
193 if kwds:
194 types = tuple([kwds.get(arg) for arg in srcargs])
195 else:
196 types = types_
197 assert len(srcargs) == len(types), (
198 'not enough types provided: expected %d, got %d' %
199 (len(types), len(srcargs)))
200
201 s_types = [None if typ is None else
202 NOT_CONSTANT if typ is NOT_CONSTANT else
203 get_annotation(typ) for typ in types]
204 result._annenforceargs_ = types
205 return result
206 return decorator
207
208 def always_inline(func):
209 """ mark the function as to-be-inlined by the RPython optimizations (not
210 the JIT!), no matter its size."""
211 func._always_inline_ = True
212 return func
213
214 def dont_inline(func):
215 """ mark the function as never-to-be-inlined by the RPython optimizations
216 (not the JIT!), no matter its size."""
217 func._dont_inline_ = True
218 return func
219
220 def try_inline(func):
221 """ tell the RPython inline (not the JIT!), to try to inline this function,
222 no matter its size."""
223 func._always_inline_ = 'try'
224 return func
225
226 def not_rpython(func):
227 """ mark a function as not rpython. the translation process will raise an
228 error if it encounters the function. """
229 # test is in annotator/test/test_annrpython.py
230 func._not_rpython_ = True
231 return func
232
233 def llhelper_error_value(error_value):
234 """
235 This decorator has two effects:
236
237 1. declare that this llhelper can raise RPython exceptions, which should
238 be correctly propagated
239
240 2. specify the error_value to return in case of exception.
241 """
242 # relevant tests:
243 # - test_ll2ctypes.test_llhelper_error_value
244 # - test_exceptiontransform.test_custom_error_value
245 def decorate(func):
246 func._llhelper_error_value_ = error_value
247 return func
248 return decorate
249
250 # ____________________________________________________________
251
252 class Symbolic(object):
253
254 def annotation(self):
255 return None
256
257 def lltype(self):
258 return None
259
260 def __cmp__(self, other):
261 if self is other:
262 return 0
263 else:
264 raise TypeError("Symbolics cannot be compared! (%r, %r)"
265 % (self, other))
266
267 def __hash__(self):
268 raise TypeError("Symbolics are not hashable! %r" % (self,))
269
270 def __nonzero__(self):
271 raise TypeError("Symbolics are not comparable! %r" % (self,))
272
273 class ComputedIntSymbolic(Symbolic):
274
275 def __init__(self, compute_fn):
276 self.compute_fn = compute_fn
277
278 def __repr__(self):
279 # repr(self.compute_fn) can arrive back here in an
280 # infinite recursion
281 try:
282 name = self.compute_fn.__name__
283 except (AttributeError, TypeError):
284 name = hex(id(self.compute_fn))
285 return '%s(%r)' % (self.__class__.__name__, name)
286
287 def annotation(self):
288 from rpython.annotator import model
289 return model.SomeInteger()
290
291 def lltype(self):
292 from rpython.rtyper.lltypesystem import lltype
293 return lltype.Signed
294
295 class CDefinedIntSymbolic(Symbolic):
296
297 def __init__(self, expr, default=0):
298 self.expr = expr
299 self.default = default
300
301 def __repr__(self):
302 return '%s(%r)' % (self.__class__.__name__, self.expr)
303
304 def annotation(self):
305 from rpython.annotator import model
306 return model.SomeInteger()
307
308 def lltype(self):
309 from rpython.rtyper.lltypesystem import lltype
310 return lltype.Signed
311
312 malloc_zero_filled = CDefinedIntSymbolic('MALLOC_ZERO_FILLED', default=0)
313 _translated_to_c = CDefinedIntSymbolic('1 /*_translated_to_c*/', default=0)
314
315 def we_are_translated_to_c():
316 return we_are_translated() and _translated_to_c
317
318 # ____________________________________________________________
319
320 def instantiate(cls, nonmovable=False):
321 "Create an empty instance of 'cls'."
322 if isinstance(cls, type):
323 return cls.__new__(cls)
324 else:
325 return types.InstanceType(cls)
326
327 def we_are_translated():
328 return False
329
330 @register_flow_sc(we_are_translated)
331 def sc_we_are_translated(ctx):
332 return Constant(True)
333
334 def register_replacement_for(replaced_function, sandboxed_name=None):
335 def wrap(func):
336 from rpython.rtyper.extregistry import ExtRegistryEntry
337 # to support calling func directly
338 func._sandbox_external_name = sandboxed_name
339 class ExtRegistry(ExtRegistryEntry):
340 _about_ = replaced_function
341 def compute_annotation(self):
342 if sandboxed_name:
343 config = self.bookkeeper.annotator.translator.config
344 if config.translation.sandbox:
345 func._sandbox_external_name = sandboxed_name
346 func._dont_inline_ = True
347 return self.bookkeeper.immutablevalue(func)
348 return func
349 return wrap
350
351 def keepalive_until_here(*values):
352 pass
353
354 def is_annotation_constant(thing):
355 """ Returns whether the annotator can prove that the argument is constant.
356 For advanced usage only."""
357 return True
358
359 class Entry(ExtRegistryEntry):
360 _about_ = is_annotation_constant
361
362 def compute_result_annotation(self, s_arg):
363 from rpython.annotator import model
364 r = model.SomeBool()
365 r.const = s_arg.is_constant()
366 return r
367
368 def specialize_call(self, hop):
369 from rpython.rtyper.lltypesystem import lltype
370 hop.exception_cannot_occur()
371 return hop.inputconst(lltype.Bool, hop.s_result.const)
372
373 def int_to_bytearray(i):
374 # XXX this can be made more efficient in the future
375 return bytearray(str(i))
376
377 def fetch_translated_config():
378 """Returns the config that is current when translating.
379 Returns None if not translated.
380 """
381 return None
382
383 class Entry(ExtRegistryEntry):
384 _about_ = fetch_translated_config
385
386 def compute_result_annotation(self):
387 config = self.bookkeeper.annotator.translator.config
388 return self.bookkeeper.immutablevalue(config)
389
390 def specialize_call(self, hop):
391 from rpython.rtyper.lltypesystem import lltype
392 translator = hop.rtyper.annotator.translator
393 hop.exception_cannot_occur()
394 return hop.inputconst(lltype.Void, translator.config)
395
396
397 def revdb_flag_io_disabled():
398 if not revdb_enabled():
399 return False
400 return _revdb_flag_io_disabled()
401
402 def _revdb_flag_io_disabled():
403 # moved in its own function for the import statement
404 from rpython.rlib import revdb
405 return revdb.flag_io_disabled()
406
407 @not_rpython
408 def revdb_enabled():
409 return False
410
411 class Entry(ExtRegistryEntry):
412 _about_ = revdb_enabled
413
414 def compute_result_annotation(self):
415 from rpython.annotator import model as annmodel
416 config = self.bookkeeper.annotator.translator.config
417 if config.translation.reverse_debugger:
418 return annmodel.s_True
419 else:
420 return annmodel.s_False
421
422 def specialize_call(self, hop):
423 from rpython.rtyper.lltypesystem import lltype
424 hop.exception_cannot_occur()
425 return hop.inputconst(lltype.Bool, hop.s_result.const)
426
427 # ____________________________________________________________
428
429 class FREED_OBJECT(object):
430 def __getattribute__(self, attr):
431 raise RuntimeError("trying to access freed object")
432 def __setattr__(self, attr, value):
433 raise RuntimeError("trying to access freed object")
434
435
436 def free_non_gc_object(obj):
437 assert not getattr(obj.__class__, "_alloc_flavor_", 'gc').startswith('gc'), "trying to free gc object"
438 obj.__dict__ = {}
439 obj.__class__ = FREED_OBJECT
440
441 # ____________________________________________________________
442
443 def newlist_hint(sizehint=0):
444 """ Create a new list, but pass a hint how big the size should be
445 preallocated
446 """
447 return []
448
449 class Entry(ExtRegistryEntry):
450 _about_ = newlist_hint
451
452 def compute_result_annotation(self, s_sizehint):
453 from rpython.annotator.model import SomeInteger, AnnotatorError
454
455 if not isinstance(s_sizehint, SomeInteger):
456 raise AnnotatorError("newlist_hint() argument must be an int")
457 s_l = self.bookkeeper.newlist()
458 s_l.listdef.listitem.resize()
459 return s_l
460
461 def specialize_call(self, orig_hop, i_sizehint=None):
462 from rpython.rtyper.rlist import rtype_newlist
463 # fish a bit hop
464 hop = orig_hop.copy()
465 v = hop.args_v[0]
466 r, s = hop.r_s_popfirstarg()
467 if s.is_constant():
468 v = hop.inputconst(r, s.const)
469 hop.exception_is_here()
470 return rtype_newlist(hop, v_sizehint=v)
471
472 def resizelist_hint(l, sizehint):
473 """Reallocate the underlying list to the specified sizehint"""
474 return
475
476 class Entry(ExtRegistryEntry):
477 _about_ = resizelist_hint
478
479 def compute_result_annotation(self, s_l, s_sizehint):
480 from rpython.annotator import model as annmodel
481 if annmodel.s_None.contains(s_l):
482 return # first argument is only None so far, but we
483 # expect a generalization later
484 if not isinstance(s_l, annmodel.SomeList):
485 raise annmodel.AnnotatorError("First argument must be a list")
486 if not isinstance(s_sizehint, annmodel.SomeInteger):
487 raise annmodel.AnnotatorError("Second argument must be an integer")
488 s_l.listdef.listitem.resize()
489
490 def specialize_call(self, hop):
491 r_list = hop.args_r[0]
492 v_list, v_sizehint = hop.inputargs(*hop.args_r)
493 hop.exception_is_here()
494 hop.gendirectcall(r_list.LIST._ll_resize_hint, v_list, v_sizehint)
495
496 def list_get_physical_size(l):
497 """ try to get the physical size of an overallocated RPython list. will
498 return the regular length untranslated. """
499 return len(l)
500
501 def ll_physical_size(l):
502 return len(l.items)
503
504 class Entry(ExtRegistryEntry):
505 _about_ = list_get_physical_size
506
507 def compute_result_annotation(self, s_l):
508 from rpython.annotator import model as annmodel
509 if annmodel.s_None.contains(s_l):
510 pass # first argument is only None so far, but we
511 # expect a generalization later
512 elif not isinstance(s_l, annmodel.SomeList):
513 raise annmodel.AnnotatorError("First argument must be a list")
514 return annmodel.SomeInteger(nonneg=True)
515
516 def specialize_call(self, hop):
517 from rpython.rtyper.lltypesystem.rlist import FixedSizeListRepr, ListRepr
518 v_list, = hop.inputargs(*hop.args_r)
519 if isinstance(hop.args_r[0], ListRepr):
520 ll_func = ll_physical_size
521 else:
522 ll_func = v_list.concretetype.TO.ll_length
523 hop.exception_cannot_occur()
524 return hop.gendirectcall(ll_func, v_list)
525
526
527 # ____________________________________________________________
528 #
529 # id-like functions. The idea is that calling hash() or id() is not
530 # allowed in RPython. You have to call one of the following more
531 # precise functions.
532
533 def compute_hash(x):
534 """RPython equivalent of hash(x), where 'x' is an immutable
535 RPython-level. For strings or unicodes it computes the hash as
536 in Python. For tuples it calls compute_hash() recursively.
537 For instances it uses compute_identity_hash().
538
539 Note that this can return 0 or -1 too.
540
541 NOTE: It returns a different number before and after translation!
542 Dictionaries will be rehashed when the translated program starts.
543 Be careful about other places that store or depend on a hash value:
544 if such a place can exist before translation, you should add for
545 example a _cleanup_() method to clear this cache during translation.
546
547 (Nowadays we could completely remove compute_hash() and decide that
548 hash(x) is valid RPython instead, at least for the types listed here.)
549 """
550 if isinstance(x, (str, unicode)):
551 return _hash_string(x)
552 if isinstance(x, int):
553 return x
554 if isinstance(x, float):
555 return _hash_float(x)
556 if isinstance(x, tuple):
557 return _hash_tuple(x)
558 if x is None:
559 return 0
560 return compute_identity_hash(x)
561
562 def compute_identity_hash(x):
563 """RPython equivalent of object.__hash__(x). This returns the
564 so-called 'identity hash', which is the non-overridable default hash
565 of Python. Can be called for any RPython-level object that turns
566 into a GC object, but not NULL. The value will be different before
567 and after translation (WARNING: this is a change with older RPythons!)
568 """
569 assert x is not None
570 return object.__hash__(x)
571
572 def compute_unique_id(x):
573 """RPython equivalent of id(x). The 'x' must be an RPython-level
574 object that turns into a GC object. This operation can be very
575 costly depending on the garbage collector. To remind you of this
576 fact, we don't support id(x) directly.
577 """
578 # The assumption with RPython is that a regular integer is wide enough
579 # to store a pointer. The following intmask() should not loose any
580 # information.
581 from rpython.rlib.rarithmetic import intmask
582 return intmask(id(x))
583
584 def current_object_addr_as_int(x):
585 """A cheap version of id(x).
586
587 The current memory location of an object can change over time for moving
588 GCs.
589 """
590 from rpython.rlib.rarithmetic import intmask
591 return intmask(id(x))
592
593 # ----------
594
595 @specialize.ll()
596 def _hash_string(s):
597 """The default algorithm behind compute_hash() for a string or a unicode.
598 This is a modified Fowler-Noll-Vo (FNV) hash. According to Wikipedia,
599 FNV needs carefully-computed constants called FNV primes and FNV offset
600 basis, which are absent from the present algorithm. Nevertheless,
601 this matches CPython 2.7 without -R, which has proven a good hash in
602 practice (even if not crypographical nor randomizable).
603
604 There is a mechanism to use another one in programs after translation.
605 See rsiphash.py, which implements the algorithm of CPython >= 3.4.
606 """
607 from rpython.rlib.rarithmetic import intmask
608
609 length = len(s)
610 if length == 0:
611 return -1
612 x = ord(s[0]) << 7
613 i = 0
614 while i < length:
615 x = intmask((1000003*x) ^ ord(s[i]))
616 i += 1
617 x ^= length
618 return intmask(x)
619
620 def ll_hash_string(ll_s):
621 return _hash_string(ll_s.chars)
622
623 def _hash_float(f):
624 """The algorithm behind compute_hash() for a float.
625 This implementation is identical to the CPython implementation,
626 except the fact that the integer case is not treated specially.
627 In RPython, floats cannot be used with ints in dicts, anyway.
628 """
629 from rpython.rlib.rarithmetic import intmask
630 from rpython.rlib.rfloat import isfinite
631 if not isfinite(f):
632 if math.isinf(f):
633 if f < 0.0:
634 return -271828
635 else:
636 return 314159
637 else: #isnan(f):
638 return 0
639 v, expo = math.frexp(f)
640 v *= TAKE_NEXT
641 hipart = int(v)
642 v = (v - float(hipart)) * TAKE_NEXT
643 x = hipart + int(v) + (expo << 15)
644 return intmask(x)
645 TAKE_NEXT = float(2**31)
646
647 @not_rpython
648 def _hash_tuple(t):
649 """The algorithm behind compute_hash() for a tuple.
650 It is modelled after the old algorithm of Python 2.3, which is
651 a bit faster than the one introduced by Python 2.4. We assume
652 that nested tuples are very uncommon in RPython, making the bad
653 case unlikely.
654 """
655 from rpython.rlib.rarithmetic import intmask
656 x = 0x345678
657 for item in t:
658 y = compute_hash(item)
659 x = intmask((1000003 * x) ^ y)
660 return x
661
662 # ----------
663
664 class Entry(ExtRegistryEntry):
665 _about_ = compute_hash
666
667 def compute_result_annotation(self, s_x):
668 from rpython.annotator import model as annmodel
669 return annmodel.SomeInteger()
670
671 def specialize_call(self, hop):
672 r_obj, = hop.args_r
673 v_obj, = hop.inputargs(r_obj)
674 ll_fn = r_obj.get_ll_hash_function()
675 hop.exception_is_here()
676 return hop.gendirectcall(ll_fn, v_obj)
677
678 class Entry(ExtRegistryEntry):
679 _about_ = ll_hash_string
680 # this is only used when annotating the code in rstr.py, and so
681 # it always occurs after the RPython program signalled its intent
682 # to use a different hash. The code below overwrites the use of
683 # ll_hash_string() to make the annotator think a possibly different
684 # function was called.
685
686 def compute_annotation(self):
687 from rpython.annotator import model as annmodel
688 bk = self.bookkeeper
689 translator = bk.annotator.translator
690 fn = getattr(translator, 'll_hash_string', ll_hash_string)
691 return annmodel.SomePBC([bk.getdesc(fn)])
692
693 class Entry(ExtRegistryEntry):
694 _about_ = compute_identity_hash
695
696 def compute_result_annotation(self, s_x):
697 from rpython.annotator import model as annmodel
698 return annmodel.SomeInteger()
699
700 def specialize_call(self, hop):
701 from rpython.rtyper.lltypesystem import lltype
702 vobj, = hop.inputargs(hop.args_r[0])
703 ok = (isinstance(vobj.concretetype, lltype.Ptr) and
704 vobj.concretetype.TO._gckind == 'gc')
705 if not ok:
706 from rpython.rtyper.error import TyperError
707 raise TyperError("compute_identity_hash() cannot be applied to"
708 " %r" % (vobj.concretetype,))
709 hop.exception_cannot_occur()
710 return hop.genop('gc_identityhash', [vobj], resulttype=lltype.Signed)
711
712 class Entry(ExtRegistryEntry):
713 _about_ = compute_unique_id
714
715 def compute_result_annotation(self, s_x):
716 from rpython.annotator import model as annmodel
717 return annmodel.SomeInteger()
718
719 def specialize_call(self, hop):
720 from rpython.rtyper.lltypesystem import lltype
721 vobj, = hop.inputargs(hop.args_r[0])
722 ok = (isinstance(vobj.concretetype, lltype.Ptr) and
723 vobj.concretetype.TO._gckind == 'gc')
724 if not ok:
725 from rpython.rtyper.error import TyperError
726 raise TyperError("compute_unique_id() cannot be applied to"
727 " %r" % (vobj.concretetype,))
728 hop.exception_cannot_occur()
729 return hop.genop('gc_id', [vobj], resulttype=lltype.Signed)
730
731 class Entry(ExtRegistryEntry):
732 _about_ = current_object_addr_as_int
733
734 def compute_result_annotation(self, s_x):
735 from rpython.annotator import model as annmodel
736 return annmodel.SomeInteger()
737
738 def specialize_call(self, hop):
739 vobj, = hop.inputargs(hop.args_r[0])
740 hop.exception_cannot_occur()
741 from rpython.rtyper.lltypesystem import lltype
742 if isinstance(vobj.concretetype, lltype.Ptr):
743 return hop.genop('cast_ptr_to_int', [vobj],
744 resulttype = lltype.Signed)
745 from rpython.rtyper.error import TyperError
746 raise TyperError("current_object_addr_as_int() cannot be applied to"
747 " %r" % (vobj.concretetype,))
748
749 # ____________________________________________________________
750
751 def hlinvoke(repr, llcallable, *args):
752 raise TypeError("hlinvoke is meant to be rtyped and not called direclty")
753
754
755 class UnboxedValue(object):
756 """A mixin class to use for classes that have exactly one field which
757 is an integer. They are represented as a tagged pointer, if the
758 translation.taggedpointers config option is used."""
759 _mixin_ = True
760
761 def __new__(cls, value):
762 assert '__init__' not in cls.__dict__ # won't be called anyway
763 assert isinstance(cls.__slots__, str) or len(cls.__slots__) == 1
764 return super(UnboxedValue, cls).__new__(cls)
765
766 def __init__(self, value):
767 # this funtion is annotated but not included in the translated program
768 int_as_pointer = value * 2 + 1 # XXX for now
769 if -sys.maxint-1 <= int_as_pointer <= sys.maxint:
770 if isinstance(self.__class__.__slots__, str):
771 setattr(self, self.__class__.__slots__, value)
772 else:
773 setattr(self, self.__class__.__slots__[0], value)
774 else:
775 raise OverflowError("UnboxedValue: argument out of range")
776
777 def __repr__(self):
778 return '<unboxed %d>' % (self.get_untagged_value(),)
779
780 def get_untagged_value(self): # helper, equivalent to reading the custom field
781 if isinstance(self.__class__.__slots__, str):
782 return getattr(self, self.__class__.__slots__)
783 else:
784 return getattr(self, self.__class__.__slots__[0])
785
786 # ____________________________________________________________
787
788 def likely(condition):
789 assert isinstance(condition, bool)
790 return condition
791
792 def unlikely(condition):
793 assert isinstance(condition, bool)
794 return condition
795
796 class Entry(ExtRegistryEntry):
797 _about_ = (likely, unlikely)
798
799 def compute_result_annotation(self, s_x):
800 from rpython.annotator import model as annmodel
801 return annmodel.SomeBool()
802
803 def specialize_call(self, hop):
804 from rpython.rtyper.lltypesystem import lltype
805 vlist = hop.inputargs(lltype.Bool)
806 hop.exception_cannot_occur()
807 return hop.genop(self.instance.__name__, vlist,
808 resulttype=lltype.Bool)
809
810 # ____________________________________________________________
811
812
813 class r_dict(object):
814 """An RPython dict-like object.
815 Only provides the interface supported by RPython.
816 The functions key_eq() and key_hash() are used by the key comparison
817 algorithm."""
818
819 def _newdict(self):
820 return {}
821
822 def __init__(self, key_eq, key_hash, force_non_null=False, simple_hash_eq=False):
823 """ force_non_null=True means that the key can never be None (even if
824 the annotator things it could be)
825
826 simple_hash_eq=True means that the hash function is very fast, meaning it's
827 efficient enough that the dict does not have to store the hash per key.
828 It also implies that neither the hash nor the eq function will mutate
829 the dictionary. """
830 self._dict = self._newdict()
831 self.key_eq = key_eq
832 self.key_hash = key_hash
833 self.force_non_null = force_non_null
834 self.simple_hash_eq = simple_hash_eq
835
836 def __getitem__(self, key):
837 return self._dict[_r_dictkey(self, key)]
838
839 def __setitem__(self, key, value):
840 self._dict[_r_dictkey(self, key)] = value
841
842 def __delitem__(self, key):
843 del self._dict[_r_dictkey(self, key)]
844
845 def __len__(self):
846 return len(self._dict)
847
848 def __iter__(self):
849 for dk in self._dict:
850 yield dk.key
851
852 def __contains__(self, key):
853 return _r_dictkey(self, key) in self._dict
854
855 def get(self, key, default):
856 return self._dict.get(_r_dictkey(self, key), default)
857
858 def setdefault(self, key, default):
859 return self._dict.setdefault(_r_dictkey(self, key), default)
860
861 def pop(self, key, *default):
862 return self._dict.pop(_r_dictkey(self, key), *default)
863
864 def popitem(self):
865 dk, value = self._dict.popitem()
866 return dk.key, value
867
868 def copy(self):
869 result = self.__class__(self.key_eq, self.key_hash)
870 result.update(self)
871 return result
872
873 def update(self, other):
874 for key, value in other.items():
875 self[key] = value
876
877 def keys(self):
878 return [dk.key for dk in self._dict]
879
880 def values(self):
881 return self._dict.values()
882
883 def items(self):
884 return [(dk.key, value) for dk, value in self._dict.items()]
885
886 iterkeys = __iter__
887
888 def itervalues(self):
889 return self._dict.itervalues()
890
891 def iteritems(self):
892 for dk, value in self._dict.items():
893 yield dk.key, value
894
895 def clear(self):
896 self._dict.clear()
897
898 def __repr__(self):
899 "Representation for debugging purposes."
900 return 'r_dict(%r)' % (self._dict,)
901
902 def __hash__(self):
903 raise TypeError("cannot hash r_dict instances")
904
905 class r_ordereddict(r_dict):
906 def _newdict(self):
907 return OrderedDict()
908
909 class _r_dictkey(object):
910 __slots__ = ['dic', 'key', 'hash']
911 def __init__(self, dic, key):
912 self.dic = dic
913 self.key = key
914 self.hash = dic.key_hash(key)
915 def __eq__(self, other):
916 if not isinstance(other, _r_dictkey):
917 return NotImplemented
918 return self.dic.key_eq(self.key, other.key)
919 def __ne__(self, other):
920 if not isinstance(other, _r_dictkey):
921 return NotImplemented
922 return not self.dic.key_eq(self.key, other.key)
923 def __hash__(self):
924 return self.hash
925
926 def __repr__(self):
927 return repr(self.key)
928
929
930 @specialize.call_location()
931 def prepare_dict_update(dict, n_elements):
932 """RPython hint that the given dict (or r_dict) will soon be
933 enlarged by n_elements."""
934 if we_are_translated():
935 dict._prepare_dict_update(n_elements)
936 # ^^ call an extra method that doesn't exist before translation
937
938 @specialize.call_location()
939 def reversed_dict(d):
940 """Equivalent to reversed(ordered_dict), but works also for
941 regular dicts."""
942 # note that there is also __pypy__.reversed_dict(), which we could
943 # try to use here if we're not translated and running on top of pypy,
944 # but that seems a bit pointless
945 if not we_are_translated():
946 d = d.keys()
947 return reversed(d)
948
949 def _expected_hash(d, key):
950 if isinstance(d, r_dict):
951 return d.key_hash(key)
952 else:
953 return compute_hash(key)
954
955 def _iterkeys_with_hash_untranslated(d):
956 for k in d:
957 yield (k, _expected_hash(d, k))
958
959 @specialize.call_location()
960 def iterkeys_with_hash(d):
961 """Iterates (key, hash) pairs without recomputing the hash."""
962 if not we_are_translated():
963 return _iterkeys_with_hash_untranslated(d)
964 return d.iterkeys_with_hash()
965
966 def _iteritems_with_hash_untranslated(d):
967 for k, v in d.iteritems():
968 yield (k, v, _expected_hash(d, k))
969
970 @specialize.call_location()
971 def iteritems_with_hash(d):
972 """Iterates (key, value, keyhash) triples without recomputing the hash."""
973 if not we_are_translated():
974 return _iteritems_with_hash_untranslated(d)
975 return d.iteritems_with_hash()
976
977 @specialize.call_location()
978 def contains_with_hash(d, key, h):
979 """Same as 'key in d'. The extra argument is the hash. Use this only
980 if you got the hash just now from some other ..._with_hash() function."""
981 if not we_are_translated():
982 assert _expected_hash(d, key) == h
983 return key in d
984 return d.contains_with_hash(key, h)
985
986 @specialize.call_location()
987 def setitem_with_hash(d, key, h, value):
988 """Same as 'd[key] = value'. The extra argument is the hash. Use this only
989 if you got the hash just now from some other ..._with_hash() function."""
990 if not we_are_translated():
991 assert _expected_hash(d, key) == h
992 d[key] = value
993 return
994 d.setitem_with_hash(key, h, value)
995
996 @specialize.call_location()
997 def getitem_with_hash(d, key, h):
998 """Same as 'd[key]'. The extra argument is the hash. Use this only
999 if you got the hash just now from some other ..._with_hash() function."""
1000 if not we_are_translated():
1001 assert _expected_hash(d, key) == h
1002 return d[key]
1003 return d.getitem_with_hash(key, h)
1004
1005 @specialize.call_location()
1006 def delitem_with_hash(d, key, h):
1007 """Same as 'del d[key]'. The extra argument is the hash. Use this only
1008 if you got the hash just now from some other ..._with_hash() function."""
1009 if not we_are_translated():
1010 assert _expected_hash(d, key) == h
1011 del d[key]
1012 return
1013 d.delitem_with_hash(key, h)
1014
1015 @specialize.call_location()
1016 def delitem_if_value_is(d, key, value):
1017 """Same as 'if d.get(key) is value: del d[key]'. It is safe even in
1018 case 'd' is an r_dict and the lookup involves callbacks that might
1019 release the GIL."""
1020 if not we_are_translated():
1021 try:
1022 if d[key] is value:
1023 del d[key]
1024 except KeyError:
1025 pass
1026 return
1027 d.delitem_if_value_is(key, value)
1028
1029 def _untranslated_move_to_end(d, key, last):
1030 "NOT_RPYTHON"
1031 value = d.pop(key)
1032 if last:
1033 d[key] = value
1034 else:
1035 items = d.items()
1036 d.clear()
1037 d[key] = value
1038 # r_dict.update does not support list of tuples, do it manually
1039 for key, value in items:
1040 d[key] = value
1041
1042 @specialize.call_location()
1043 def move_to_end(d, key, last=True):
1044 if not we_are_translated():
1045 _untranslated_move_to_end(d, key, last)
1046 return
1047 d.move_to_end(key, last)
1048
1049 NO_DEFAULT = object()
1050
1051 @not_rpython
1052 def dict_to_switch(d, inline=True, default=NO_DEFAULT):
1053 """Convert dictionary with integer or char keys to a switch statement."""
1054 from rpython.rlib.unroll import unrolling_iterable
1055
1056 have_default = default is not NO_DEFAULT
1057
1058 assert len(d) >= 1
1059 firstkey = next(iter(d))
1060 if isinstance(firstkey, int):
1061 precheck = always_inline(lambda key: key)
1062 for key in d:
1063 assert isinstance(key, int)
1064 else:
1065 assert isinstance(firstkey, str) # only int and char allowed for now
1066 assert not have_default
1067 for key in d:
1068 assert isinstance(key, str) and len(key) == 1
1069
1070 @always_inline
1071 def precheck(key):
1072 # make sure it's a char switch
1073 if len(key) > 1:
1074 raise KeyError
1075 return key[0]
1076
1077 cached_size = len(d)
1078 unrolling_iteritems = unrolling_iterable(d.iteritems())
1079
1080 def lookup(query):
1081 if we_are_translated():
1082 query = precheck(query)
1083 for key, value in unrolling_iteritems:
1084 if key == query:
1085 return value
1086 else:
1087 if have_default:
1088 return default
1089 raise KeyError
1090 else:
1091 assert len(d) == cached_size, "dictionary size changed!"
1092 if have_default:
1093 return d.get(query, default)
1094 else:
1095 return d[query]
1096
1097
1098 if inline:
1099 lookup = always_inline(lookup)
1100 return lookup
1101
1102 # ____________________________________________________________
1103
1104 def import_from_mixin(M, special_methods=['__init__', '__del__']):
1105 """Copy all methods and class attributes from the class M into
1106 the current scope. Should be called when defining a class body.
1107 Function and staticmethod objects are duplicated, which means
1108 that annotation will not consider them as identical to another
1109 copy in another unrelated class.
1110
1111 By default, "special" methods and class attributes, with a name
1112 like "__xxx__", are not copied unless they are "__init__" or
1113 "__del__". The list can be changed with the optional second
1114 argument.
1115 """
1116 flatten = {}
1117 caller = sys._getframe(1)
1118 caller_name = caller.f_globals.get('__name__')
1119 immutable_fields = []
1120 for base in inspect.getmro(M):
1121 if base is object:
1122 continue
1123 for key, value in base.__dict__.items():
1124 if key == '_immutable_fields_':
1125 immutable_fields.extend(value)
1126 continue
1127 if key.startswith('__') and key.endswith('__'):
1128 if key not in special_methods:
1129 continue
1130 if key in flatten:
1131 continue
1132 if isinstance(value, types.FunctionType):
1133 value = func_with_new_name(value, value.__name__)
1134 elif isinstance(value, staticmethod):
1135 func = value.__get__(42)
1136 func = func_with_new_name(func, func.__name__)
1137 if caller_name:
1138 # staticmethods lack a unique im_class so further
1139 # distinguish them from themselves
1140 func.__module__ = caller_name
1141 value = staticmethod(func)
1142 elif isinstance(value, classmethod):
1143 raise AssertionError("classmethods not supported "
1144 "in 'import_from_mixin'")
1145 flatten[key] = value
1146 #
1147 target = caller.f_locals
1148 for key, value in flatten.items():
1149 if key in target:
1150 raise Exception("import_from_mixin: would overwrite the value "
1151 "already defined locally for %r" % (key,))
1152 if key == '_mixin_':
1153 raise Exception("import_from_mixin(M): class M should not "
1154 "have '_mixin_ = True'")
1155 target[key] = value
1156 if immutable_fields:
1157 target['_immutable_fields_'] = target.get('_immutable_fields_', []) + immutable_fields
1158
1159 def never_allocate(cls):
1160 """
1161 Class decorator to ensure that a class is NEVER instantiated at runtime.
1162
1163 Useful e.g for context manager which are expected to be constant-folded
1164 away.
1165 """
1166 cls._rpython_never_allocate_ = True
1167 return cls