| 1 |
from pypy.interpreter.error import OperationError, oefmt, wrap_oserror |
| 2 |
from pypy.interpreter.gateway import WrappedDefault, 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, rstack |
| 13 |
from rpython.rtyper.lltypesystem import rffi |
| 14 |
|
| 15 |
|
| 16 |
def internal_repr(space, w_object): |
| 17 |
return space.newtext('%r' % (w_object,)) |
| 18 |
|
| 19 |
def objects_in_repr(space): |
| 20 |
"""The identitydict of objects currently being repr(). |
| 21 |
|
| 22 |
This object is thread-local and can be used in a __repr__ method |
| 23 |
to avoid recursion. |
| 24 |
""" |
| 25 |
return space.get_objects_in_repr() |
| 26 |
|
| 27 |
|
| 28 |
def attach_gdb(space): |
| 29 |
"""Run an interp-level gdb (or pdb when untranslated)""" |
| 30 |
from rpython.rlib.debug import attach_gdb |
| 31 |
attach_gdb() |
| 32 |
|
| 33 |
|
| 34 |
@unwrap_spec(name='text') |
| 35 |
def method_cache_counter(space, name): |
| 36 |
"""Return a tuple (method_cache_hits, method_cache_misses) for calls to |
| 37 |
methods with the name.""" |
| 38 |
assert space.config.objspace.std.withmethodcachecounter |
| 39 |
cache = space.fromcache(MethodCache) |
| 40 |
return space.newtuple2(space.newint(cache.hits.get(name, 0)), |
| 41 |
space.newint(cache.misses.get(name, 0))) |
| 42 |
|
| 43 |
def reset_method_cache_counter(space): |
| 44 |
"""Reset the method cache counter to zero for all method names.""" |
| 45 |
assert space.config.objspace.std.withmethodcachecounter |
| 46 |
cache = space.fromcache(MethodCache) |
| 47 |
cache.clear() |
| 48 |
cache.misses = {} |
| 49 |
cache.hits = {} |
| 50 |
cache = space.fromcache(MapAttrCache) |
| 51 |
cache.clear() |
| 52 |
cache.misses = {} |
| 53 |
cache.hits = {} |
| 54 |
|
| 55 |
@unwrap_spec(name='text') |
| 56 |
def mapdict_cache_counter(space, name): |
| 57 |
"""Return a tuple (index_cache_hits, index_cache_misses) for lookups |
| 58 |
in the mapdict cache with the given attribute name.""" |
| 59 |
assert space.config.objspace.std.withmethodcachecounter |
| 60 |
cache = space.fromcache(MapAttrCache) |
| 61 |
return space.newtuple2(space.newint(cache.hits.get(name, 0)), |
| 62 |
space.newint(cache.misses.get(name, 0))) |
| 63 |
|
| 64 |
def builtinify(space, w_func): |
| 65 |
"""To implement at app-level modules that are, in CPython, |
| 66 |
implemented in C: this decorator protects a function from being ever |
| 67 |
bound like a method. Useful because some tests do things like put |
| 68 |
a "built-in" function on a class and access it via the instance. |
| 69 |
""" |
| 70 |
from pypy.interpreter.function import Function, BuiltinFunction |
| 71 |
func = space.interp_w(Function, w_func) |
| 72 |
bltn = BuiltinFunction(func) |
| 73 |
return bltn |
| 74 |
|
| 75 |
def hidden_applevel(space, w_func): |
| 76 |
"""Decorator that hides a function's frame from app-level""" |
| 77 |
from pypy.interpreter.function import Function |
| 78 |
func = space.interp_w(Function, w_func) |
| 79 |
func.getcode().hidden_applevel = True |
| 80 |
return w_func |
| 81 |
|
| 82 |
@unwrap_spec(meth='text') |
| 83 |
def lookup_special(space, w_obj, meth): |
| 84 |
"""Lookup up a special method on an object.""" |
| 85 |
w_descr = space.lookup(w_obj, meth) |
| 86 |
if w_descr is None: |
| 87 |
return space.w_None |
| 88 |
return space.get(w_descr, w_obj) |
| 89 |
|
| 90 |
def do_what_I_mean(space): |
| 91 |
"Return 42" |
| 92 |
return space.newint(42) |
| 93 |
|
| 94 |
def _internal_crash(space, w_crash=None): |
| 95 |
"""for testing purposes, raise an interpreter-level ValueError. Should turn |
| 96 |
into a SystemError automatically""" |
| 97 |
raise ValueError |
| 98 |
|
| 99 |
def strategy(space, w_obj): |
| 100 |
""" strategy(dict or list or set or instance) |
| 101 |
|
| 102 |
Return the underlying strategy currently used by a dict, list or set object |
| 103 |
""" |
| 104 |
if isinstance(w_obj, W_DictMultiObject): |
| 105 |
name = w_obj.get_strategy().__class__.__name__ |
| 106 |
elif isinstance(w_obj, W_ListObject): |
| 107 |
name = w_obj.strategy.__class__.__name__ |
| 108 |
elif isinstance(w_obj, W_BaseSetObject): |
| 109 |
name = w_obj.strategy.__class__.__name__ |
| 110 |
else: |
| 111 |
m = w_obj._get_mapdict_map() |
| 112 |
if m is not None: |
| 113 |
name = m.repr() |
| 114 |
else: |
| 115 |
raise oefmt(space.w_TypeError, "expecting dict or list or set object, or instance of some kind") |
| 116 |
return space.newtext(name) |
| 117 |
|
| 118 |
def list_get_physical_size(space, w_obj): |
| 119 |
if not isinstance(w_obj, W_ListObject): |
| 120 |
raise oefmt(space.w_TypeError, "expected list") |
| 121 |
return space.newint(w_obj.physical_size()) |
| 122 |
|
| 123 |
|
| 124 |
def get_console_cp(space): |
| 125 |
"""get_console_cp() |
| 126 |
|
| 127 |
Return the console and console output code page (windows only) |
| 128 |
""" |
| 129 |
from rpython.rlib import rwin32 |
| 130 |
return space.newtuple2( |
| 131 |
space.newtext('cp%d' % rwin32.GetConsoleCP()), |
| 132 |
space.newtext('cp%d' % rwin32.GetConsoleOutputCP()), |
| 133 |
) |
| 134 |
|
| 135 |
@unwrap_spec(fd=int) |
| 136 |
def get_osfhandle(space, fd): |
| 137 |
"""get_osfhandle() |
| 138 |
|
| 139 |
Return the handle corresponding to the file descriptor (windows only) |
| 140 |
""" |
| 141 |
from rpython.rlib import rwin32 |
| 142 |
try: |
| 143 |
ret = rwin32.get_osfhandle(fd) |
| 144 |
return space.newint(rffi.cast(rffi.INT, ret)) |
| 145 |
except OSError as e: |
| 146 |
raise wrap_oserror(space, e) |
| 147 |
|
| 148 |
@unwrap_spec(sizehint=int) |
| 149 |
def resizelist_hint(space, w_list, sizehint): |
| 150 |
""" Reallocate the underlying storage of the argument list to sizehint """ |
| 151 |
if not isinstance(w_list, W_ListObject): |
| 152 |
raise oefmt(space.w_TypeError, "arg 1 must be a 'list'") |
| 153 |
w_list._resize_hint(sizehint) |
| 154 |
|
| 155 |
@unwrap_spec(sizehint=int) |
| 156 |
def newlist_hint(space, sizehint): |
| 157 |
""" Create a new empty list that has an underlying storage of length sizehint """ |
| 158 |
return space.newlist_hint(sizehint) |
| 159 |
|
| 160 |
@unwrap_spec(estimate=int) |
| 161 |
def add_memory_pressure(space, estimate): |
| 162 |
""" Add memory pressure of estimate bytes. Useful when calling a C function |
| 163 |
that internally allocates a big chunk of memory. This instructs the GC to |
| 164 |
garbage collect sooner than it would otherwise.""" |
| 165 |
rgc.add_memory_pressure(estimate) |
| 166 |
|
| 167 |
@unwrap_spec(w_frame=PyFrame) |
| 168 |
def locals_to_fast(space, w_frame): |
| 169 |
assert isinstance(w_frame, PyFrame) |
| 170 |
w_frame.locals2fast() |
| 171 |
|
| 172 |
def set_code_callback(space, w_callable): |
| 173 |
cache = space.fromcache(CodeHookCache) |
| 174 |
if space.is_none(w_callable): |
| 175 |
cache._code_hook = None |
| 176 |
else: |
| 177 |
cache._code_hook = w_callable |
| 178 |
|
| 179 |
@unwrap_spec(string='bytes', byteorder='text', signed=int) |
| 180 |
def decode_long(space, string, byteorder='little', signed=1): |
| 181 |
from rpython.rlib.rbigint import rbigint, InvalidEndiannessError |
| 182 |
try: |
| 183 |
result = rbigint.frombytes(string, byteorder, bool(signed)) |
| 184 |
except InvalidEndiannessError: |
| 185 |
raise oefmt(space.w_ValueError, "invalid byteorder argument") |
| 186 |
return space.newlong_from_rbigint(result) |
| 187 |
|
| 188 |
def _promote(space, w_obj): |
| 189 |
""" Promote the first argument of the function and return it. Promote is by |
| 190 |
value for ints, floats, strs, unicodes (but not subclasses thereof) and by |
| 191 |
reference otherwise. (Unicodes not supported right now.) |
| 192 |
|
| 193 |
This function is experimental!""" |
| 194 |
from rpython.rlib import jit |
| 195 |
if space.is_w(space.type(w_obj), space.w_int): |
| 196 |
jit.promote(space.int_w(w_obj)) |
| 197 |
elif space.is_w(space.type(w_obj), space.w_float): |
| 198 |
jit.promote(space.float_w(w_obj)) |
| 199 |
elif space.is_w(space.type(w_obj), space.w_bytes): |
| 200 |
jit.promote_string(space.bytes_w(w_obj)) |
| 201 |
elif space.is_w(space.type(w_obj), space.w_unicode): |
| 202 |
raise oefmt(space.w_TypeError, "promoting unicode unsupported") |
| 203 |
else: |
| 204 |
jit.promote(w_obj) |
| 205 |
return w_obj |
| 206 |
|
| 207 |
@unwrap_spec(w_value=WrappedDefault(None), w_tb=WrappedDefault(None)) |
| 208 |
def normalize_exc(space, w_type, w_value=None, w_tb=None): |
| 209 |
operr = OperationError(w_type, w_value, w_tb) |
| 210 |
return operr.normalize_exception(space) |
| 211 |
|
| 212 |
def stack_almost_full(space): |
| 213 |
"""Return True if the stack is more than 15/16th full.""" |
| 214 |
return space.newbool(rstack.stack_almost_full()) |
| 215 |
|
| 216 |
def fsencode(space, w_obj): |
| 217 |
"""Direct access to the interp-level fsencode()""" |
| 218 |
return space.fsencode(w_obj) |
| 219 |
|
| 220 |
def fsdecode(space, w_obj): |
| 221 |
"""Direct access to the interp-level fsdecode()""" |
| 222 |
return space.fsdecode(w_obj) |
| 223 |
|
| 224 |
def side_effects_ok(space): |
| 225 |
"""For use with the reverse-debugger: this function normally returns |
| 226 |
True, but will return False if we are evaluating a debugging command |
| 227 |
like a watchpoint. You are responsible for not doing any side effect |
| 228 |
at all (including no caching) when evaluating watchpoints. This |
| 229 |
function is meant to help a bit---you can write: |
| 230 |
|
| 231 |
if not __pypy__.side_effects_ok(): |
| 232 |
skip the caching logic |
| 233 |
|
| 234 |
inside getter methods or properties, to make them usable from |
| 235 |
watchpoints. Note that you need to re-run ``REVDB=.. pypy'' |
| 236 |
after changing the Python code. |
| 237 |
""" |
| 238 |
return space.newbool(space._side_effects_ok()) |
| 239 |
|
| 240 |
def revdb_stop(space): |
| 241 |
from pypy.interpreter.reverse_debugging import stop_point |
| 242 |
stop_point() |
| 243 |
|
| 244 |
def pyos_inputhook(space): |
| 245 |
"""Call PyOS_InputHook() from the CPython C API.""" |
| 246 |
if not space.config.objspace.usemodules.cpyext: |
| 247 |
return |
| 248 |
w_modules = space.sys.get('modules') |
| 249 |
if space.finditem_str(w_modules, 'cpyext') is None: |
| 250 |
return |
| 251 |
from pypy.module.cpyext.api import invoke_pyos_inputhook |
| 252 |
invoke_pyos_inputhook(space) |
| 253 |
|
| 254 |
def utf8content(space, w_u): |
| 255 |
""" Given a unicode string u, return it's internal byte representation. |
| 256 |
Useful for debugging only. """ |
| 257 |
from pypy.objspace.std.unicodeobject import W_UnicodeObject |
| 258 |
if type(w_u) is not W_UnicodeObject: |
| 259 |
raise oefmt(space.w_TypeError, "expected unicode string, got %T", w_u) |
| 260 |
return space.newbytes(w_u._utf8) |
| 261 |
|
| 262 |
def set_exc_info(space, w_type, w_value, w_traceback=None): |
| 263 |
ec = space.getexecutioncontext() |
| 264 |
ec.set_sys_exc_info3(w_value) |
| 265 |
|
| 266 |
def get_contextvar_context(space): |
| 267 |
ec = space.getexecutioncontext() |
| 268 |
context = ec.contextvar_context |
| 269 |
if context: |
| 270 |
return context |
| 271 |
else: |
| 272 |
return space.w_None |
| 273 |
|
| 274 |
def set_contextvar_context(space, w_obj): |
| 275 |
ec = space.getexecutioncontext() |
| 276 |
ec.contextvar_context = w_obj |
| 277 |
return space.w_None |
| 278 |
|
| 279 |
|
| 280 |
@unwrap_spec(where='text') |
| 281 |
def write_unraisable(space, where, w_exc, w_obj): |
| 282 |
"""write_unraisable(where, exc, obj) |
| 283 |
Equivalent to CPython's _PyErr_WriteUnraisableMsg() |
| 284 |
|
| 285 |
where: msg to write (text) |
| 286 |
exc: error raised |
| 287 |
obj: object to print its repr |
| 288 |
""" |
| 289 |
OperationError(space.type(w_exc), w_exc).write_unraisable( |
| 290 |
space, where, w_obj, with_traceback=True) |
| 291 |
|
| 292 |
def _testing_clear_audithooks(space): |
| 293 |
if we_are_translated(): |
| 294 |
raise oefmt(space.w_RuntimeError, "can only use _testing_clear_audithooks before translation") |
| 295 |
from pypy.module.sys.vm import AuditHolder |
| 296 |
holder = space.fromcache(AuditHolder) |
| 297 |
holder.hook_chain = None |