PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/__pypy__/interp_magic.py

https://bitbucket.org/pypy/pypy/
Python | 190 lines | 172 code | 9 blank | 9 comment | 0 complexity | f9b9322e4afa4d8c6c7e7bd6d9ce2909 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from pypy.interpreter.error import oefmt, wrap_oserror
  2. from pypy.interpreter.gateway import unwrap_spec
  3. from pypy.interpreter.pycode import CodeHookCache
  4. from pypy.interpreter.pyframe import PyFrame
  5. from pypy.interpreter.mixedmodule import MixedModule
  6. from rpython.rlib.objectmodel import we_are_translated
  7. from pypy.objspace.std.dictmultiobject import W_DictMultiObject
  8. from pypy.objspace.std.listobject import W_ListObject
  9. from pypy.objspace.std.setobject import W_BaseSetObject
  10. from pypy.objspace.std.typeobject import MethodCache
  11. from pypy.objspace.std.mapdict import MapAttrCache
  12. from rpython.rlib import rposix, rgc
  13. def internal_repr(space, w_object):
  14. return space.wrap('%r' % (w_object,))
  15. def attach_gdb(space):
  16. """Run an interp-level gdb (or pdb when untranslated)"""
  17. from rpython.rlib.debug import attach_gdb
  18. attach_gdb()
  19. @unwrap_spec(name=str)
  20. def method_cache_counter(space, name):
  21. """Return a tuple (method_cache_hits, method_cache_misses) for calls to
  22. methods with the name."""
  23. assert space.config.objspace.std.withmethodcachecounter
  24. cache = space.fromcache(MethodCache)
  25. return space.newtuple([space.newint(cache.hits.get(name, 0)),
  26. space.newint(cache.misses.get(name, 0))])
  27. def reset_method_cache_counter(space):
  28. """Reset the method cache counter to zero for all method names."""
  29. assert space.config.objspace.std.withmethodcachecounter
  30. cache = space.fromcache(MethodCache)
  31. cache.misses = {}
  32. cache.hits = {}
  33. cache = space.fromcache(MapAttrCache)
  34. cache.misses = {}
  35. cache.hits = {}
  36. @unwrap_spec(name=str)
  37. def mapdict_cache_counter(space, name):
  38. """Return a tuple (index_cache_hits, index_cache_misses) for lookups
  39. in the mapdict cache with the given attribute name."""
  40. assert space.config.objspace.std.withmethodcachecounter
  41. cache = space.fromcache(MapAttrCache)
  42. return space.newtuple([space.newint(cache.hits.get(name, 0)),
  43. space.newint(cache.misses.get(name, 0))])
  44. def builtinify(space, w_func):
  45. """To implement at app-level modules that are, in CPython,
  46. implemented in C: this decorator protects a function from being ever
  47. bound like a method. Useful because some tests do things like put
  48. a "built-in" function on a class and access it via the instance.
  49. """
  50. from pypy.interpreter.function import Function, BuiltinFunction
  51. func = space.interp_w(Function, w_func)
  52. bltn = BuiltinFunction(func)
  53. return space.wrap(bltn)
  54. def hidden_applevel(space, w_func):
  55. """Decorator that hides a function's frame from app-level"""
  56. from pypy.interpreter.function import Function
  57. func = space.interp_w(Function, w_func)
  58. func.getcode().hidden_applevel = True
  59. return w_func
  60. def get_hidden_tb(space):
  61. """Return the traceback of the current exception being handled by a
  62. frame hidden from applevel.
  63. """
  64. operr = space.getexecutioncontext().sys_exc_info(for_hidden=True)
  65. return space.w_None if operr is None else space.wrap(operr.get_traceback())
  66. @unwrap_spec(meth=str)
  67. def lookup_special(space, w_obj, meth):
  68. """Lookup up a special method on an object."""
  69. if space.is_oldstyle_instance(w_obj):
  70. raise oefmt(space.w_TypeError,
  71. "this doesn't do what you want on old-style classes")
  72. w_descr = space.lookup(w_obj, meth)
  73. if w_descr is None:
  74. return space.w_None
  75. return space.get(w_descr, w_obj)
  76. def do_what_I_mean(space):
  77. return space.wrap(42)
  78. def strategy(space, w_obj):
  79. """ strategy(dict or list or set)
  80. Return the underlying strategy currently used by a dict, list or set object
  81. """
  82. if isinstance(w_obj, W_DictMultiObject):
  83. name = w_obj.get_strategy().__class__.__name__
  84. elif isinstance(w_obj, W_ListObject):
  85. name = w_obj.strategy.__class__.__name__
  86. elif isinstance(w_obj, W_BaseSetObject):
  87. name = w_obj.strategy.__class__.__name__
  88. else:
  89. raise oefmt(space.w_TypeError, "expecting dict or list or set object")
  90. return space.wrap(name)
  91. @unwrap_spec(fd='c_int')
  92. def validate_fd(space, fd):
  93. try:
  94. rposix.validate_fd(fd)
  95. except OSError as e:
  96. raise wrap_oserror(space, e)
  97. def get_console_cp(space):
  98. from rpython.rlib import rwin32 # Windows only
  99. return space.newtuple([
  100. space.wrap('cp%d' % rwin32.GetConsoleCP()),
  101. space.wrap('cp%d' % rwin32.GetConsoleOutputCP()),
  102. ])
  103. @unwrap_spec(sizehint=int)
  104. def resizelist_hint(space, w_iterable, sizehint):
  105. if not isinstance(w_iterable, W_ListObject):
  106. raise oefmt(space.w_TypeError, "arg 1 must be a 'list'")
  107. w_iterable._resize_hint(sizehint)
  108. @unwrap_spec(sizehint=int)
  109. def newlist_hint(space, sizehint):
  110. return space.newlist_hint(sizehint)
  111. @unwrap_spec(debug=bool)
  112. def set_debug(space, debug):
  113. space.sys.debug = debug
  114. space.setitem(space.builtin.w_dict,
  115. space.wrap('__debug__'),
  116. space.wrap(debug))
  117. @unwrap_spec(estimate=int)
  118. def add_memory_pressure(estimate):
  119. rgc.add_memory_pressure(estimate)
  120. @unwrap_spec(w_frame=PyFrame)
  121. def locals_to_fast(space, w_frame):
  122. assert isinstance(w_frame, PyFrame)
  123. w_frame.locals2fast()
  124. @unwrap_spec(w_module=MixedModule)
  125. def save_module_content_for_future_reload(space, w_module):
  126. w_module.save_module_content_for_future_reload()
  127. def specialized_zip_2_lists(space, w_list1, w_list2):
  128. from pypy.objspace.std.specialisedtupleobject import specialized_zip_2_lists
  129. return specialized_zip_2_lists(space, w_list1, w_list2)
  130. def set_code_callback(space, w_callable):
  131. cache = space.fromcache(CodeHookCache)
  132. if space.is_none(w_callable):
  133. cache._code_hook = None
  134. else:
  135. cache._code_hook = w_callable
  136. @unwrap_spec(string=str, byteorder=str, signed=int)
  137. def decode_long(space, string, byteorder='little', signed=1):
  138. from rpython.rlib.rbigint import rbigint, InvalidEndiannessError
  139. try:
  140. result = rbigint.frombytes(string, byteorder, bool(signed))
  141. except InvalidEndiannessError:
  142. raise oefmt(space.w_ValueError, "invalid byteorder argument")
  143. return space.newlong_from_rbigint(result)
  144. def _promote(space, w_obj):
  145. """ Promote the first argument of the function and return it. Promote is by
  146. value for ints, floats, strs, unicodes (but not subclasses thereof) and by
  147. reference otherwise. (Unicodes not supported right now.)
  148. This function is experimental!"""
  149. from rpython.rlib import jit
  150. if space.is_w(space.type(w_obj), space.w_int):
  151. jit.promote(space.int_w(w_obj))
  152. elif space.is_w(space.type(w_obj), space.w_float):
  153. jit.promote(space.float_w(w_obj))
  154. elif space.is_w(space.type(w_obj), space.w_str):
  155. jit.promote_string(space.str_w(w_obj))
  156. elif space.is_w(space.type(w_obj), space.w_unicode):
  157. raise oefmt(space.w_TypeError, "promoting unicode unsupported")
  158. else:
  159. jit.promote(w_obj)
  160. return w_obj