def setup_class(cls): cls.space = gettestobjspace(**{"objspace.std.withcelldict": True}) cls.w_impl_used = cls.space.appexec([], """(): import __pypy__ def impl_used(obj): assert "ModuleDictImplementation" in __pypy__.internal_repr(obj) return impl_used """) def is_in_cache(space, w_code, w_globals, w_name): name = space.str_w(w_name) cache = get_global_cache(space, w_code, w_globals) index = [space.str_w(w_n) for w_n in w_code.co_names_w].index(name) return space.wrap(cache[index].w_value is not None) is_in_cache = gateway.interp2app(is_in_cache) cls.w_is_in_cache = cls.space.wrap(is_in_cache) stored_builtins = [] def rescue_builtins(space): w_dict = space.builtin.getdict() content = {} for key, cell in w_dict.implementation.content.iteritems(): newcell = ModuleCell() newcell.w_value = cell.w_value content[key] = newcell stored_builtins.append(content) rescue_builtins = gateway.interp2app(rescue_builtins) cls.w_rescue_builtins = cls.space.wrap(rescue_builtins) def restore_builtins(space): w_dict = space.builtin.getdict() if not isinstance(w_dict.implementation, ModuleDictImplementation): w_dict.implementation = ModuleDictImplementation(space) w_dict.implementation.content = stored_builtins.pop() restore_builtins = gateway.interp2app(restore_builtins) cls.w_restore_builtins = cls.space.wrap(restore_builtins)
def _attach_helpers(space): from pypy.interpreter import pytraceback def hide_top_frame(space, w_frame): w_last = None while w_frame.f_backref(): w_last = w_frame w_frame = w_frame.f_backref() assert w_last w_saved = w_last.f_backref() w_last.f_backref = vref_None return w_saved def restore_top_frame(space, w_frame, w_saved): while w_frame.f_backref(): w_frame = w_frame.f_backref() w_frame.f_backref = non_virtual_ref(w_saved) def read_exc_type(space, w_frame): if w_frame.last_exception is None: return space.w_None else: return w_frame.last_exception.w_type from pypy.interpreter import gateway hide_gw = gateway.interp2app(hide_top_frame) space.setitem(space.builtin.w_dict, space.wrap("hide_top_frame"), space.wrap(hide_gw)) restore_gw = gateway.interp2app(restore_top_frame) space.setitem(space.builtin.w_dict, space.wrap("restore_top_frame"), space.wrap(restore_gw)) read_exc_type_gw = gateway.interp2app(read_exc_type) space.setitem(space.builtin.w_dict, space.wrap("read_exc_type"), space.wrap(read_exc_type_gw))
def setup_class(cls): if option.runappdirect: py.test.skip("Can't run this test with -A") space = gettestobjspace(usemodules=('pypyjit',)) cls.space = space w_f = space.appexec([], """(): def f(): pass return f """) ll_code = cast_instance_to_base_ptr(w_f.code) logger = Logger(MockSD()) oplist = parse(""" [i1, i2] i3 = int_add(i1, i2) guard_true(i3) [] """, namespace={'ptr0': 3}).operations def interp_on_compile(): pypyjitdriver.on_compile(logger, LoopToken(), oplist, 'loop', 0, False, ll_code) def interp_on_compile_bridge(): pypyjitdriver.on_compile_bridge(logger, LoopToken(), oplist, 0) cls.w_on_compile = space.wrap(interp2app(interp_on_compile)) cls.w_on_compile_bridge = space.wrap(interp2app(interp_on_compile_bridge))
def test_interp2app_unwrap_spec_c_int(self): from rpython.rlib.rarithmetic import r_longlong space = self.space w = space.wrap def g(space, x): return space.wrap(x + 6) app_g = gateway.interp2app(g, unwrap_spec=[gateway.ObjSpace, "c_int"]) app_ug = gateway.interp2app(g, unwrap_spec=[gateway.ObjSpace, "c_uint"]) app_ng = gateway.interp2app(g, unwrap_spec=[gateway.ObjSpace, "c_nonnegint"]) assert app_ug is not app_g w_app_g = space.wrap(app_g) w_app_ug = space.wrap(app_ug) w_app_ng = space.wrap(app_ng) # assert self.space.eq_w(space.call_function(w_app_g, space.wrap(7)), space.wrap(13)) space.raises_w(space.w_OverflowError, space.call_function, w_app_g, space.wrap(r_longlong(0x80000000))) space.raises_w(space.w_OverflowError, space.call_function, w_app_g, space.wrap(r_longlong(-0x80000001))) # assert self.space.eq_w(space.call_function(w_app_ug, space.wrap(7)), space.wrap(13)) assert self.space.eq_w( space.call_function(w_app_ug, space.wrap(0x7FFFFFFF)), space.wrap(r_longlong(0x7FFFFFFF + 6)) ) space.raises_w(space.w_ValueError, space.call_function, w_app_ug, space.wrap(-1)) space.raises_w(space.w_OverflowError, space.call_function, w_app_ug, space.wrap(r_longlong(0x100000000))) # assert self.space.eq_w(space.call_function(w_app_ng, space.wrap(7)), space.wrap(13)) space.raises_w(space.w_OverflowError, space.call_function, w_app_ng, space.wrap(r_longlong(0x80000000))) space.raises_w(space.w_ValueError, space.call_function, w_app_ng, space.wrap(-1))
def setup_class(cls): cls.w_TEXT = cls.space.wrapbytes(TEXT) cls.DATA = DATA cls.w_DATA = cls.space.wrapbytes(DATA) cls.DATA_CRLF = DATA_CRLF cls.w_DATA_CRLF = cls.space.wrapbytes(DATA_CRLF) cls.temppath = str(py.test.ensuretemp("bz2").join("foo")) cls.w_temppath = cls.space.wrap(cls.temppath) if cls.runappdirect: cls.w_create_temp_file = create_temp_file cls.w_create_broken_temp_file = create_broken_temp_file cls.w_decompress = decompress else: @gateway.unwrap_spec(crlf=bool) def create_temp_file_w(crlf=False): create_temp_file(cls, crlf) cls.w_create_temp_file = cls.space.wrap( gateway.interp2app(create_temp_file_w)) @gateway.unwrap_spec(data=bytes) def decompress_w(space, data): return space.wrapbytes(decompress(cls, data)) cls.w_decompress = cls.space.wrap(gateway.interp2app(decompress_w)) def create_broken_temp_file_w(): create_broken_temp_file(cls) cls.w_create_broken_temp_file = cls.space.wrap( gateway.interp2app(create_broken_temp_file_w)) cls.w_random_data = cls.space.wrapbytes(RANDOM_DATA)
def setup_class(cls): if option.runappdirect: py.test.skip("Can't run this test with -A") space = gettestobjspace(usemodules=('pypyjit',)) cls.space = space w_f = space.appexec([], """(): def function(): pass return function """) cls.w_f = w_f ll_code = cast_instance_to_base_ptr(w_f.code) code_gcref = lltype.cast_opaque_ptr(llmemory.GCREF, ll_code) logger = Logger(MockSD()) oplist = parse(""" [i1, i2, p2] i3 = int_add(i1, i2) debug_merge_point(0, 0, 0, 0, 0, ConstPtr(ptr0)) guard_nonnull(p2) [] guard_true(i3) [] """, namespace={'ptr0': code_gcref}).operations greenkey = [ConstInt(0), ConstInt(0), ConstPtr(code_gcref)] offset = {} for i, op in enumerate(oplist): if i != 1: offset[op] = i di_loop = JitDebugInfo(MockJitDriverSD, logger, JitCellToken(), oplist, 'loop', greenkey) di_loop_optimize = JitDebugInfo(MockJitDriverSD, logger, JitCellToken(), oplist, 'loop', greenkey) di_loop.asminfo = AsmInfo(offset, 0, 0) di_bridge = JitDebugInfo(MockJitDriverSD, logger, JitCellToken(), oplist, 'bridge', fail_descr_no=0) di_bridge.asminfo = AsmInfo(offset, 0, 0) def interp_on_compile(): di_loop.oplist = cls.oplist pypy_hooks.after_compile(di_loop) def interp_on_compile_bridge(): pypy_hooks.after_compile_bridge(di_bridge) def interp_on_optimize(): di_loop_optimize.oplist = cls.oplist pypy_hooks.before_compile(di_loop_optimize) def interp_on_abort(): pypy_hooks.on_abort(ABORT_TOO_LONG, pypyjitdriver, greenkey, 'blah') cls.w_on_compile = space.wrap(interp2app(interp_on_compile)) cls.w_on_compile_bridge = space.wrap(interp2app(interp_on_compile_bridge)) cls.w_on_abort = space.wrap(interp2app(interp_on_abort)) cls.w_int_add_num = space.wrap(rop.INT_ADD) cls.w_dmp_num = space.wrap(rop.DEBUG_MERGE_POINT) cls.w_on_optimize = space.wrap(interp2app(interp_on_optimize)) cls.orig_oplist = oplist
def create_entry_point(space, w_dict): w_entry_point = space.getitem(w_dict, space.wrap('entry_point')) w_run_toplevel = space.getitem(w_dict, space.wrap('run_toplevel')) w_call_finish_gateway = space.wrap(gateway.interp2app(call_finish)) w_call_startup_gateway = space.wrap(gateway.interp2app(call_startup)) w_os = setup_nanos(space) withjit = space.config.objspace.usemodules.pypyjit def entry_point(argv): space.timer.start("Entrypoint") if withjit: from pypy.jit.backend.hlinfo import highleveljitinfo highleveljitinfo.sys_executable = argv[0] #debug("entry point starting") #for arg in argv: # debug(" argv -> " + arg) if len(argv) > 2 and argv[1] == '--heapsize': # Undocumented option, handled at interp-level. # It has silently no effect with some GCs. # It works in Boehm and in the semispace or generational GCs # (but see comments in semispace.py:set_max_heap_size()). # At the moment this option exists mainly to support sandboxing. from pypy.rlib import rgc rgc.set_max_heap_size(int(argv[2])) argv = argv[:1] + argv[3:] try: try: space.timer.start("space.startup") space.call_function(w_run_toplevel, w_call_startup_gateway) space.timer.stop("space.startup") w_executable = space.wrap(argv[0]) w_argv = space.newlist([space.wrap(s) for s in argv[1:]]) space.timer.start("w_entry_point") w_exitcode = space.call_function(w_entry_point, w_executable, w_argv, w_os) space.timer.stop("w_entry_point") exitcode = space.int_w(w_exitcode) # try to pull it all in ## from pypy.interpreter import main, interactive, error ## con = interactive.PyPyConsole(space) ## con.interact() except OperationError, e: debug("OperationError:") debug(" operror-type: " + e.w_type.getname(space)) debug(" operror-value: " + space.str_w(space.str(e.get_w_value(space)))) return 1 finally: try: space.timer.start("space.finish") space.call_function(w_run_toplevel, w_call_finish_gateway) space.timer.stop("space.finish") except OperationError, e: debug("OperationError:") debug(" operror-type: " + e.w_type.getname(space)) debug(" operror-value: " + space.str_w(space.str(e.get_w_value(space)))) return 1 space.timer.stop("Entrypoint") space.timer.dump() return exitcode
def create_builder(name, strtype, builder_cls): class W_Builder(W_Root): def __init__(self, space, size): if size < 0: self.builder = builder_cls() else: self.builder = builder_cls(size) def _check_done(self, space): if self.builder is None: raise OperationError(space.w_ValueError, space.wrap( "Can't operate on a built builder")) @unwrap_spec(size=int) def descr__new__(space, w_subtype, size=-1): return W_Builder(space, size) @unwrap_spec(s=strtype) def descr_append(self, space, s): self._check_done(space) self.builder.append(s) @unwrap_spec(s=strtype, start=int, end=int) def descr_append_slice(self, space, s, start, end): self._check_done(space) if not 0 <= start <= end <= len(s): raise OperationError(space.w_ValueError, space.wrap( "bad start/stop")) self.builder.append_slice(s, start, end) def descr_build(self, space): self._check_done(space) s = self.builder.build() self.builder = None if strtype is str: return space.wrapbytes(s) else: return space.wrap(s) def descr_len(self, space): if self.builder is None: raise OperationError(space.w_ValueError, space.wrap( "no length of built builder")) return space.wrap(self.builder.getlength()) W_Builder.__name__ = "W_%s" % name W_Builder.typedef = TypeDef(name, __new__ = interp2app(func_with_new_name( W_Builder.descr__new__.im_func, '%s_new' % (name,))), append = interp2app(W_Builder.descr_append), append_slice = interp2app(W_Builder.descr_append_slice), build = interp2app(W_Builder.descr_build), __len__ = interp2app(W_Builder.descr_len), ) W_Builder.typedef.acceptable_as_base_class = False return W_Builder
def test_interp2app_unwrap_spec_bool(self): space = self.space w = space.wrap def g(space, b): return space.wrap(b) app_g = gateway.interp2app(g, unwrap_spec=[gateway.ObjSpace, bool]) app_g2 = gateway.interp2app(g, unwrap_spec=[gateway.ObjSpace, bool]) assert app_g is app_g2 w_app_g = space.wrap(app_g) assert self.space.eq_w(space.call_function(w_app_g, space.wrap(True)), space.wrap(True))
def test_caching_methods(self): class Base(gateway.Wrappable): def f(self): return 1 class A(Base): pass class B(Base): pass app_A = gateway.interp2app(A.f) app_B = gateway.interp2app(B.f) assert app_A is not app_B
def test_interp2app_unwrap_spec_nonnegint(self): space = self.space w = space.wrap def g(space, x): return space.wrap(x * 6) app_g = gateway.interp2app(g, unwrap_spec=[gateway.ObjSpace, "nonnegint"]) app_g2 = gateway.interp2app(g, unwrap_spec=[gateway.ObjSpace, "nonnegint"]) assert app_g is app_g2 w_app_g = space.wrap(app_g) assert self.space.eq_w(space.call_function(w_app_g, space.wrap(7)), space.wrap(42)) assert self.space.eq_w(space.call_function(w_app_g, space.wrap(0)), space.wrap(0)) space.raises_w(space.w_ValueError, space.call_function, w_app_g, space.wrap(-1))
def setup_class(cls): cls.w_TEXT = cls.space.wrap(TEXT) cls.w_DATA = cls.space.wrap(DATA) cls.w_DATA_CRLF = cls.space.wrap(DATA_CRLF) cls.w_temppath = cls.space.wrap( str(py.test.ensuretemp("bz2").join("foo"))) if cls.runappdirect: cls.w_create_temp_file = create_temp_file cls.w_create_broken_temp_file = lambda self: create_broken_temp_file() cls.w_decompress = lambda self, *args: decompress(cls.space, *args) else: cls.w_create_temp_file = cls.space.wrap(interp2app(create_temp_file)) cls.w_create_broken_temp_file = cls.space.wrap(interp2app(create_broken_temp_file)) cls.w_decompress = cls.space.wrap(interp2app(decompress)) cls.w_random_data = cls.space.wrap(RANDOM_DATA)
def generic_new_descr(W_Type): def descr_new(space, w_subtype, __args__): self = space.allocate_instance(W_Type, w_subtype) W_Type.__init__(self, space) return space.wrap(self) descr_new = func_with_new_name(descr_new, 'descr_new_%s' % W_Type.__name__) return interp2app(descr_new)
def setup_class(cls): cls.space = gettestobjspace(**{"objspace.std.withstrslice": True}) def not_forced(space, w_s): return space.wrap(isinstance(w_s, W_StringSliceObject) and (w_s.start != 0 or w_s.stop != len(w_s.str))) cls.w_not_forced = cls.space.wrap(gateway.interp2app(not_forced))
def setup_method(self, func): AppTestCpythonExtensionBase.setup_method.im_func(self, func) @unwrap_spec(name=str, init=str, body=str) def create_cdll(space, name, init, body, w_symbols): # the following is loosely from test_cpyext.py import_module; it # is copied here to be able to tweak the call to # compile_extension_module and to get a different return result # than in that function code = """ #include <Python.h> %(body)s PyMODINIT_FUNC init%(name)s(void) { %(init)s } """ % dict(name=name, init=init, body=body) kwds = dict(separate_module_sources=[code]) symbols = [space.str_w(w_item) for w_item in space.fixedview(w_symbols)] mod = compile_extension_module(space, name, symbols, **kwds) # explicitly load the module as a CDLL rather than as a module from pypy.module.imp.importing import get_so_extension fullmodname = os.path.join( os.path.dirname(mod), name + get_so_extension(space)) return space.wrap(fullmodname) self.w_create_cdll = self.space.wrap(interp2app(create_cdll))
def test_format_traceback(self): from pypy.tool.pytest.objspace import maketestobjspace from pypy.interpreter.gateway import interp2app # def format_traceback(space): return space.format_traceback() # space = maketestobjspace() w_format_traceback = space.wrap(interp2app(format_traceback)) w_tb = space.appexec( [w_format_traceback], """(format_traceback): def foo(): return bar() def bar(): return format_traceback() return foo() """, ) tb = space.str_w(w_tb) expected = "\n".join( [ ' File "?", line 6, in anonymous', # this is the appexec code object ' File "?", line 3, in foo', ' File "?", line 5, in bar', "", ] ) assert tb == expected
def register_builtin_error_handlers(space): "NOT_RPYTHON" state = space.fromcache(CodecState) for error in ("strict", "ignore", "replace", "xmlcharrefreplace", "backslashreplace"): name = error + "_errors" state.codec_error_registry[error] = space.wrap(interp2app(globals()[name]))
def setup_class(cls): from pypy.interpreter import gateway import sys space = cls.space cls.w_cpython_behavior = space.wrap(not option.runappdirect) cls.w_cpython_version = space.wrap(tuple(sys.version_info)) cls.w_appdirect = space.wrap(option.runappdirect) cls.w_cpython_apptest = space.wrap(option.runappdirect and not hasattr(sys, 'pypy_translation_info')) def w_unwrap_wrap_unicode(space, w_obj): return space.wrap(space.unicode_w(w_obj)) cls.w_unwrap_wrap_unicode = space.wrap(gateway.interp2app(w_unwrap_wrap_unicode)) def w_unwrap_wrap_bytes(space, w_obj): return space.wrapbytes(space.bytes_w(w_obj)) cls.w_unwrap_wrap_bytes = space.wrap(gateway.interp2app(w_unwrap_wrap_bytes))
def setup_class(cls): cls.space = gettestobjspace(**{"objspace.std.withmapdict": True}) if option.runappdirect: py.test.skip("can only be run on py.py") def has_mapdict(space, w_inst): return space.wrap(w_inst._get_mapdict_map() is not None) cls.w_has_mapdict = cls.space.wrap(gateway.interp2app(has_mapdict))
def test_exception(): space = CPyObjSpace() func = interp2app(entrypoint1).__spacebind__(space) bltin = BuiltinFunction(func) w_entrypoint = space.wrap(bltin) w1 = space.wrap('not an int') raises_w(space, space.w_TypeError, space.call_function, w_entrypoint, w1)
def setup_method(self, func): @unwrap_spec(name=str, init=str, body=str) def create_cdll(space, name, init, body): # the following is loosely from test_cpyext.py import_module; it # is copied here to be able to tweak the call to # compile_extension_module and to get a different return result # than in that function code = """ #include <Python.h> /* fix for cpython 2.7 Python.h if running tests with -A since pypy compiles with -fvisibility-hidden */ #undef PyMODINIT_FUNC #define PyMODINIT_FUNC RPY_EXPORTED void %(body)s PyMODINIT_FUNC init%(name)s(void) { %(init)s } """ % dict( name=name, init=init, body=body ) kwds = dict(separate_module_sources=[code]) mod = compile_extension_module(space, name, **kwds) # explicitly load the module as a CDLL rather than as a module from pypy.module.imp.importing import get_so_extension fullmodname = os.path.join(os.path.dirname(mod), name + get_so_extension(space)) return space.wrap(fullmodname) self.w_create_cdll = self.space.wrap(interp2app(create_cdll))
def test_None_result(): space = CPyObjSpace() func = interp2app(entrypoint2).__spacebind__(space) bltin = BuiltinFunction(func) w_entrypoint = space.wrap(bltin) w_result = space.call_function(w_entrypoint, space.wrap(-2)) assert space.is_w(w_result, space.wrap(None))
def test_with_new_with_allocate_instance(): def mytype_new(space, w_subtype, x): w_obj = space.allocate_instance(W_MyType, w_subtype) W_MyType.__init__(space.interp_w(W_MyType, w_obj), space, x) return w_obj mytype_new.unwrap_spec = [ObjSpace, W_Root, int] W_MyType.typedef = TypeDef("MyType", __new__ = interp2app(mytype_new), x = interp_attrproperty("x", W_MyType)) space = CPyObjSpace() def build(): w_type = space.gettypefor(W_MyType) return space.call_function(w_type, space.wrap(42)) w_obj = build() w_name = space.getattr(space.type(w_obj), space.wrap('__name__')) assert space.unwrap(w_name) == 'MyType' assert space.int_w(space.getattr(w_obj, space.wrap('x'))) == 42 fn = compile(build, [], annotatorpolicy = CPyAnnotatorPolicy(space)) res = fn(expected_extra_mallocs=1) assert type(res).__name__ == 'MyType' assert res.x == 42
def test_with_new_with_allocate_instance_subclass(): py.test.skip("dealloction for now segfaults") def mytype_new(space, w_subtype, x): w_obj = space.allocate_instance(W_MyType, w_subtype) W_MyType.__init__(space.interp_w(W_MyType, w_obj), space, x) return w_obj mytype_new.unwrap_spec = [ObjSpace, W_Root, int] W_MyType.typedef = TypeDef("MyType", __new__ = interp2app(mytype_new), x = interp_attrproperty("x", W_MyType)) space = CPyObjSpace() def build(): w_type = space.gettypefor(W_MyType) return space.call_function(w_type, space.wrap(42)) fn = compile(build, [], annotatorpolicy = CPyAnnotatorPolicy(space)) res = fn(expected_extra_mallocs=1) assert type(res).__name__ == 'MyType' assert res.x == 42 class MyType2(type(res)): pass res2 = MyType2(42) assert type(res2) is MyType2 assert res2.x == 42 del res2 import gc gc.collect()
def setup_class(cls): BaseAppTestFFI.setup_class.im_func(cls) @unwrap_spec(addr=int, typename=str, length=int) def read_raw_mem(space, addr, typename, length): import ctypes addr = ctypes.cast(addr, ctypes.c_void_p) c_type = getattr(ctypes, typename) array_type = ctypes.POINTER(c_type * length) ptr_array = ctypes.cast(addr, array_type) array = ptr_array[0] lst = [array[i] for i in range(length)] return space.wrap(lst) if cls.runappdirect: cls.w_read_raw_mem = lambda self, *args: read_raw_mem(cls.space, *args) else: cls.w_read_raw_mem = cls.space.wrap(interp2app(read_raw_mem)) # from rpython.rlib import clibffi from rpython.rlib.rarithmetic import r_uint from rpython.rtyper.lltypesystem import lltype, rffi dummy_type = lltype.malloc(clibffi.FFI_TYPE_P.TO, flavor='raw') dummy_type.c_size = r_uint(123) dummy_type.c_alignment = rffi.cast(rffi.USHORT, 0) dummy_type.c_type = rffi.cast(rffi.USHORT, 0) cls.w_dummy_type = W_FFIType('dummy', dummy_type) cls.w_runappdirect = cls.space.wrap(cls.runappdirect)
def patch_unicodedb(): from pypy.module.unicodedata import unicodedb_4_1_0 from pypy.module.unicodedata.interp_ucd import UCD, methods, \ unichr_to_code_w from pypy.interpreter.gateway import W_Root, ObjSpace, NoneNotWrapped from unicodedb import _casefold from pypy.interpreter.typedef import TypeDef, interp_attrproperty from pypy.interpreter.gateway import interp2app def casefold(code): try: return _casefold[code] except KeyError: return [code] unicodedb_4_1_0.casefold = casefold # patch the app-level, so it's exposed def interp_casefold(self, space, w_unichr): code = unichr_to_code_w(space, w_unichr) return space.newlist([space.wrap(c) for c in casefold(code)]) unwrap_spec = ['self', ObjSpace, W_Root] UCD.casefold = interp_casefold methods['casefold'] = interp2app(UCD.casefold, unwrap_spec=unwrap_spec) UCD.typedef = TypeDef("unicodedata.UCD", __doc__ = "", unidata_version = interp_attrproperty('version', UCD), **methods)
def _new_exception(name, base, docstring, **kwargs): # Create a subclass W_Exc of the class 'base'. Note that there is # hackery going on on the typedef of W_Exc: when we make further # app-level subclasses, they inherit at interp-level from 'realbase' # instead of W_Exc. This allows multiple inheritance to work (see # test_multiple_inheritance in test_exc.py). class W_Exc(base): __doc__ = docstring W_Exc.__name__ = 'W_' + name realbase = base.typedef.applevel_subclasses_base or base for k, v in kwargs.items(): kwargs[k] = interp2app(v.__get__(None, realbase)) W_Exc.typedef = TypeDef( name, base.typedef, __doc__ = W_Exc.__doc__, __module__ = 'exceptions', **kwargs ) W_Exc.typedef.applevel_subclasses_base = realbase return W_Exc
def setup_class(cls): from pypy.interpreter import gateway # def check(space, w_func, name): w_code = space.getattr(w_func, space.wrap("__code__")) nameindex = map(space.str_w, w_code.co_names_w).index(name) entry = w_code._mapdict_caches[nameindex] entry.failure_counter = 0 entry.success_counter = 0 INVALID_CACHE_ENTRY.failure_counter = 0 # w_res = space.call_function(w_func) assert space.eq_w(w_res, space.wrap(42)) # entry = w_code._mapdict_caches[nameindex] if entry is INVALID_CACHE_ENTRY: failures = successes = 0 else: failures = entry.failure_counter successes = entry.success_counter globalfailures = INVALID_CACHE_ENTRY.failure_counter return space.wrap((failures, successes, globalfailures)) check.unwrap_spec = [gateway.ObjSpace, gateway.W_Root, str] cls.w_check = cls.space.wrap(gateway.interp2app(check))
def setup_class(cls): from pypy.interpreter import gateway cls.space = gettestobjspace( **{"objspace.std.withmapdict": True, "objspace.std.withmethodcachecounter": True, "objspace.opcodes.CALL_METHOD": True}) # def check(space, w_func, name): w_code = space.getattr(w_func, space.wrap('func_code')) nameindex = map(space.str_w, w_code.co_names_w).index(name) entry = w_code._mapdict_caches[nameindex] entry.failure_counter = 0 entry.success_counter = 0 INVALID_CACHE_ENTRY.failure_counter = 0 # w_res = space.call_function(w_func) assert space.eq_w(w_res, space.wrap(42)) # entry = w_code._mapdict_caches[nameindex] if entry is INVALID_CACHE_ENTRY: failures = successes = 0 else: failures = entry.failure_counter successes = entry.success_counter globalfailures = INVALID_CACHE_ENTRY.failure_counter return space.wrap((failures, successes, globalfailures)) check.unwrap_spec = [gateway.ObjSpace, gateway.W_Root, str] cls.w_check = cls.space.wrap(gateway.interp2app(check))
def win32_namespace(space): "NOT_RPYTHON" w_win32 = space.call_function(space.w_type, space.wrap("win32"), space.newtuple([]), space.newdict()) # constants for name in CONSTANTS: space.setattr(w_win32, space.wrap(name), space.wrap(config[name])) space.setattr(w_win32, space.wrap('NULL'), space.newint(0)) # functions for name in ['CloseHandle', 'GetLastError', 'CreateFile', 'CreateNamedPipe', 'ConnectNamedPipe', 'SetNamedPipeHandleState', 'WaitNamedPipe', 'ExitProcess', ]: function = globals()[name] w_function = space.wrap(interp2app(function)) w_method = space.wrap(StaticMethod(w_function)) space.setattr(w_win32, space.wrap(name), w_method) return w_win32
srepat.w_pattern = w_pattern # the original uncompiled pattern srepat.flags = flags # note: we assume that the app-level is caching SRE_Pattern objects, # so that we don't need to do it here. Creating new SRE_Pattern # objects all the time would be bad for the JIT, which relies on the # identity of the CompiledPattern() object. srepat.code = rsre_core.CompiledPattern(code) srepat.num_groups = groups srepat.w_groupindex = w_groupindex srepat.w_indexgroup = w_indexgroup return w_srepat W_SRE_Pattern.typedef = TypeDef( 'SRE_Pattern', __new__=interp2app(SRE_Pattern__new__), __copy__=interp2app(W_SRE_Pattern.cannot_copy_w), __deepcopy__=interp2app(W_SRE_Pattern.cannot_copy_w), __weakref__=make_weakref_descr(W_SRE_Pattern), findall=interp2app(W_SRE_Pattern.findall_w), finditer=interp2app(W_SRE_Pattern.finditer_w), match=interp2app(W_SRE_Pattern.match_w), scanner=interp2app(W_SRE_Pattern.finditer_w), # reuse finditer() search=interp2app(W_SRE_Pattern.search_w), split=interp2app(W_SRE_Pattern.split_w), sub=interp2app(W_SRE_Pattern.sub_w), subn=interp2app(W_SRE_Pattern.subn_w), flags=interp_attrproperty('flags', W_SRE_Pattern, wrapfn="newint"), groupindex=interp_attrproperty_w('w_groupindex', W_SRE_Pattern), groups=interp_attrproperty('num_groups', W_SRE_Pattern, wrapfn="newint"), pattern=interp_attrproperty_w('w_pattern', W_SRE_Pattern),
# only share the empty string if len(s) == 0: return W_BytesObject.EMPTY return W_BytesObject(s) def wrapchar(space, c): if space.config.objspace.std.withprebuiltchar and not we_are_jitted(): return W_BytesObject.PREBUILT[ord(c)] else: return W_BytesObject(c) W_BytesObject.typedef = TypeDef( "str", basestring_typedef, __new__ = interp2app(W_BytesObject.descr_new), __doc__ = """str(object='') -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. """, __repr__ = interpindirect2app(W_AbstractBytesObject.descr_repr), __str__ = interpindirect2app(W_AbstractBytesObject.descr_str), __hash__ = interpindirect2app(W_AbstractBytesObject.descr_hash), __eq__ = interpindirect2app(W_AbstractBytesObject.descr_eq), __ne__ = interpindirect2app(W_AbstractBytesObject.descr_ne), __lt__ = interpindirect2app(W_AbstractBytesObject.descr_lt), __le__ = interpindirect2app(W_AbstractBytesObject.descr_le), __gt__ = interpindirect2app(W_AbstractBytesObject.descr_gt),
raise OperationError( w_errortype, space.newtuple2(space.newint(e.errno), space.newtext(message))) finally: self.running = False retval_w = [] for fd, revents in retval: retval_w.append( space.newtuple2(space.newint(fd), space.newint(revents))) return space.newlist(retval_w) pollmethods = {} for methodname in 'register modify unregister poll'.split(): pollmethods[methodname] = interp2app(getattr(Poll, methodname)) Poll.typedef = TypeDef('select.poll', **pollmethods) # ____________________________________________________________ @objectmodel.always_inline # get rid of the tuple result def _build_fd_set(space, list_w, ll_list, nfds): _c.FD_ZERO(ll_list) fdlist = [] for w_f in list_w: fd = space.c_filedescriptor_w(w_f) if fd > nfds: if _c.MAX_FD_SIZE is not None and fd >= _c.MAX_FD_SIZE: raise oefmt(space.w_ValueError, "file descriptor out of range in select()")
try: return CDLL(name) except DLOpenError as e: raise wrap_dlopenerror(space, e, name or "<None>") except OSError as e: raise wrap_oserror(space, e) @unwrap_spec(name='fsencode_or_none') def descr_new_cdll(space, w_type, name): cdll = open_cdll(space, name) return W_CDLL(space, name, cdll) W_CDLL.typedef = TypeDef('CDLL', __new__=interp2app(descr_new_cdll), ptr=interp2app(W_CDLL.ptr), getaddressindll=interp2app(W_CDLL.getaddressindll), name=interp_attrproperty('name', W_CDLL, wrapfn="newtext_or_none"), __doc__=""" C Dynamically loaded library use CDLL(libname) to create a handle to a C library (the argument is processed the same way as dlopen processes it). On such a library you can call: lib.ptr(func_name, argtype_list, restype) where argtype_list is a list of single characters and restype is a single character. The character meanings are more or less the same as in the struct module, except that s has trailing \x00 added, while p is considered a raw buffer."""
return self.ctptr.typeoffsetof_index(index) class W_CDataIter(W_Root): _immutable_fields_ = ['ctitem', 'cdata', '_stop'] # but not '_next' def __init__(self, space, ctitem, cdata): self.space = space self.ctitem = ctitem self.cdata = cdata length = cdata.get_array_length() self._next = cdata.unsafe_escaping_ptr() self._stop = rffi.ptradd(self._next, length * ctitem.size) def iter_w(self): return self def next_w(self): result = self._next if result == self._stop: raise OperationError(self.space.w_StopIteration, self.space.w_None) self._next = rffi.ptradd(result, self.ctitem.size) return self.ctitem.convert_to_object(result) W_CDataIter.typedef = TypeDef( '_cffi_backend.__CData_iterator', __iter__ = interp2app(W_CDataIter.iter_w), __next__ = interp2app(W_CDataIter.next_w), ) W_CDataIter.typedef.acceptable_as_base_class = False
if space.issubtype_w(w_type, space.gettypeobject(PyCode.typedef)): return W_TransparentCode(space, w_type, w_controller) if w_type.layout.typedef is space.w_object.layout.typedef: return W_Transparent(space, w_type, w_controller) else: raise oefmt(space.w_TypeError, "type expected as first argument") w_lookup = w_type for k, v in type_cache.cache: if w_lookup == k: return v(space, w_type, w_controller) raise oefmt(space.w_TypeError, "'%N' object could not be wrapped", w_type) def register_proxyable(space, cls): tpdef = cls.typedef class W_TransparentUserCreated(W_Transparent): typedef = tpdef type_cache.cache.append((space.gettypeobject(tpdef), W_TransparentUserCreated)) def proxy_controller(space, w_object): """get_tproxy_controller(obj) -> controller If obj is really a transparent proxy, return its controller. Otherwise return None.""" if isinstance(w_object, W_Transparent): return w_object.w_controller #if isinstance(w_object, W_TransparentObject): # return w_object.w_controller return None app_proxy = gateway.interp2app(proxy) app_proxy_controller = gateway.interp2app(proxy_controller)
def get_bytecode_no(self, space): if self.jd_name == pypyjitdriver.name: return space.getitem(self.w_greenkey, space.newint(1)) raise oefmt( space.w_AttributeError, "This DebugMergePoint doesn't belong to the main Python " "JitDriver") def get_jitdriver_name(self, space): return space.newtext(self.jd_name) WrappedOp.typedef = TypeDef( 'ResOperation', __doc__=WrappedOp.__doc__, __new__=interp2app(descr_new_resop), __repr__=interp2app(WrappedOp.descr_repr), name=GetSetProperty(WrappedOp.descr_name), offset=interp_attrproperty("offset", cls=WrappedOp, wrapfn="newint"), ) WrappedOp.typedef.acceptable_as_base_class = False GuardOp.typedef = TypeDef( 'GuardOp', __doc__=GuardOp.__doc__, __new__=interp2app(descr_new_guardop), __repr__=interp2app(GuardOp.descr_repr), name=GetSetProperty(GuardOp.descr_name), offset=interp_attrproperty("offset", cls=GuardOp, wrapfn="newint"), hash=interp_attrproperty("hash", cls=GuardOp, wrapfn="newint"), )
''', filename=__file__).interphook('makefile') @unwrap_spec(family=int, type=int, proto=int) def newsocket(space, w_subtype, family=AF_INET, type=SOCK_STREAM, proto=0): self = space.allocate_instance(W_Socket, w_subtype) try: sock = RSocket(family, type, proto) except SocketError as e: raise converted_error(space, e) W_Socket.__init__(self, space, sock) return self descr_socket_new = interp2app(newsocket) # ____________________________________________________________ # Automatic shutdown()/close() # On some systems, the C library does not guarantee that when the program # finishes, all data sent so far is really sent even if the socket is not # explicitly closed. This behavior has been observed on Windows but not # on Linux, so far. NEED_EXPLICIT_CLOSE = (sys.platform == 'win32') class OpenRSockets(rweaklist.RWeakListMixin): pass
dequerepr = app.interphook("dequerepr") def descr__new__(space, w_subtype, __args__): w_self = space.allocate_instance(W_Deque, w_subtype) W_Deque.__init__(space.interp_w(W_Deque, w_self), space) return w_self W_Deque.typedef = TypeDef( "collections.deque", __doc__="""deque(iterable[, maxlen]) --> deque object Build an ordered collection accessible from endpoints only.""", __new__=interp2app(descr__new__), __init__=interp2app(W_Deque.init), append=interp2app(W_Deque.append), appendleft=interp2app(W_Deque.appendleft), clear=interp2app(W_Deque.clear), count=interp2app(W_Deque.count), extend=interp2app(W_Deque.extend), extendleft=interp2app(W_Deque.extendleft), pop=interp2app(W_Deque.pop), popleft=interp2app(W_Deque.popleft), remove=interp2app(W_Deque.remove), reverse=interp2app(W_Deque.reverse), rotate=interp2app(W_Deque.rotate), __weakref__=make_weakref_descr(W_Deque), __iter__=interp2app(W_Deque.iter), __reversed__=interp2app(W_Deque.reviter),
return space.wrap(block_size) def _digest(self, space): with lltype.scoped_alloc(ropenssl.EVP_MD_CTX.TO) as ctx: with self.lock: ropenssl.EVP_MD_CTX_copy(ctx, self.ctx) digest_size = self.digest_size with lltype.scoped_alloc(rffi.CCHARP.TO, digest_size) as digest: ropenssl.EVP_DigestFinal(ctx, digest, None) ropenssl.EVP_MD_CTX_cleanup(ctx) return rffi.charpsize2str(digest, digest_size) W_Hash.typedef = TypeDef( 'HASH', __repr__=interp2app(W_Hash.descr_repr), update=interp2app(W_Hash.update), copy=interp2app(W_Hash.copy), digest=interp2app(W_Hash.digest), hexdigest=interp2app(W_Hash.hexdigest), # digest_size=GetSetProperty(W_Hash.get_digest_size), digestsize=GetSetProperty(W_Hash.get_digest_size), block_size=GetSetProperty(W_Hash.get_block_size), ) W_Hash.acceptable_as_base_class = False @unwrap_spec(name=str, string='bufferstr') def new(space, name, string=''): w_hash = W_Hash(space, name)
return self.space.wrap(self.hexdigest()) def copy_w(self): clone = W_SHA(self.space) clone._copyfrom(self) return self.space.wrap(clone) def W_SHA___new__(space, w_subtype, initialdata=''): """ Create a new sha object and call its initializer. """ w_sha = space.allocate_instance(W_SHA, w_subtype) sha = space.interp_w(W_SHA, w_sha) W_SHA.__init__(sha, space) sha.update(initialdata) return w_sha W_SHA.typedef = TypeDef( 'SHAType', __new__=interp2app(W_SHA___new__, unwrap_spec=[ObjSpace, W_Root, 'bufferstr']), update=interp2app(W_SHA.update_w, unwrap_spec=['self', 'bufferstr']), digest=interp2app(W_SHA.digest_w, unwrap_spec=['self']), hexdigest=interp2app(W_SHA.hexdigest_w, unwrap_spec=['self']), copy=interp2app(W_SHA.copy_w, unwrap_spec=['self']), __doc__="""sha(arg) -> return new sha object. If arg is present, the method call update(arg) is made.""")
# try: output = c_codecs.encode(self.codec, input, errors, state.encode_error_handler, self.name) except c_codecs.EncodeDecodeError as e: raise wrap_unicodeencodeerror(space, e, input, self.name) except RuntimeError: raise wrap_runtimeerror(space) return space.newtuple( [space.newbytes(output), space.newint(len(input))]) MultibyteCodec.typedef = TypeDef( 'MultibyteCodec', decode=interp2app(MultibyteCodec.decode), encode=interp2app(MultibyteCodec.encode), ) MultibyteCodec.typedef.acceptable_as_base_class = False @unwrap_spec(name='text') def getcodec(space, name): try: codec = c_codecs.getcodec(name) except KeyError: raise oefmt(space.w_LookupError, "no such codec is supported.") return MultibyteCodec(name, codec) def wrap_unicodedecodeerror(space, e, input, name):
raise OperationError(space.w_ValueError, strerror) bytes = ((k - 1) // 32 + 1) * 4 bytesarray = rstring.StringBuilder(bytes) for i in range(0, bytes, 4): r = self._rnd.genrand32() if k < 32: r >>= (32 - k) bytesarray.append(chr(r & r_uint(0xff))) bytesarray.append(chr((r >> 8) & r_uint(0xff))) bytesarray.append(chr((r >> 16) & r_uint(0xff))) bytesarray.append(chr((r >> 24) & r_uint(0xff))) k -= 32 # little endian order to match bytearray assignment order result = rbigint.rbigint.frombytes(bytesarray.build(), 'little', signed=False) return space.newlong_from_rbigint(result) W_Random.typedef = TypeDef( "Random", __new__=interp2app(descr_new__), random=interp2app(W_Random.random), seed=interp2app(W_Random.seed), getstate=interp2app(W_Random.getstate), setstate=interp2app(W_Random.setstate), jumpahead=interp2app(W_Random.jumpahead), getrandbits=interp2app(W_Random.getrandbits), )
doc="count(obj) -> number of times obj appears in the tuple") tuple_index = SMM("index", 4, defaults=(0, sys.maxint), doc="index(obj, [start, [stop]]) -> first index that obj " "appears in the tuple") def descr__new__(space, w_tupletype, w_sequence=None): from pypy.objspace.std.tupleobject import W_TupleObject if w_sequence is None: tuple_w = [] elif (space.is_w(w_tupletype, space.w_tuple) and space.is_w(space.type(w_sequence), space.w_tuple)): return w_sequence else: tuple_w = space.fixedview(w_sequence) w_obj = space.allocate_instance(W_TupleObject, w_tupletype) W_TupleObject.__init__(w_obj, tuple_w) return w_obj # ____________________________________________________________ tuple_typedef = StdTypeDef("tuple", __doc__ = '''tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items If the argument is a tuple, the return value is the same object.''', __new__ = gateway.interp2app(descr__new__), ) tuple_typedef.registermethods(globals())
elif self.typecode == "c": r = space.repr(self.descr_tostring(space)) s = "array('%s', %s)" % (self.typecode, space.text_w(r)) return space.newtext(s) elif self.typecode == "u": r = space.repr(self.descr_tounicode(space)) s = "array('%s', %s)" % (self.typecode, space.text_w(r)) return space.newtext(s) else: r = space.repr(self.descr_tolist(space)) s = "array('%s', %s)" % (self.typecode, space.text_w(r)) return space.newtext(s) W_ArrayBase.typedef = TypeDef( 'array.array', None, None, "read-write", __new__ = interp2app(w_array), __len__ = interp2app(W_ArrayBase.descr_len), __eq__ = interp2app(W_ArrayBase.descr_eq), __ne__ = interp2app(W_ArrayBase.descr_ne), __lt__ = interp2app(W_ArrayBase.descr_lt), __le__ = interp2app(W_ArrayBase.descr_le), __gt__ = interp2app(W_ArrayBase.descr_gt), __ge__ = interp2app(W_ArrayBase.descr_ge), __getitem__ = interp2app(W_ArrayBase.descr_getitem), __getslice__ = interp2app(W_ArrayBase.descr_getslice), __setitem__ = interp2app(W_ArrayBase.descr_setitem), __setslice__ = interp2app(W_ArrayBase.descr_setslice), __delitem__ = interp2app(W_ArrayBase.descr_delitem), __delslice__ = interp2app(W_ArrayBase.descr_delslice),
class WrappedBox(Wrappable): """ A class representing a single box """ def __init__(self, llbox): self.llbox = llbox def descr_getint(self, space): return space.wrap(jit_hooks.box_getint(self.llbox)) @unwrap_spec(no=int) def descr_new_box(space, w_tp, no): return WrappedBox(jit_hooks.boxint_new(no)) WrappedBox.typedef = TypeDef( 'Box', __new__ = interp2app(descr_new_box), getint = interp2app(WrappedBox.descr_getint), ) @unwrap_spec(num=int, offset=int, repr=str, res=WrappedBox) def descr_new_resop(space, w_tp, num, w_args, res, offset=-1, repr=''): args = [space.interp_w(WrappedBox, w_arg).llbox for w_arg in space.listview(w_args)] if res is None: llres = jit_hooks.emptyval() else: llres = res.llbox return WrappedOp(jit_hooks.resop_new(num, args, llres), offset, repr) class WrappedOp(Wrappable):
Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. Add a 'U' to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a '\n' in Python. Also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\r', '\n', '\r\n' or a tuple containing all the newline types seen. Note: open() is an alias for file(). """, __new__=interp2app(descr_file__new__), fdopen=interp2app(descr_file_fdopen, as_classmethod=True), name=interp_attrproperty_w('w_name', cls=W_File, doc="file name"), mode=interp_attrproperty('mode', cls=W_File, doc="file mode ('r', 'U', 'w', 'a', " "possibly with 'b' or '+' added)"), encoding=interp_attrproperty('encoding', cls=W_File), errors=interp_attrproperty('errors', cls=W_File), closed=GetSetProperty(descr_file_closed, cls=W_File, doc="True if the file is closed"), newlines=GetSetProperty(descr_file_newlines, cls=W_File, doc="end-of-line convention used in this file"), softspace=GetSetProperty(descr_file_softspace,
def wrap_trampoline_in_gateway(func, methname, multimethod): """NOT_RPYTHON""" if 'doc' in multimethod.extras: func.__doc__ = multimethod.extras['doc'] return gateway.interp2app(func, app_name=methname)
if name == '__dict__': raise OperationError(space.w_ValueError, space.wrap("Cannot change __dict__")) js_val = self.ctx.python_to_js(w_value) self.ctx.set(self.js_val, name, js_val) return space.w_None def call(self, space, args_w): js_res = self.ctx.call(self.js_val, [self.ctx.python_to_js(arg) for arg in args_w], self.this) return self.ctx.js_to_python(js_res) def str(self, space): return space.wrap('JSObject(' + self.ctx.str_js(self.js_val) + ')') JSObject.typedef = TypeDef( "JSObject", __getattribute__=interp2app(JSObject.descr_get, unwrap_spec=['self', ObjSpace, W_Root]), __getitem__=interp2app(JSObject.descr_get, unwrap_spec=['self', ObjSpace, W_Root]), __setitem__=interp2app(JSObject.descr_set, unwrap_spec=['self', ObjSpace, W_Root, W_Root]), __setattr__=interp2app(JSObject.descr_set, unwrap_spec=['self', ObjSpace, W_Root, W_Root]), __str__=interp2app(JSObject.str, unwrap_spec=['self', ObjSpace]), __call__=interp2app(JSObject.call, unwrap_spec=['self', ObjSpace, 'args_w']))
The result is the value of the handle before it is detached. If the handle is already detached, this will return zero. After calling this function, the handle is effectively invalidated, but the handle is not closed. You would call this function when you need the underlying win32 handle to exist beyond the lifetime of the handle object. On 64 bit windows, the result of this function is a long integer""" hkey = self.hkey self.hkey = 0 return space.wrap(hkey) Detach.unwrap_spec = ['self', ObjSpace] def new_HKEY(space, w_subtype, hkey): return space.wrap(W_HKEY(hkey)) descr_HKEY_new = interp2app(new_HKEY, unwrap_spec=[ObjSpace, W_Root, int]) W_HKEY.typedef = TypeDef( "_winreg.HKEYType", __doc__ = """\ PyHKEY Object - A Python object, representing a win32 registry key. This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the Close() method on the PyHKEY, or the CloseKey() method. All functions which accept a handle object also accept an integer - however, use of the handle object is encouraged. Functions: Close() - Closes the underlying handle.
def truncate_w(self, space, w_size=None): self._check_closed(space) self._check_writable(space) if space.is_none(w_size): w_size = self.tell_w(space) try: self._truncate(space.r_longlong_w(w_size)) except OSError as e: raise wrap_oserror(space, e, w_exception_class=space.w_IOError) return w_size W_FileIO.typedef = TypeDef( '_io.FileIO', W_RawIOBase.typedef, __new__ = interp2app(W_FileIO.descr_new.im_func), __init__ = interp2app(W_FileIO.descr_init), __repr__ = interp2app(W_FileIO.repr_w), seek = interp2app(W_FileIO.seek_w), tell = interp2app(W_FileIO.tell_w), write = interp2app(W_FileIO.write_w), read = interp2app(W_FileIO.read_w), readinto = interp2app(W_FileIO.readinto_w), readall = interp2app(W_FileIO.readall_w), truncate = interp2app(W_FileIO.truncate_w), close = interp2app(W_FileIO.close_w), readable = interp2app(W_FileIO.readable_w), writable = interp2app(W_FileIO.writable_w), seekable = interp2app(W_FileIO.seekable_w),
w_clone = space.allocate_instance(W_DictIter_Values, w_typeobj) elif isinstance(w_self, W_DictIter_Items): w_clone = space.allocate_instance(W_DictIter_Items, w_typeobj) else: msg = "unsupported dictiter type '%s' during pickling" % (w_self, ) raise OperationError(space.w_TypeError, space.wrap(msg)) w_clone.space = space w_clone.content = w_self.content w_clone.len = w_self.len w_clone.pos = 0 w_clone.setup_iterator() # spool until we have the same pos while w_clone.pos < w_self.pos: w_obj = w_clone.next_entry() w_clone.pos += 1 stuff = [w_clone.next_entry() for i in range(w_clone.pos, w_clone.len)] w_res = space.newlist(stuff) tup = [w_res] w_ret = space.newtuple([new_inst, space.newtuple(tup)]) return w_ret # ____________________________________________________________ dictiter_typedef = StdTypeDef( "dictionaryiterator", __reduce__=gateway.interp2app( descr_dictiter__reduce__, unwrap_spec=[gateway.W_Root, gateway.ObjSpace]), )
not space.len_w(args_w[0]) == 1: raise oefmt(space.w_TypeError, "tuple object of length 1 expected, received %T", args_w[0]) w_shape = args_w[0] # shape in W_ArrayInstance-speak is somewhat different from what # e.g. numpy thinks of it: self.shape contains the info (itemcode, # size, etc.) of a single entry; length is user-facing shape self.length = space.int_w(space.getitem(w_shape, space.newint(0))) W_LowLevelView.typedef = TypeDef( 'LowLevelView', __repr__=interp2app(W_LowLevelView.descr_repr), __setitem__=interp2app(W_LowLevelView.descr_setitem), __getitem__=interp2app(W_LowLevelView.descr_getitem), __len__=interp2app(W_LowLevelView.getlength), buffer=GetSetProperty(W_LowLevelView.getbuffer), shape=interp_attrproperty_w('shape', W_LowLevelView), free=interp2app(W_LowLevelView.free), byptr=interp2app(W_LowLevelView.byptr), itemaddress=interp2app(W_LowLevelView.descr_itemaddress), reshape=interp2app(W_LowLevelView.reshape), ) W_LowLevelView.typedef.acceptable_as_base_class = False class W_ArrayOfInstances(W_Root): _attrs_ = ['converter', 'baseaddress', 'clssize', 'length']
Return a copy of B with all ASCII characters converted to uppercase. """ def zfill(): """B.zfill(width) -> copy of B Pad a numeric string B with zeros on the left, to fill a field of the specified width. B is never truncated. """ W_BytearrayObject.typedef = TypeDef( "bytearray", None, None, "read-write", __doc__ = BytearrayDocstrings.__doc__, __new__ = interp2app(W_BytearrayObject.descr_new), __hash__ = None, __reduce__ = interp2app(W_BytearrayObject.descr_reduce, doc=BytearrayDocstrings.__reduce__.__doc__), fromhex = interp2app(W_BytearrayObject.descr_fromhex, as_classmethod=True, doc=BytearrayDocstrings.fromhex.__doc__), __repr__ = interp2app(W_BytearrayObject.descr_repr, doc=BytearrayDocstrings.__repr__.__doc__), __str__ = interp2app(W_BytearrayObject.descr_str, doc=BytearrayDocstrings.__str__.__doc__), __eq__ = interp2app(W_BytearrayObject.descr_eq, doc=BytearrayDocstrings.__eq__.__doc__), __ne__ = interp2app(W_BytearrayObject.descr_ne, doc=BytearrayDocstrings.__ne__.__doc__),
or space.is_w(w_cls, space.type(space.w_None))) if asking_for_bound: return Method(space, w_function, w_obj, w_cls) else: return w_function def cclassmethod_descr_get(space, w_function, w_obj, w_cls=None): if not w_cls: w_cls = space.type(w_obj) return Method(space, w_function, w_cls, space.w_None) W_PyCFunctionObject.typedef = TypeDef( 'builtin_function_or_method', __call__=interp2app(cfunction_descr_call), __doc__=GetSetProperty(W_PyCFunctionObject.get_doc), __module__=interp_attrproperty_w('w_module', cls=W_PyCFunctionObject), __name__=interp_attrproperty('name', cls=W_PyCFunctionObject, wrapfn="newtext_or_none"), ) W_PyCFunctionObject.typedef.acceptable_as_base_class = False W_PyCMethodObject.typedef = TypeDef( 'method', __get__=interp2app(cmethod_descr_get), __call__=interp2app(cmethod_descr_call), __name__=interp_attrproperty('name', cls=W_PyCMethodObject, wrapfn="newtext_or_none"),
""" w_stream = space.allocate_instance(Compress, w_subtype) w_stream = space.interp_w(Compress, w_stream) try: stream = rzlib.deflateInit(level, method, wbits, memLevel, strategy) except rzlib.RZlibError as e: raise zlib_error(space, e.msg) except ValueError: raise oefmt(space.w_ValueError, "Invalid initialization option") Compress.__init__(w_stream, space, stream) return w_stream Compress.typedef = TypeDef( 'Compress', __new__ = interp2app(Compress___new__), copy = interp2app(Compress.copy), compress = interp2app(Compress.compress), flush = interp2app(Compress.flush), __doc__ = """compressobj([level]) -- Return a compressor object. Optional arg level is the compression level, in 1-9. """) class Decompress(ZLibObject): """ Wrapper around zlib's z_stream structure which provides convenient decompression functionality. """ def __init__(self, space, stream, unused_data, unconsumed_tail):
__args__=None): if __args__.arguments_w: raise OperationError( space.w_TypeError, space.wrap("__new__ expected at most 2 arguments")) if space.is_none(w_callable): return get_or_make_weakref(space, w_subtype, w_obj) else: return make_weakref_with_callback(space, w_subtype, w_obj, w_callable) W_Weakref.typedef = TypeDef( "weakref", __doc__="""A weak reference to an object 'obj'. A 'callback' can be given, which is called with 'obj' as an argument when it is about to be finalized.""", __new__=interp2app(descr__new__weakref), __init__=interp2app(W_Weakref.descr__init__weakref), __eq__=interp2app(W_Weakref.descr__eq__), __ne__=interp2app(W_Weakref.descr__ne__), __hash__=interp2app(W_Weakref.descr_hash), __call__=interp2app(W_Weakref.descr_call), __repr__=interp2app(W_WeakrefBase.descr__repr__), ) def _weakref_count(lifeline, wref, count): if wref() is not None: count += 1 return count
def setup_class(cls): space = cls.space cls.w_udir = space.wrap(str(udir)) cls.w_regex_search = space.wrap(interp2app(regex_search))
and space.lookup(w_obj, '__float__') is None): raise oefmt(space.w_TypeError, "expected a number") @unwrap_spec(w_start=WrappedDefault(0), w_step=WrappedDefault(1)) def W_Count___new__(space, w_subtype, w_start, w_step): check_number(space, w_start) check_number(space, w_step) r = space.allocate_instance(W_Count, w_subtype) r.__init__(space, w_start, w_step) return r W_Count.typedef = TypeDef( 'itertools.count', __new__=interp2app(W_Count___new__), __iter__=interp2app(W_Count.iter_w), next=interp2app(W_Count.next_w), __reduce__=interp2app(W_Count.reduce_w), __repr__=interp2app(W_Count.repr_w), __doc__="""Make an iterator that returns evenly spaced values starting with n. If not specified n defaults to zero. Often used as an argument to imap() to generate consecutive data points. Also, used with izip() to add sequence numbers. Equivalent to: def count(start=0, step=1): n = start while True: yield n
def explode(self): #msg = self.operr.errorstr(space) raise OperationError(self.space.w_TaintError, self.space.w_None) def taint(w_obj): """Return a tainted version of the argument.""" if w_obj is None or isinstance(w_obj, W_Tainted): return w_obj else: return W_Tainted(w_obj) taint.unwrap_spec = [gateway.W_Root] app_taint = gateway.interp2app(taint) def is_tainted(space, w_obj): """Return whether the argument is tainted.""" res = isinstance(w_obj, W_Tainted) or isinstance(w_obj, W_TaintBomb) return space.wrap(res) app_is_tainted = gateway.interp2app(is_tainted) def untaint(space, w_expectedtype, w_obj): """untaint(expectedtype, tainted_obj) -> obj Untaint untainted_obj and return it. If the result is not of expectedtype, raise a type error."""