rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
expected = """ [i0] jump(1) """ self.optimize_loop(ops, 'Not', expected)
preamble = """ [i0] jump() """ expected = """ [] jump() """ self.optimize_loop(ops, 'Not', expected, preamble)
def test_virtual_constant_isnull(self): ops = """ [i0] p0 = new_with_vtable(ConstClass(node_vtable)) setfield_gc(p0, NULL, descr=nextdescr) p2 = getfield_gc(p0, descr=nextdescr) i1 = ptr_eq(p2, NULL) jump(i1) """ expected = """ [i0] jump(1) """ self.optimize_loop(ops, 'Not', expected)
expected = """ [i0] jump(0)
preamble = """ [i0] jump() """ expected = """ [] jump()
def test_virtual_constant_isnonnull(self): ops = """ [i0] p0 = new_with_vtable(ConstClass(node_vtable)) setfield_gc(p0, ConstPtr(myptr), descr=nextdescr) p2 = getfield_gc(p0, descr=nextdescr) i1 = ptr_eq(p2, NULL) jump(i1) """ expected = """ [i0] jump(0) """ self.optimize_loop(ops, 'Not', expected)
expected = ops self.optimize_loop(ops, 'Not, Not', expected)
preamble = """ [i, p0] i0 = getfield_gc(p0, descr=valuedescr) escape(p0) i1 = int_add(i0, i) jump(i, i1) """ expected = """ [i, i1] p1 = new_with_vtable(ConstClass(node_vtable)) setfield_gc(p1, i1, descr=valuedescr) escape(p1) i2 = int_add(i1, i) jump(i, i2) """ self.optimize_loop(ops, 'Not, Not', expected, preamble)
def test_nonvirtual_2(self): ops = """ [i, p0] i0 = getfield_gc(p0, descr=valuedescr) escape(p0) i1 = int_add(i0, i) p1 = new_with_vtable(ConstClass(node_vtable)) setfield_gc(p1, i1, descr=valuedescr) jump(i, p1) """ expected = ops self.optimize_loop(ops, 'Not, Not', expected)
expected = ops self.optimize_loop(ops, 'Not', expected)
preamble = ops expected = """ [i] jump(i) """ self.optimize_loop(ops, 'Not', expected, preamble)
def test_getfield_gc_nonpure_2(self): ops = """ [i] i1 = getfield_gc(ConstPtr(myptr), descr=valuedescr) jump(i1) """ expected = ops self.optimize_loop(ops, 'Not', expected)
expected = """
preamble = """
def test_varray_alloc_and_set(self): ops = """ [i1] p1 = new_array(2, descr=arraydescr) setarrayitem_gc(p1, 0, 25, descr=arraydescr) i2 = getarrayitem_gc(p1, 1, descr=arraydescr) jump(i2) """ expected = """ [i1] jump(0) """ self.optimize_loop(ops, 'Not', expected)
jump(0) """ self.optimize_loop(ops, 'Not', expected)
jump() """ expected = """ [] jump() """ self.optimize_loop(ops, 'Not', expected, preamble)
def test_varray_alloc_and_set(self): ops = """ [i1] p1 = new_array(2, descr=arraydescr) setarrayitem_gc(p1, 0, 25, descr=arraydescr) i2 = getarrayitem_gc(p1, 1, descr=arraydescr) jump(i2) """ expected = """ [i1] jump(0) """ self.optimize_loop(ops, 'Not', expected)
expected = """ [i0, i1, i2]
preamble = """ [i0, p1] i1 = getarrayitem_gc(p1, 0, descr=arraydescr) i2 = getarrayitem_gc(p1, 1, descr=arraydescr)
def test_varray_2(self): ops = """ [i0, p1] i1 = getarrayitem_gc(p1, 0, descr=arraydescr) i2 = getarrayitem_gc(p1, 1, descr=arraydescr) i3 = int_sub(i1, i2) guard_value(i3, 15) [] p2 = new_array(2, descr=arraydescr) setarrayitem_gc(p2, 1, i0, descr=arraydescr) setarrayitem_gc(p2, 0, 20, descr=arraydescr) jump(i0, p2) """ expected = """ [i0, i1, i2] i3 = int_sub(i1, i2) guard_value(i3, 15) [] jump(i0, 20, i0) """ self.optimize_loop(ops, 'Not, VArray(arraydescr, Not, Not)', expected)
jump(i0, 20, i0) """ self.optimize_loop(ops, 'Not, VArray(arraydescr, Not, Not)', expected)
jump(i0) """ expected = """ [i0] i3 = int_sub(20, i0) guard_value(i3, 15) [] jump(5) """ self.optimize_loop(ops, 'Not, Not', expected, preamble)
def test_varray_2(self): ops = """ [i0, p1] i1 = getarrayitem_gc(p1, 0, descr=arraydescr) i2 = getarrayitem_gc(p1, 1, descr=arraydescr) i3 = int_sub(i1, i2) guard_value(i3, 15) [] p2 = new_array(2, descr=arraydescr) setarrayitem_gc(p2, 1, i0, descr=arraydescr) setarrayitem_gc(p2, 0, 20, descr=arraydescr) jump(i0, p2) """ expected = """ [i0, i1, i2] i3 = int_sub(i1, i2) guard_value(i3, 15) [] jump(i0, 20, i0) """ self.optimize_loop(ops, 'Not, VArray(arraydescr, Not, Not)', expected)
config.objspace.compiler = "ast"
def target(self, driver, args): driver.exe_name = 'pypy-%(backend)s'
filename = '<codegen %s:%d>' % (fn, lineno)
filename = '<%d-codegen %s:%d>' % (self._counter, fn, lineno)
def compile(self, filename=None, mode='exec', flag=generators.compiler_flag, dont_inherit=0, _genframe=None): """ return compiled code object. if filename is None invent an artificial filename which displays the source/line position of the caller frame. """ if not filename or py.path.local(filename).check(file=0): if _genframe is None: _genframe = sys._getframe(1) # the caller fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno if not filename: filename = '<codegen %s:%d>' % (fn, lineno) else: filename = '<codegen %r %s:%d>' % (filename, fn, lineno) source = "\n".join(self.lines) + '\n' try: co = cpy_compile(source, filename, mode, flag) except SyntaxError: ex = sys.exc_info()[1] # re-represent syntax errors from parsing python strings msglines = self.lines[:ex.lineno] if ex.offset: msglines.append(" "*ex.offset + '^') msglines.append("syntax error probably generated here: %s" % filename) newex = SyntaxError('\n'.join(msglines)) newex.offset = ex.offset newex.lineno = ex.lineno newex.text = ex.text raise newex else: if flag & _AST_FLAG: return co lines = [(x + "\n") for x in self.lines] if sys.version_info[0] >= 3: # XXX py3's inspect.getsourcefile() checks for a module # and a pep302 __loader__ ... we don't have a module # at code compile-time so we need to fake it here m = ModuleType("_pycodecompile_pseudo_module") py.std.inspect.modulesbyfile[filename] = None py.std.sys.modules[None] = m m.__loader__ = 1 py.std.linecache.cache[filename] = (1, None, lines, filename) return co
filename = '<codegen %r %s:%d>' % (filename, fn, lineno)
filename = '<%d-codegen %r %s:%d>' % (self._counter, filename, fn, lineno) self.__class__._counter += 1
def compile(self, filename=None, mode='exec', flag=generators.compiler_flag, dont_inherit=0, _genframe=None): """ return compiled code object. if filename is None invent an artificial filename which displays the source/line position of the caller frame. """ if not filename or py.path.local(filename).check(file=0): if _genframe is None: _genframe = sys._getframe(1) # the caller fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno if not filename: filename = '<codegen %s:%d>' % (fn, lineno) else: filename = '<codegen %r %s:%d>' % (filename, fn, lineno) source = "\n".join(self.lines) + '\n' try: co = cpy_compile(source, filename, mode, flag) except SyntaxError: ex = sys.exc_info()[1] # re-represent syntax errors from parsing python strings msglines = self.lines[:ex.lineno] if ex.offset: msglines.append(" "*ex.offset + '^') msglines.append("syntax error probably generated here: %s" % filename) newex = SyntaxError('\n'.join(msglines)) newex.offset = ex.offset newex.lineno = ex.lineno newex.text = ex.text raise newex else: if flag & _AST_FLAG: return co lines = [(x + "\n") for x in self.lines] if sys.version_info[0] >= 3: # XXX py3's inspect.getsourcefile() checks for a module # and a pep302 __loader__ ... we don't have a module # at code compile-time so we need to fake it here m = ModuleType("_pycodecompile_pseudo_module") py.std.inspect.modulesbyfile[filename] = None py.std.sys.modules[None] = m m.__loader__ = 1 py.std.linecache.cache[filename] = (1, None, lines, filename) return co
in_dll = ll2ctypes.get_ctypes_type(PyObject).in_dll(bridge, name)
def build_bridge(space): "NOT_RPYTHON" from pypy.module.cpyext.pyobject import make_ref export_symbols = list(FUNCTIONS) + SYMBOLS_C + list(GLOBALS) from pypy.translator.c.database import LowLevelDatabase db = LowLevelDatabase() generate_macros(export_symbols, rename=True, do_deref=True) # Structure declaration code members = [] structindex = {} for name, func in sorted(FUNCTIONS.iteritems()): restype, args = c_function_signature(db, func) members.append('%s (*%s)(%s);' % (restype, name, args)) structindex[name] = len(structindex) structmembers = '\n'.join(members) struct_declaration_code = """\ struct PyPyAPI { %(members)s } _pypyAPI; struct PyPyAPI* pypyAPI = &_pypyAPI; """ % dict(members=structmembers) functions = generate_decls_and_callbacks(db, export_symbols) global_objects = [] for name, (typ, expr) in GLOBALS.iteritems(): if "#" in name: continue if name.startswith('PyExc_'): global_objects.append('%s %s;' % (typ[:-1], '_' + name)) else: global_objects.append('%s %s = NULL;' % (typ, name)) global_code = '\n'.join(global_objects) prologue = "#include <Python.h>\n" code = (prologue + struct_declaration_code + global_code + '\n' + '\n'.join(functions)) eci = build_eci(True, export_symbols, code) eci = eci.compile_shared_lib( outputfilename=str(udir / "module_cache" / "pypyapi")) modulename = py.path.local(eci.libraries[-1]) run_bootstrap_functions(space) # load the bridge, and init structure import ctypes bridge = ctypes.CDLL(str(modulename), mode=ctypes.RTLD_GLOBAL) # populate static data for name, (typ, expr) in GLOBALS.iteritems(): from pypy.module import cpyext w_obj = eval(expr) if name.endswith('#'): name = name[:-1] isptr = False else: isptr = True if name.startswith('PyExc_'): isptr = False INTERPLEVEL_API[name] = w_obj name = name.replace('Py', 'PyPy') if isptr: ptr = ctypes.c_void_p.in_dll(bridge, name) ptr.value = ctypes.cast(ll2ctypes.lltype2ctypes(make_ref(space, w_obj)), ctypes.c_void_p).value elif typ in ('PyObject*', 'PyTypeObject*'): in_dll = ll2ctypes.get_ctypes_type(PyObject).in_dll(bridge, name) if name.startswith('PyPyExc_'): # we already have the pointer py_obj = ll2ctypes.ctypes2lltype(PyObject, in_dll) else: # we have a structure, get its address py_obj = ll2ctypes.ctypes2lltype(PyObject, ctypes.pointer(in_dll)) from pypy.module.cpyext.pyobject import ( track_reference, get_typedescr) w_type = space.type(w_obj) typedescr = get_typedescr(w_type.instancetypedef) py_obj.c_ob_refcnt = 1 py_obj.c_ob_type = rffi.cast(PyTypeObjectPtr, make_ref(space, w_type)) typedescr.attach(space, py_obj, w_obj) track_reference(space, py_obj, w_obj) else: assert False, "Unknown static object: %s %s" % (typ, name) pypyAPI = ctypes.POINTER(ctypes.c_void_p).in_dll(bridge, 'pypyAPI') # implement structure initialization code for name, func in FUNCTIONS.iteritems(): if name.startswith('cpyext_'): # XXX hack continue pypyAPI[structindex[name]] = ctypes.cast( ll2ctypes.lltype2ctypes(func.get_llhelper(space)), ctypes.c_void_p) setup_va_functions(eci) setup_init_functions(eci) return modulename.new(ext='')
total = 0
total = %d
def f(a,b): if a < 0: return -1 return a-b
''', 170, ([], 4999450000L))
''' % startvalue, 170, ([], startvalue + 4999450000L))
def f(a,b): if a < 0: return -1 return a-b
target = target_ofs-arch.PC_OFFSET/2
def B_offs(self, target_ofs, c=cond.AL): target = target_ofs-arch.PC_OFFSET/2 pos = self.currpos() if target_ofs > pos: raise NotImplementedError else: if target >= 0 and target <= 0xFF: pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2 self.SUB_ri(reg.pc.value, reg.pc.value, target, cond=c) else: assert c == cond.AL self.LDR_ri(reg.ip.value, reg.pc.value, cond=c) self.SUB_rr(reg.pc.value, reg.pc.value, reg.ip.value, cond=c) pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2 self.write32(target)
pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2
def B_offs(self, target_ofs, c=cond.AL): target = target_ofs-arch.PC_OFFSET/2 pos = self.currpos() if target_ofs > pos: raise NotImplementedError else: if target >= 0 and target <= 0xFF: pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2 self.SUB_ri(reg.pc.value, reg.pc.value, target, cond=c) else: assert c == cond.AL self.LDR_ri(reg.ip.value, reg.pc.value, cond=c) self.SUB_rr(reg.pc.value, reg.pc.value, reg.ip.value, cond=c) pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2 self.write32(target)
pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2
target += 2 * WORD
def B_offs(self, target_ofs, c=cond.AL): target = target_ofs-arch.PC_OFFSET/2 pos = self.currpos() if target_ofs > pos: raise NotImplementedError else: if target >= 0 and target <= 0xFF: pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2 self.SUB_ri(reg.pc.value, reg.pc.value, target, cond=c) else: assert c == cond.AL self.LDR_ri(reg.ip.value, reg.pc.value, cond=c) self.SUB_rr(reg.pc.value, reg.pc.value, reg.ip.value, cond=c) pos = self.currpos() target_ofs = pos - target_ofs target = WORD + target_ofs + arch.PC_OFFSET/2 self.write32(target)
ResOperation(rop.DEBUG_MERGE_POINT, ['dummy'], None),
ResOperation(rop.DEBUG_MERGE_POINT, ['dummy', 2], None),
def test_get_rid_of_debug_merge_point(self): operations = [ ResOperation(rop.DEBUG_MERGE_POINT, ['dummy'], None), ] gc_ll_descr = self.gc_ll_descr gc_ll_descr.rewrite_assembler(None, operations) assert len(operations) == 0
assert space.unwrap(space.str(w_date)) == '1970-01-01'
date = datetime.date.fromtimestamp(0) assert space.unwrap(space.str(w_date)) == str(date)
def test_fromtimestamp(self, space, api): w_args = space.wrap((0,)) w_date = api.PyDate_FromTimestamp(w_args) assert space.unwrap(space.str(w_date)) == '1970-01-01'
si.hStdInput = startup_info.hStdInput.handle
si.hStdInput = int(startup_info.hStdInput)
def CreateProcess(name, command_line, process_attr, thread_attr, inherit, flags, env, start_dir, startup_info): si = _STARTUPINFO() if startup_info is not None: si.dwFlags = startup_info.dwFlags si.wShowWindow = startup_info.wShowWindow if startup_info.hStdInput: si.hStdInput = startup_info.hStdInput.handle if startup_info.hStdOutput: si.hStdOutput = startup_info.hStdOutput.handle if startup_info.hStdError: si.hStdError = startup_info.hStdError.handle pi = _PROCESS_INFORMATION() if env is not None: envbuf = "" for k, v in env.iteritems(): envbuf += "%s=%s\0" % (k, v) envbuf += '\0' else: envbuf = None res = _CreateProcess(name, command_line, None, None, inherit, flags, envbuf, start_dir, _byref(si), _byref(pi)) if not res: raise WindowsError("Error") return _handle(pi.hProcess), _handle(pi.hThread), pi.dwProcessID, pi.dwThreadID
si.hStdOutput = startup_info.hStdOutput.handle
si.hStdOutput = int(startup_info.hStdOutput)
def CreateProcess(name, command_line, process_attr, thread_attr, inherit, flags, env, start_dir, startup_info): si = _STARTUPINFO() if startup_info is not None: si.dwFlags = startup_info.dwFlags si.wShowWindow = startup_info.wShowWindow if startup_info.hStdInput: si.hStdInput = startup_info.hStdInput.handle if startup_info.hStdOutput: si.hStdOutput = startup_info.hStdOutput.handle if startup_info.hStdError: si.hStdError = startup_info.hStdError.handle pi = _PROCESS_INFORMATION() if env is not None: envbuf = "" for k, v in env.iteritems(): envbuf += "%s=%s\0" % (k, v) envbuf += '\0' else: envbuf = None res = _CreateProcess(name, command_line, None, None, inherit, flags, envbuf, start_dir, _byref(si), _byref(pi)) if not res: raise WindowsError("Error") return _handle(pi.hProcess), _handle(pi.hThread), pi.dwProcessID, pi.dwThreadID
si.hStdError = startup_info.hStdError.handle
si.hStdError = int(startup_info.hStdError)
def CreateProcess(name, command_line, process_attr, thread_attr, inherit, flags, env, start_dir, startup_info): si = _STARTUPINFO() if startup_info is not None: si.dwFlags = startup_info.dwFlags si.wShowWindow = startup_info.wShowWindow if startup_info.hStdInput: si.hStdInput = startup_info.hStdInput.handle if startup_info.hStdOutput: si.hStdOutput = startup_info.hStdOutput.handle if startup_info.hStdError: si.hStdError = startup_info.hStdError.handle pi = _PROCESS_INFORMATION() if env is not None: envbuf = "" for k, v in env.iteritems(): envbuf += "%s=%s\0" % (k, v) envbuf += '\0' else: envbuf = None res = _CreateProcess(name, command_line, None, None, inherit, flags, envbuf, start_dir, _byref(si), _byref(pi)) if not res: raise WindowsError("Error") return _handle(pi.hProcess), _handle(pi.hThread), pi.dwProcessID, pi.dwThreadID
res = _WaitForSingleObject(handle.handle, milliseconds)
res = _WaitForSingleObject(int(handle), milliseconds)
def WaitForSingleObject(handle, milliseconds): res = _WaitForSingleObject(handle.handle, milliseconds) if res < 0: raise WindowsError("Error") return res
res = _GetExitCodeProcess(handle.handle, _byref(code))
res = _GetExitCodeProcess(int(handle), _byref(code))
def GetExitCodeProcess(handle): code = _c_int() res = _GetExitCodeProcess(handle.handle, _byref(code)) if not res: raise WindowsError("Error") return code.value
guard_nonnull(p1) [] guard_class(p1, ConstClass(node_vtable2)) []
guard_nonnull_class(p1, ConstClass(node_vtable2)) []
def test_bug_3(self): ops = """ [p1] guard_nonnull(p1) [] guard_class(p1, ConstClass(node_vtable2)) [] p2 = getfield_gc(p1, descr=nextdescr) guard_nonnull(12) [] guard_class(p2, ConstClass(node_vtable)) [] p3 = getfield_gc(p1, descr=otherdescr) guard_nonnull(12) [] guard_class(p3, ConstClass(node_vtable)) [] setfield_gc(p3, p2, descr=otherdescr) p1a = new_with_vtable(ConstClass(node_vtable2)) p2a = new_with_vtable(ConstClass(node_vtable)) p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) setfield_gc(p1a, p2a, descr=nextdescr) setfield_gc(p1a, p3a, descr=otherdescr) jump(p1a) """ preamble = """ [p1] guard_nonnull(p1) [] guard_class(p1, ConstClass(node_vtable2)) [] p2 = getfield_gc(p1, descr=nextdescr) guard_class(p2, ConstClass(node_vtable)) [] p3 = getfield_gc(p1, descr=otherdescr) guard_class(p3, ConstClass(node_vtable)) [] p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) setfield_gc(p3, p2, descr=otherdescr) jump(p2a, p3a) """ expected = """ [p2, p3] guard_class(p2, ConstClass(node_vtable)) [] guard_class(p3, ConstClass(node_vtable)) [] setfield_gc(p3, p2, descr=otherdescr) p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) p2a = new_with_vtable(ConstClass(node_vtable)) jump(p2a, p3a) """ self.optimize_loop(ops, expected) # XXX Virtual(node_vtable2, nextdescr=Not, otherdescr=Not)
p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) setfield_gc(p3, p2, descr=otherdescr) jump(p2a, p3a) """ expected = """ [p2, p3] guard_class(p2, ConstClass(node_vtable)) [] guard_class(p3, ConstClass(node_vtable)) []
def test_bug_3(self): ops = """ [p1] guard_nonnull(p1) [] guard_class(p1, ConstClass(node_vtable2)) [] p2 = getfield_gc(p1, descr=nextdescr) guard_nonnull(12) [] guard_class(p2, ConstClass(node_vtable)) [] p3 = getfield_gc(p1, descr=otherdescr) guard_nonnull(12) [] guard_class(p3, ConstClass(node_vtable)) [] setfield_gc(p3, p2, descr=otherdescr) p1a = new_with_vtable(ConstClass(node_vtable2)) p2a = new_with_vtable(ConstClass(node_vtable)) p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) setfield_gc(p1a, p2a, descr=nextdescr) setfield_gc(p1a, p3a, descr=otherdescr) jump(p1a) """ preamble = """ [p1] guard_nonnull(p1) [] guard_class(p1, ConstClass(node_vtable2)) [] p2 = getfield_gc(p1, descr=nextdescr) guard_class(p2, ConstClass(node_vtable)) [] p3 = getfield_gc(p1, descr=otherdescr) guard_class(p3, ConstClass(node_vtable)) [] p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) setfield_gc(p3, p2, descr=otherdescr) jump(p2a, p3a) """ expected = """ [p2, p3] guard_class(p2, ConstClass(node_vtable)) [] guard_class(p3, ConstClass(node_vtable)) [] setfield_gc(p3, p2, descr=otherdescr) p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) p2a = new_with_vtable(ConstClass(node_vtable)) jump(p2a, p3a) """ self.optimize_loop(ops, expected) # XXX Virtual(node_vtable2, nextdescr=Not, otherdescr=Not)
p2a = new_with_vtable(ConstClass(node_vtable)) jump(p2a, p3a) """ self.optimize_loop(ops, expected)
jump(p3a) """ expected = """ [p3a] p2 = new_with_vtable(ConstClass(node_vtable)) setfield_gc(p3a, p2, descr=otherdescr) p3anew = new_with_vtable(ConstClass(node_vtable)) escape(p3anew) jump(p3anew) """ self.optimize_loop(ops, expected, preamble)
def test_bug_3(self): ops = """ [p1] guard_nonnull(p1) [] guard_class(p1, ConstClass(node_vtable2)) [] p2 = getfield_gc(p1, descr=nextdescr) guard_nonnull(12) [] guard_class(p2, ConstClass(node_vtable)) [] p3 = getfield_gc(p1, descr=otherdescr) guard_nonnull(12) [] guard_class(p3, ConstClass(node_vtable)) [] setfield_gc(p3, p2, descr=otherdescr) p1a = new_with_vtable(ConstClass(node_vtable2)) p2a = new_with_vtable(ConstClass(node_vtable)) p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) setfield_gc(p1a, p2a, descr=nextdescr) setfield_gc(p1a, p3a, descr=otherdescr) jump(p1a) """ preamble = """ [p1] guard_nonnull(p1) [] guard_class(p1, ConstClass(node_vtable2)) [] p2 = getfield_gc(p1, descr=nextdescr) guard_class(p2, ConstClass(node_vtable)) [] p3 = getfield_gc(p1, descr=otherdescr) guard_class(p3, ConstClass(node_vtable)) [] p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) setfield_gc(p3, p2, descr=otherdescr) jump(p2a, p3a) """ expected = """ [p2, p3] guard_class(p2, ConstClass(node_vtable)) [] guard_class(p3, ConstClass(node_vtable)) [] setfield_gc(p3, p2, descr=otherdescr) p3a = new_with_vtable(ConstClass(node_vtable)) escape(p3a) p2a = new_with_vtable(ConstClass(node_vtable)) jump(p2a, p3a) """ self.optimize_loop(ops, expected) # XXX Virtual(node_vtable2, nextdescr=Not, otherdescr=Not)
if Q >> BITS: raise ValueError("input out of range")
if not objectmodel.we_are_translated(): if Q >> BITS: raise ValueError("input out of range")
def float_unpack(Q, size): """Convert a 32-bit or 64-bit integer created by float_pack into a Python float.""" if size == 8: MIN_EXP = -1021 # = sys.float_info.min_exp MAX_EXP = 1024 # = sys.float_info.max_exp MANT_DIG = 53 # = sys.float_info.mant_dig BITS = 64 elif size == 4: MIN_EXP = -125 # C's FLT_MIN_EXP MAX_EXP = 128 # FLT_MAX_EXP MANT_DIG = 24 # FLT_MANT_DIG BITS = 32 else: raise ValueError("invalid size value") if Q >> BITS: raise ValueError("input out of range") # extract pieces one = r_ulonglong(1) sign = rarithmetic.intmask(Q >> BITS - 1) exp = rarithmetic.intmask((Q & ((one << BITS - 1) - (one << MANT_DIG - 1))) >> MANT_DIG - 1) mant = Q & ((1 << MANT_DIG - 1) - 1) if exp == MAX_EXP - MIN_EXP + 2: # nan or infinity result = float('nan') if mant else float('inf') elif exp == 0: # subnormal or zero result = math.ldexp(mant, MIN_EXP - MANT_DIG) else: # normal mant += 1 << MANT_DIG - 1 result = math.ldexp(mant, exp + MIN_EXP - MANT_DIG - 1) return -result if sign else result
pass
return False
def note_import_star(self, imp): """Called when a star import is found.""" pass
if op == "-":
elif op == "-":
def f(code, n): pc = 0 while pc < len(code):
if op == "c":
elif op == "c":
def f(code, n): pc = 0 while pc < len(code):
expected = """
preamble = """
def test_mul_ovf(self): ops = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_lt(i1, 5) guard_true(i3) [] i4 = int_gt(i1, -10) guard_true(i4) [] i5 = int_mul_ovf(i2, i1) guard_no_overflow() [] i6 = int_lt(i5, -2550) guard_false(i6) [] i7 = int_ge(i5, 1276) guard_false(i7) [] i8 = int_gt(i5, 126) guard_true(i8) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_lt(i1, 5) guard_true(i3) [] i4 = int_gt(i1, -10) guard_true(i4) [] i5 = int_mul(i2, i1) i8 = int_gt(i5, 126) guard_true(i8) [] jump(i0, i1) """ self.optimize_loop(ops, expected)
self.optimize_loop(ops, expected)
expected = """ [i0, i1] jump(i0, i1) """ self.optimize_loop(ops, expected, preamble)
def test_mul_ovf(self): ops = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_lt(i1, 5) guard_true(i3) [] i4 = int_gt(i1, -10) guard_true(i4) [] i5 = int_mul_ovf(i2, i1) guard_no_overflow() [] i6 = int_lt(i5, -2550) guard_false(i6) [] i7 = int_ge(i5, 1276) guard_false(i7) [] i8 = int_gt(i5, 126) guard_true(i8) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_lt(i1, 5) guard_true(i3) [] i4 = int_gt(i1, -10) guard_true(i4) [] i5 = int_mul(i2, i1) i8 = int_gt(i5, 126) guard_true(i8) [] jump(i0, i1) """ self.optimize_loop(ops, expected)
expected = """
preamble = """
def test_mul_ovf_before(self): ops = """ [i0, i1] i2 = int_and(i0, 255) i22 = int_add(i2, 1) i3 = int_mul_ovf(i22, i1) guard_no_overflow() [] i4 = int_lt(i3, 10) guard_true(i4) [] i5 = int_gt(i3, 2) guard_true(i5) [] i6 = int_lt(i1, 0) guard_false(i6) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_and(i0, 255) i22 = int_add(i2, 1) i3 = int_mul_ovf(i22, i1) guard_no_overflow() [] i4 = int_lt(i3, 10) guard_true(i4) [] i5 = int_gt(i3, 2) guard_true(i5) [] jump(i0, i1) """ self.optimize_loop(ops, expected)
jump(i0, i1) """ self.optimize_loop(ops, expected)
jump(i0, i1, i22) """ expected = """ [i0, i1, i22] i3 = int_mul(i22, i1) i4 = int_lt(i3, 10) guard_true(i4) [] i5 = int_gt(i3, 2) guard_true(i5) [] jump(i0, i1, i22) """ self.optimize_loop(ops, expected, preamble)
def test_mul_ovf_before(self): ops = """ [i0, i1] i2 = int_and(i0, 255) i22 = int_add(i2, 1) i3 = int_mul_ovf(i22, i1) guard_no_overflow() [] i4 = int_lt(i3, 10) guard_true(i4) [] i5 = int_gt(i3, 2) guard_true(i5) [] i6 = int_lt(i1, 0) guard_false(i6) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_and(i0, 255) i22 = int_add(i2, 1) i3 = int_mul_ovf(i22, i1) guard_no_overflow() [] i4 = int_lt(i3, 10) guard_true(i4) [] i5 = int_gt(i3, 2) guard_true(i5) [] jump(i0, i1) """ self.optimize_loop(ops, expected)
expected = """
preamble = """
def test_sub_ovf_before(self): ops = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_sub_ovf(i2, i1) guard_no_overflow() [] i4 = int_le(i3, 10) guard_true(i4) [] i5 = int_ge(i3, 2) guard_true(i5) [] i6 = int_lt(i1, -10) guard_false(i6) [] i7 = int_gt(i1, 253) guard_false(i7) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_sub_ovf(i2, i1) guard_no_overflow() [] i4 = int_le(i3, 10) guard_true(i4) [] i5 = int_ge(i3, 2) guard_true(i5) [] jump(i0, i1) """ self.optimize_loop(ops, expected)
jump(i0, i1) """ self.optimize_loop(ops, expected)
jump(i0, i1, i2) """ expected = """ [i0, i1, i2] i3 = int_sub(i2, i1) i4 = int_le(i3, 10) guard_true(i4) [] i5 = int_ge(i3, 2) guard_true(i5) [] jump(i0, i1, i2) """ self.optimize_loop(ops, expected, preamble)
def test_sub_ovf_before(self): ops = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_sub_ovf(i2, i1) guard_no_overflow() [] i4 = int_le(i3, 10) guard_true(i4) [] i5 = int_ge(i3, 2) guard_true(i5) [] i6 = int_lt(i1, -10) guard_false(i6) [] i7 = int_gt(i1, 253) guard_false(i7) [] jump(i0, i1) """ expected = """ [i0, i1] i2 = int_and(i0, 255) i3 = int_sub_ovf(i2, i1) guard_no_overflow() [] i4 = int_le(i3, 10) guard_true(i4) [] i5 = int_ge(i3, 2) guard_true(i5) [] jump(i0, i1) """ self.optimize_loop(ops, expected)
print "AFA CONTINUE", bufSize, retDataSize[0]
def QueryValueEx(space, w_hkey, w_subkey): """value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key.
print "AFA OK", bufSize, retDataSize[0]
def QueryValueEx(space, w_hkey, w_subkey): """value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key.
rstack.resume_point("CALL_METHOD", f, returns=w_result)
rstack.resume_point("CALL_METHOD", f, w_self, returns=w_result)
def CALL_METHOD(f, oparg, *ignored): # opargs contains the arg, and kwarg count, excluding the implicit 'self' n_args = oparg & 0xff n_kwargs = (oparg >> 8) & 0xff w_self = f.peekvalue(n_args + (2 * n_kwargs)) w_callable = f.peekvalue(n_args + (2 * n_kwargs) + 1) n = n_args + (w_self is not None) if not n_kwargs: try: w_result = f.space.call_valuestack(w_callable, n, f) rstack.resume_point("CALL_METHOD", f, n_args, returns=w_result) finally: f.dropvalues(n_args + 2) else: keywords = [None] * n_kwargs keywords_w = [None] * n_kwargs while True: n_kwargs -= 1 if n_kwargs < 0: break w_value = f.popvalue() w_key = f.popvalue() key = f.space.str_w(w_key) keywords[n_kwargs] = key keywords_w[n_kwargs] = w_value arguments = f.popvalues(n) args = f.argument_factory(arguments, keywords, keywords_w, None, None) try: w_result = f.space.call_args(w_callable, args) rstack.resume_point("CALL_METHOD", f, returns=w_result) finally: f.dropvalues(1 + (w_self is None)) f.pushvalue(w_result)
self.mc.MOV_rr(bytes_loc.value, length_loc.value) self._load_address(length_loc, 0, scale, bytes_loc)
self.mc.MOV_ri(r.ip.value, 1<<scale) self.mc.MUL(bytes_loc.value, r.ip.value, length_loc.value)
def _emit_copystrcontent(self, op, regalloc, fcond, is_unicode): # compute the source address args = list(op.getarglist()) base_loc, box = self._ensure_value_is_boxed(args[0], regalloc, args) args.append(box) ofs_loc, box = self._ensure_value_is_boxed(args[2], regalloc, args) args.append(box) assert args[0] is not args[1] # forbidden case of aliasing regalloc.possibly_free_var(args[0]) if args[3] is not args[2] is not args[4]: # MESS MESS MESS: don't free regalloc.possibly_free_var(args[2]) # it if ==args[3] or args[4] srcaddr_box = TempBox() forbidden_vars = [args[1], args[3], args[4], srcaddr_box] srcaddr_loc = regalloc.force_allocate_reg(srcaddr_box, forbidden_vars) self._gen_address_inside_string(base_loc, ofs_loc, srcaddr_loc, is_unicode=is_unicode)
def _load_address(self, sizereg, baseofs, scale, result, baseloc=None): if baseloc is not None: assert baseloc.is_reg() self.mc.MOV_rr(result.value, baseloc.value) else: self.mc.MOV_ri(result.value, 0) assert sizereg.is_reg() if scale > 0: self.mc.LSL_ri(r.ip.value, sizereg.value, scale) else: self.mc.MOV_rr(r.ip.value, sizereg.value) self.mc.ADD_rr(result.value, result.value, r.ip.value) self.mc.ADD_ri(result.value, result.value, baseofs)
def _load_address(self, sizereg, baseofs, scale, result, baseloc=None): if baseloc is not None: assert baseloc.is_reg() self.mc.MOV_rr(result.value, baseloc.value) else: self.mc.MOV_ri(result.value, 0) assert sizereg.is_reg() if scale > 0: self.mc.LSL_ri(r.ip.value, sizereg.value, scale) else: self.mc.MOV_rr(r.ip.value, sizereg.value) self.mc.ADD_rr(result.value, result.value, r.ip.value) self.mc.ADD_ri(result.value, result.value, baseofs)
self._load_address(ofsloc, ofs_items, scale, resloc, baseloc)
self._gen_address(ofsloc, ofs_items, scale, resloc, baseloc) def _gen_address(self, sizereg, baseofs, scale, result, baseloc=None): assert sizereg.is_reg() if scale > 0: scaled_loc = r.ip self.mc.LSL_ri(r.ip.value, sizereg.value, scale) else: scaled_loc = sizereg if baseloc is not None: assert baseloc.is_reg() self.mc.ADD_rr(result.value, baseloc.value, scaled_loc.value) self.mc.ADD_ri(result.value, result.value, baseofs) else: self.mc.ADD_ri(result.value, scaled_loc.value, baseofs)
def _gen_address_inside_string(self, baseloc, ofsloc, resloc, is_unicode): cpu = self.cpu if is_unicode: ofs_items, _, _ = symbolic.get_array_token(rstr.UNICODE, self.cpu.translate_support_code) scale = self._get_unicode_item_scale() else: ofs_items, itemsize, _ = symbolic.get_array_token(rstr.STR, self.cpu.translate_support_code) assert itemsize == 1 scale = 0 self._load_address(ofsloc, ofs_items, scale, resloc, baseloc)
assert type(wrapper_func_kwds) is not str
assert not isinstance(wrapper_func_kwds, str)
def __init__(self, space, pto, method_name, wrapper_func, wrapper_func_kwds, doc, func): self.space = space self.method_name = method_name self.wrapper_func = wrapper_func assert type(wrapper_func_kwds) is not str self.wrapper_func_kwds = wrapper_func_kwds self.doc = doc self.func = func pyo = rffi.cast(PyObject, pto) self.w_objclass = from_ref(space, pyo)
self.header(shadow).tid = 0
self.header(shadow).tid = self.header(obj).tid typeid = self.get_type_id(obj) if self.is_varsize(typeid): lenofs = self.varsize_offset_to_length(typeid) (shadow + lenofs).signed[0] = (obj + lenofs).signed[0]
def id_or_identityhash(self, gcobj, special_case_prebuilt): """Implement the common logic of id() and identityhash() of an object, given as a GCREF. """ obj = llmemory.cast_ptr_to_adr(gcobj) # if self.is_valid_gc_object(obj): if self.is_in_nursery(obj): # # The object is not a tagged pointer, and it is still in the # nursery. Find or allocate a "shadow" object, which is # where the object will be moved by the next minor # collection if self.header(obj).tid & GCFLAG_HAS_SHADOW: shadow = self.young_objects_shadows.get(obj) ll_assert(shadow != NULL, "GCFLAG_HAS_SHADOW but no shadow found") else: size_gc_header = self.gcheaderbuilder.size_gc_header size = self.get_size(obj) shadowhdr = self._malloc_out_of_nursery(size_gc_header + size) # initialize to an invalid tid *without* GCFLAG_VISITED, # so that if the object dies before the next minor # collection, the shadow will stay around but be collected # by the next major collection. shadow = shadowhdr + size_gc_header self.header(shadow).tid = 0 self.header(obj).tid |= GCFLAG_HAS_SHADOW self.young_objects_shadows.setitem(obj, shadow) # # The answer is the address of the shadow. obj = shadow # elif special_case_prebuilt: if self.header(obj).tid & GCFLAG_HAS_SHADOW: # # For identityhash(), we need a special case for some # prebuilt objects: their hash must be the same before # and after translation. It is stored as an extra word # after the object. But we cannot use it for id() # because the stored value might clash with a real one. size = self.get_size(obj) return (obj + size).signed[0] # return llmemory.cast_adr_to_int(obj)
lifeline = w_obj.get_pyolifeline()
lifeline = api.lifeline_dict.get(w_obj)
def check_and_print_leaks(self): # check for sane refcnts leaking = False state = self.space.fromcache(State) import gc gc.collect() lost_objects_w = identity_dict() lost_objects_w.update((key, None) for key in self.frozen_refcounts.keys()) for w_obj, obj in state.py_objects_w2r.iteritems(): base_refcnt = self.frozen_refcounts.get(w_obj) delta = obj.c_ob_refcnt if base_refcnt is not None: delta -= base_refcnt lost_objects_w.pop(w_obj) if delta != 0: leaking = True print >>sys.stderr, "Leaking %r: %i references" % (w_obj, delta) lifeline = w_obj.get_pyolifeline() if lifeline is not None: refcnt = lifeline.pyo.c_ob_refcnt if refcnt > 0: print >>sys.stderr, "\tThe object also held by C code." else: referrers_repr = [] for o in gc.get_referrers(w_obj): try: repr_str = repr(o) except TypeError, e: repr_str = "%s (type of o is %s)" % (str(e), type(o)) referrers_repr.append(repr_str) referrers = ", ".join(referrers_repr) print >>sys.stderr, "\tThe object is referenced by these objects:", \ referrers for w_obj in lost_objects_w: print >>sys.stderr, "Lost object %r" % (w_obj, ) leaking = True for llvalue in set(ll2ctypes.ALLOCATED.values()) - self.frozen_ll2callocations: if getattr(llvalue, "_traceback", None): # this means that the allocation should be tracked leaking = True print >>sys.stderr, "Did not deallocate %r (ll2ctypes)" % (llvalue, ) print >>sys.stderr, "\t" + "\n\t".join(llvalue._traceback.splitlines()) for llvalue in set_difference(lltype.ALLOCATED, self.frozen_lltallocations).keys(): leaking = True print >>sys.stderr, "Did not deallocate %r (llvalue)" % (llvalue, ) print >>sys.stderr, "\t" + "\n\t".join(llvalue._traceback.splitlines()) return leaking
self.optimize_strunicode_loop(ops, expected)
self.optimize_strunicode_loop(ops, expected, expected)
def test_bound_strlen(self): ops = """ [p0] i0 = strlen(p0) i1 = int_ge(i0, 0) guard_true(i1) [] jump(p0) """ # The dead strlen will be eliminated be the backend. expected = """ [p0] i0 = strlen(p0) jump(p0) """ self.optimize_strunicode_loop(ops, expected)
libc = CDLL('libc.so.6')
from pypy.rpython.lltypesystem.ll2ctypes import libc_name libc = CDLL(libc_name)
def test_call_to_c_function(self): from pypy.rlib.libffi import CDLL, types, ArgChain libc = CDLL('libc.so.6') c_tolower = libc.getpointer('tolower', [types.uchar], types.sint) argchain = ArgChain().arg(ord('A')) assert c_tolower.call(argchain, rffi.INT) == ord('a')
visit_cmove = binary_insn visit_cmovne = binary_insn visit_cmovg = binary_insn visit_cmovge = binary_insn visit_cmovl = binary_insn visit_cmovle = binary_insn visit_cmova = binary_insn visit_cmovae = binary_insn visit_cmovb = binary_insn visit_cmovbe = binary_insn visit_cmovp = binary_insn visit_cmovnp = binary_insn visit_cmovs = binary_insn visit_cmovns = binary_insn visit_cmovo = binary_insn visit_cmovno = binary_insn
for name in ''' e ne g ge l le a ae b be p np s ns o no '''.split(): locals()['visit_cmov' + name] = binary_insn locals()['visit_cmov' + name + 'l'] = binary_insn
def binary_insn(self, line): match = self.r_binaryinsn.match(line) if not match: raise UnrecognizedOperation(line) source = match.group("source") target = match.group("target") if self.r_localvar.match(target): return InsnSetLocal(target, [source]) elif target == self.ESP: raise UnrecognizedOperation(line) else: return []
expr = '%s(%r%s)' %(func.__name__, args, k)
expr = '%s(%r%s)' %(getattr(func, '__name__', func), args, k)
def raises(ExpectedException, *args, **kwargs): """ raise AssertionError, if target code does not raise the expected exception. """ __tracebackhide__ = True assert args if isinstance(args[0], str): code, = args assert isinstance(code, str) frame = sys._getframe(1) loc = frame.f_locals.copy() loc.update(kwargs) #print "raises frame scope: %r" % frame.f_locals try: code = py.code.Source(code).compile() py.builtin.exec_(code, frame.f_globals, loc) # XXX didn'T mean f_globals == f_locals something special? # this is destroyed here ... except ExpectedException: return py.code.ExceptionInfo() else: func = args[0] try: func(*args[1:], **kwargs) except ExpectedException: return py.code.ExceptionInfo() k = ", ".join(["%s=%r" % x for x in kwargs.items()]) if k: k = ', ' + k expr = '%s(%r%s)' %(func.__name__, args, k) raise ExceptionFailure(msg="DID NOT RAISE", expr=args, expected=ExpectedException)
return _callinfo_for_oopspec[oopspecindex]
try: return _callinfo_for_oopspec[oopspecindex] except KeyError: return None
def callinfo_for_oopspec(oopspecindex): """A function that returns the calldescr and the function address (as an int) of one of the OS_XYZ functions defined above. Don't use this if there might be several implementations of the same OS_XYZ specialized by type, e.g. OS_ARRAYCOPY.""" return _callinfo_for_oopspec[oopspecindex]
rstack.resume_point("CALL_METHOD", f, w_self, returns=w_result)
rstack.resume_point("CALL_METHOD", f, returns=w_result)
def CALL_METHOD(f, oparg, *ignored): # opargs contains the arg, and kwarg count, excluding the implicit 'self' n_args = oparg & 0xff n_kwargs = (oparg >> 8) & 0xff w_self = f.peekvalue(n_args + (2 * n_kwargs)) w_callable = f.peekvalue(n_args + (2 * n_kwargs) + 1) n = n_args + (w_self is not None) if not n_kwargs: try: w_result = f.space.call_valuestack(w_callable, n, f) rstack.resume_point("CALL_METHOD", f, n_args, returns=w_result) finally: f.dropvalues(n_args + 2) else: keywords = [None] * n_kwargs keywords_w = [None] * n_kwargs while True: n_kwargs -= 1 if n_kwargs < 0: break w_value = f.popvalue() w_key = f.popvalue() key = f.space.str_w(w_key) keywords[n_kwargs] = key keywords_w[n_kwargs] = w_value arguments = f.popvalues(n) args = f.argument_factory(arguments, keywords, keywords_w, None, None) try: w_result = f.space.call_args(w_callable, args) rstack.resume_point("CALL_METHOD", f, w_self, returns=w_result) finally: f.dropvalues(1 + (w_self is None)) f.pushvalue(w_result)
skip("not working yet")
def test_new_exception(self): skip("not working yet") mod = self.import_extension('foo', [ ('newexc', 'METH_VARARGS', ''' char *name = PyString_AsString(PyTuple_GetItem(args, 0)); return PyExc_NewException(name, PyTuple_GetItem(args, 1), PyTuple_GetItem(args, 2)); ''' ), ]) raises(SystemError, mod.newexc, "name", Exception, {})
return PyExc_NewException(name, PyTuple_GetItem(args, 1),
return PyErr_NewException(name, PyTuple_GetItem(args, 1),
def test_new_exception(self): skip("not working yet") mod = self.import_extension('foo', [ ('newexc', 'METH_VARARGS', ''' char *name = PyString_AsString(PyTuple_GetItem(args, 0)); return PyExc_NewException(name, PyTuple_GetItem(args, 1), PyTuple_GetItem(args, 2)); ''' ), ]) raises(SystemError, mod.newexc, "name", Exception, {})
if 'getitem__Array' in graph.name: if len(inputcells) > 2 and isinstance(inputcells[1], annmodel.SomeInstance) and 'Base' in str(inputcells[1].classdef): import pdb pdb.set_trace() print graph print inputcells
def bindinputargs(self, graph, block, inputcells, called_from_graph=None): if 'getitem__Array' in graph.name: if len(inputcells) > 2 and isinstance(inputcells[1], annmodel.SomeInstance) and 'Base' in str(inputcells[1].classdef): import pdb pdb.set_trace() print graph print inputcells # Create the initial bindings for the input args of a block. assert len(block.inputargs) == len(inputcells) where = (graph, block, None) for a, cell in zip(block.inputargs, inputcells): self.setbinding(a, cell, called_from_graph, where=where) self.annotated[block] = False # must flowin. self.blocked_blocks[block] = graph
"""])
"""], export_symbols=['fn_test_result_of_call'])
def test_short_result_of_call_direct(self): # Test that calling a function that returns a CHAR, SHORT or INT, # signed or unsigned, properly gets zero-extended or sign-extended. from pypy.translator.tool.cbuild import ExternalCompilationInfo for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR, rffi.SHORT, rffi.USHORT, rffi.INT, rffi.UINT, rffi.LONG, rffi.ULONG]: # Tested with a function that intentionally does not cast the # result to RESTYPE, but makes sure that we return the whole # value in eax or rax. eci = ExternalCompilationInfo(separate_module_sources=[""" long fn_test_result_of_call(long x) { return x + 1; } """]) f = rffi.llexternal('fn_test_result_of_call', [lltype.Signed], RESTYPE, compilation_info=eci, _nowrapper=True) value = intmask(0xFFEEDDCCBBAA9988) expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value + 1)) assert intmask(f(value)) == expected # FUNC = self.FuncType([lltype.Signed], RESTYPE) FPTR = self.Ptr(FUNC) calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT) x = self.cpu.bh_call_i(self.get_funcbox(self.cpu, f).value, calldescr, [value], None, None) assert x == expected, ( "%r: got %r, expected %r" % (RESTYPE, x, expected))
"""])
"""], export_symbols=['fn_test_result_of_call'])
def test_short_result_of_call_compiled(self): # Test that calling a function that returns a CHAR, SHORT or INT, # signed or unsigned, properly gets zero-extended or sign-extended. from pypy.translator.tool.cbuild import ExternalCompilationInfo for RESTYPE in [rffi.SIGNEDCHAR, rffi.UCHAR, rffi.SHORT, rffi.USHORT, rffi.INT, rffi.UINT, rffi.LONG, rffi.ULONG]: # Tested with a function that intentionally does not cast the # result to RESTYPE, but makes sure that we return the whole # value in eax or rax. eci = ExternalCompilationInfo(separate_module_sources=[""" long fn_test_result_of_call(long x) { return x + 1; } """]) f = rffi.llexternal('fn_test_result_of_call', [lltype.Signed], RESTYPE, compilation_info=eci, _nowrapper=True) value = intmask(0xFFEEDDCCBBAA9988) expected = rffi.cast(lltype.Signed, rffi.cast(RESTYPE, value + 1)) assert intmask(f(value)) == expected # FUNC = self.FuncType([lltype.Signed], RESTYPE) FPTR = self.Ptr(FUNC) calldescr = self.cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT) funcbox = self.get_funcbox(self.cpu, f) res = self.execute_operation(rop.CALL, [funcbox, BoxInt(value)], 'int', descr=calldescr) assert res.value == expected, ( "%r: got %r, expected %r" % (RESTYPE, res.value, expected))
assert prefix.join('bin', 'pypy-c').check()
assert prefix.join('bin', 'pypy').check()
def test_dir_structure(test='test'): # make sure we have sort of pypy-c pypy_c = py.path.local(pypydir).join('translator', 'goal', 'pypy-c') if not pypy_c.check(): os.system("echo faked_pypy_c> %s" % (pypy_c,)) fake_pypy_c = True else: fake_pypy_c = False try: builddir = package(py.path.local(pypydir).dirpath(), test) prefix = builddir.join(test) cpyver = '%d.%d.%d' % CPYTHON_VERSION[:3] assert prefix.join('lib-python', cpyver, 'test').check() assert prefix.join('bin', 'pypy-c').check() assert prefix.join('lib_pypy', 'syslog.py').check() assert not prefix.join('lib_pypy', 'py').check() assert not prefix.join('lib_pypy', 'ctypes_configure').check() assert prefix.join('LICENSE').check() assert prefix.join('README').check() th = tarfile.open(str(builddir.join('%s.tar.bz2' % test))) assert th.getmember('%s/lib_pypy/syslog.py' % test) # the headers file could be not there, because they are copied into # trunk/include only during translation includedir = py.path.local(pypydir).dirpath().join('include') def check_include(name): if includedir.join(name).check(file=True): assert th.getmember('%s/include/%s' % (test, name)) check_include('Python.h') check_include('modsupport.inl') check_include('pypy_decl.h') finally: if fake_pypy_c: pypy_c.remove()
assert total0 + total == 10
assert total0 + total == 16
def heuristic(graph): for block in graph.iterblocks(): for op in block.operations: if op.opname in ('malloc',): return inline.inlining_heuristic(graph) return sys.maxint, False
virtuals=True)
not_a_bridge=True)
def optimize_loop(self, ops, spectext, optops): loop = self.parse(ops) # self.loop = loop metainterp_sd = FakeMetaInterpStaticData(self.cpu) if hasattr(self, 'vrefinfo'): metainterp_sd.virtualref_info = self.vrefinfo # # XXX list the exact optimizations that are needed for each test from pypy.jit.metainterp.optimizeopt import (OptIntBounds, OptRewrite, OptVirtualize, OptString, OptHeap, Optimizer) optimizations = [OptIntBounds(), OptRewrite(), OptVirtualize(), OptString(), OptHeap(), ] optimizer = Optimizer(metainterp_sd, loop, optimizations, virtuals=True) optimizer.propagate_all_forward() # expected = self.parse(optops) print '\n'.join([str(o) for o in loop.operations]) self.assert_equal(loop, expected)
split_one_loop(real_loops, 'Guard5', 'extra')
split_one_loop(real_loops, 'Guard5', 'extra', 1)
def test_split_one_loop(self): real_loops = [FinalBlock(preparse(""" p21 = getfield_gc(p4, descr=<GcPtrFieldDescr 16>) guard_class(p4, 141310752, descr=<Guard51>) [p0, p1] """), None), FinalBlock(preparse(""" p60 = getfield_gc(p4, descr=<GcPtrFieldDescr 16>) guard_nonnull(p60, descr=<Guard5>) [p0, p1] """), None)] split_one_loop(real_loops, 'Guard5', 'extra') assert isinstance(real_loops[1], Block) assert real_loops[1].content.endswith('p1]') assert real_loops[1].left.content == '' assert real_loops[1].right.content.startswith('guard_nonnull')
assert real_loops[0].content.startswith("_runCallbacks, file '/tmp/x/twisted-trunk/twisted/internet/defer.py', line 357")
assert real_loops[0].header.startswith("_runCallbacks, file '/tmp/x/twisted-trunk/twisted/internet/defer.py', line 357")
def test_postparse(self): real_loops = [FinalBlock("debug_merge_point('<code object _runCallbacks, file '/tmp/x/twisted-trunk/twisted/internet/defer.py', line 357> #40 POP_TOP')", None)] postprocess(real_loops) assert real_loops[0].content.startswith("_runCallbacks, file '/tmp/x/twisted-trunk/twisted/internet/defer.py', line 357")
s, ord(c), self.fmtpos)
s, ord(c), self.fmtpos - 1)
def unknown_fmtchar(self): space = self.space c = self.fmt[self.fmtpos - 1] if do_unicode: w_defaultencoding = space.call_function( space.sys.get('getdefaultencoding')) w_s = space.call_method(space.wrap(c), "encode", w_defaultencoding, space.wrap('replace')) s = space.str_w(w_s) else: s = c msg = "unsupported format character '%s' (0x%x) at index %d" % ( s, ord(c), self.fmtpos) raise OperationError(space.w_ValueError, space.wrap(msg))
def __init__(self, color=None, width=None, block='█', empty=' '):
def __init__(self, color=None, width=None, block='.', empty=' '):
def __init__(self, color=None, width=None, block='█', empty=' '): """ color -- color name (BLUE GREEN CYAN RED MAGENTA YELLOW WHITE BLACK) width -- bar width (optinal) block -- progress display character (default '█') empty -- bar display character (default ' ') """ if color: self.color = getattr(terminal, color.upper()) else: self.color = '' if width and width < terminal.COLUMNS - self.PADDING: self.width = width else: # Adjust to the width of the terminal self.width = terminal.COLUMNS - self.PADDING self.block = block self.empty = empty self.progress = None self.lines = 0
block -- progress display character (default '█')
block -- progress display character (default '.')
def __init__(self, color=None, width=None, block='█', empty=' '): """ color -- color name (BLUE GREEN CYAN RED MAGENTA YELLOW WHITE BLACK) width -- bar width (optinal) block -- progress display character (default '█') empty -- bar display character (default ' ') """ if color: self.color = getattr(terminal, color.upper()) else: self.color = '' if width and width < terminal.COLUMNS - self.PADDING: self.width = width else: # Adjust to the width of the terminal self.width = terminal.COLUMNS - self.PADDING self.block = block self.empty = empty self.progress = None self.lines = 0
w_dem = space.newlong(1)
w_den = space.newlong(1)
def float_as_integer_ratio__Float(space, w_float): value = w_float.floatval if isinf(value): w_msg = space.wrap("cannot pass infinity to as_integer_ratio()") raise OperationError(space.w_OverflowError, w_msg) elif isnan(value): w_msg = space.wrap("cannot pass nan to as_integer_ratio()") raise OperationError(space.w_ValueError, w_msg) float_part, exp = math.frexp(value) for i in range(300): if float_part == math.floor(float_part): break float_part *= 2.0 exp -= 1 w_num = W_LongObject.fromfloat(float_part) w_dem = space.newlong(1) w_exp = space.newlong(abs(exp)) w_exp = space.lshift(w_dem, w_exp) if exp > 0: w_num = space.mul(w_num, w_exp) else: w_dem = w_exp # Try to return int. return space.newtuple([space.int(w_num), space.int(w_dem)])
w_exp = space.lshift(w_dem, w_exp)
w_exp = space.lshift(w_den, w_exp)
def float_as_integer_ratio__Float(space, w_float): value = w_float.floatval if isinf(value): w_msg = space.wrap("cannot pass infinity to as_integer_ratio()") raise OperationError(space.w_OverflowError, w_msg) elif isnan(value): w_msg = space.wrap("cannot pass nan to as_integer_ratio()") raise OperationError(space.w_ValueError, w_msg) float_part, exp = math.frexp(value) for i in range(300): if float_part == math.floor(float_part): break float_part *= 2.0 exp -= 1 w_num = W_LongObject.fromfloat(float_part) w_dem = space.newlong(1) w_exp = space.newlong(abs(exp)) w_exp = space.lshift(w_dem, w_exp) if exp > 0: w_num = space.mul(w_num, w_exp) else: w_dem = w_exp # Try to return int. return space.newtuple([space.int(w_num), space.int(w_dem)])
w_dem = w_exp
w_den = w_exp
def float_as_integer_ratio__Float(space, w_float): value = w_float.floatval if isinf(value): w_msg = space.wrap("cannot pass infinity to as_integer_ratio()") raise OperationError(space.w_OverflowError, w_msg) elif isnan(value): w_msg = space.wrap("cannot pass nan to as_integer_ratio()") raise OperationError(space.w_ValueError, w_msg) float_part, exp = math.frexp(value) for i in range(300): if float_part == math.floor(float_part): break float_part *= 2.0 exp -= 1 w_num = W_LongObject.fromfloat(float_part) w_dem = space.newlong(1) w_exp = space.newlong(abs(exp)) w_exp = space.lshift(w_dem, w_exp) if exp > 0: w_num = space.mul(w_num, w_exp) else: w_dem = w_exp # Try to return int. return space.newtuple([space.int(w_num), space.int(w_dem)])
return space.newtuple([space.int(w_num), space.int(w_dem)])
return space.newtuple([space.int(w_num), space.int(w_den)])
def float_as_integer_ratio__Float(space, w_float): value = w_float.floatval if isinf(value): w_msg = space.wrap("cannot pass infinity to as_integer_ratio()") raise OperationError(space.w_OverflowError, w_msg) elif isnan(value): w_msg = space.wrap("cannot pass nan to as_integer_ratio()") raise OperationError(space.w_ValueError, w_msg) float_part, exp = math.frexp(value) for i in range(300): if float_part == math.floor(float_part): break float_part *= 2.0 exp -= 1 w_num = W_LongObject.fromfloat(float_part) w_dem = space.newlong(1) w_exp = space.newlong(abs(exp)) w_exp = space.lshift(w_dem, w_exp) if exp > 0: w_num = space.mul(w_num, w_exp) else: w_dem = w_exp # Try to return int. return space.newtuple([space.int(w_num), space.int(w_dem)])
self.max_delta = 0.0
self.max_delta = float(r_uint(-1))
def __init__(self, config, read_from_env=False, nursery_size=32*WORD, page_size=16*WORD, arena_size=64*WORD, small_request_threshold=5*WORD, major_collection_threshold=2.5, growth_rate_max=2.5, # for tests card_page_indices=0, large_object=8*WORD, large_object_gcptrs=10*WORD, ArenaCollectionClass=None, **kwds): MovingGCBase.__init__(self, config, **kwds) assert small_request_threshold % WORD == 0 self.read_from_env = read_from_env self.nursery_size = nursery_size self.small_request_threshold = small_request_threshold self.major_collection_threshold = major_collection_threshold self.growth_rate_max = growth_rate_max self.num_major_collects = 0 self.min_heap_size = 0.0 self.max_heap_size = 0.0 self.max_heap_size_already_raised = False self.max_delta = 0.0 # self.card_page_indices = card_page_indices if self.card_page_indices > 0: self.card_page_shift = 0 while (1 << self.card_page_shift) < self.card_page_indices: self.card_page_shift += 1 # # 'large_object' and 'large_object_gcptrs' limit how big objects # can be in the nursery, so they give a lower bound on the allowed # size of the nursery. self.nonlarge_max = large_object - 1 self.nonlarge_gcptrs_max = large_object_gcptrs - 1 assert self.nonlarge_max <= self.nonlarge_gcptrs_max # self.nursery = NULL self.nursery_free = NULL self.nursery_top = NULL self.debug_always_do_minor_collect = False # # The ArenaCollection() handles the nonmovable objects allocation. if ArenaCollectionClass is None: ArenaCollectionClass = minimarkpage.ArenaCollection self.ac = ArenaCollectionClass(arena_size, page_size, small_request_threshold) # # Used by minor collection: a list of non-young objects that # (may) contain a pointer to a young object. Populated by # the write barrier. self.old_objects_pointing_to_young = self.AddressStack() # # Similar to 'old_objects_pointing_to_young', but lists objects # that have the GCFLAG_CARDS_SET bit. For large arrays. Note # that it is possible for an object to be listed both in here # and in 'old_objects_pointing_to_young', in which case we # should just clear the cards and trace it fully, as usual. self.old_objects_with_cards_set = self.AddressStack() # # A list of all prebuilt GC objects that contain pointers to the heap self.prebuilt_root_objects = self.AddressStack() # self._init_writebarrier_logic()
if self.max_delta > 0.0: threshold_max = min(threshold_max, self.next_major_collection_threshold + self.max_delta)
def set_major_threshold_from(self, threshold, reserving_size=0): # Set the next_major_collection_threshold. threshold_max = (self.next_major_collection_threshold * self.growth_rate_max) if self.max_delta > 0.0: threshold_max = min(threshold_max, self.next_major_collection_threshold + self.max_delta) if threshold > threshold_max: threshold = threshold_max # threshold += reserving_size if threshold < self.min_heap_size: threshold = self.min_heap_size # if self.max_heap_size > 0.0 and threshold > self.max_heap_size: threshold = self.max_heap_size bounded = True else: bounded = False # self.next_major_collection_threshold = threshold return bounded
self.get_total_memory_used() * self.major_collection_threshold,
min(total_memory_used * self.major_collection_threshold, total_memory_used + self.max_delta),
def major_collection(self, reserving_size=0): """Do a major collection. Only for when the nursery is empty.""" # debug_start("gc-collect") debug_print() debug_print(".----------- Full collection ------------------") debug_print("| used before collection:") debug_print("| in ArenaCollection: ", self.ac.total_memory_used, "bytes") debug_print("| raw_malloced: ", self.rawmalloced_total_size, "bytes") # # Debugging checks ll_assert(self.nursery_free == self.nursery, "nursery not empty in major_collection()") self.debug_check_consistency() # # Note that a major collection is non-moving. The goal is only to # find and free some of the objects allocated by the ArenaCollection. # We first visit all objects and toggle the flag GCFLAG_VISITED on # them, starting from the roots. self.objects_to_trace = self.AddressStack() self.collect_roots() self.visit_all_objects() # # Finalizer support: adds the flag GCFLAG_VISITED to all objects # with a finalizer and all objects reachable from there (and also # moves some objects from 'objects_with_finalizers' to # 'run_finalizers'). if self.objects_with_finalizers.non_empty(): self.deal_with_objects_with_finalizers() # self.objects_to_trace.delete() # # Weakref support: clear the weak pointers to dying objects if self.old_objects_with_weakrefs.non_empty(): self.invalidate_old_weakrefs() # # Walk all rawmalloced objects and free the ones that don't # have the GCFLAG_VISITED flag. self.free_unvisited_rawmalloc_objects() # # Ask the ArenaCollection to visit all objects. Free the ones # that have not been visited above, and reset GCFLAG_VISITED on # the others. self.ac.mass_free(self._free_if_unvisited) # # We also need to reset the GCFLAG_VISITED on prebuilt GC objects. self.prebuilt_root_objects.foreach(self._reset_gcflag_visited, None) # self.debug_check_consistency() # self.num_major_collects += 1 debug_print("| used after collection:") debug_print("| in ArenaCollection: ", self.ac.total_memory_used, "bytes") debug_print("| raw_malloced: ", self.rawmalloced_total_size, "bytes") debug_print("| number of major collects: ", self.num_major_collects) debug_print("`----------------------------------------------") debug_stop("gc-collect") # # Set the threshold for the next major collection to be when we # have allocated 'major_collection_threshold' times more than # we currently have. bounded = self.set_major_threshold_from( self.get_total_memory_used() * self.major_collection_threshold, reserving_size) # # Max heap size: gives an upper bound on the threshold. If we # already have at least this much allocated, raise MemoryError. if bounded and (float(self.get_total_memory_used()) + reserving_size >= self.next_major_collection_threshold): # # First raise MemoryError, giving the program a chance to # quit cleanly. It might still allocate in the nursery, # which might eventually be emptied, triggering another # major collect and (possibly) reaching here again with an # even higher memory consumption. To prevent it, if it's # the second time we are here, then abort the program. if self.max_heap_size_already_raised: llop.debug_fatalerror(lltype.Void, "Using too much memory, aborting") self.max_heap_size_already_raised = True raise MemoryError # # At the end, we can execute the finalizers of the objects # listed in 'run_finalizers'. Note that this will typically do # more allocations. self.execute_finalizers()
assert result == rctime.strftime('%m/%d/%y', t)
assert result == rctime.strftime('%m/%d/%y', tt)
def test_strftime_ext(self): import time as rctime
builder.append(unichr(chr))
builder.append(UNICHR(chr))
def hexescape(builder, s, pos, digits, encoding, errorhandler, message, errors): import sys chr = 0 if pos + digits > len(s): message = "end of string in escape sequence" res, pos = errorhandler(errors, "unicodeescape", message, s, pos-2, len(s)) builder.append(res) else: try: chr = r_uint(int(s[pos:pos+digits], 16)) except ValueError: endinpos = pos while s[endinpos] in hexdigits: endinpos += 1 res, pos = errorhandler(errors, encoding, message, s, pos-2, endinpos+1) builder.append(res) else: # when we get here, chr is a 32-bit unicode character if chr <= MAXUNICODE: builder.append(unichr(chr)) pos += digits elif chr <= 0x10ffff: chr -= 0x10000L builder.append(unichr(0xD800 + (chr >> 10))) builder.append(unichr(0xDC00 + (chr & 0x03FF))) pos += digits else: message = "illegal Unicode character" res, pos = errorhandler(errors, encoding, message, s, pos-2, pos+digits) builder.append(res) return pos
builder.append(unichr(code))
builder.append(UNICHR(code))
def str_decode_unicode_escape(s, size, errors, final=False, errorhandler=False, unicodedata_handler=None): if errorhandler is None: errorhandler = raise_unicode_exception_decode if size == 0: return u'', 0 builder = UnicodeBuilder(size) pos = 0 while pos < size: ch = s[pos] # Non-escape characters are interpreted as Unicode ordinals if ch != '\\': builder.append(unichr(ord(ch))) pos += 1 continue # - Escapes pos += 1 if pos >= size: message = "\\ at end of string" res, pos = errorhandler(errors, "unicodeescape", message, s, pos-1, size) builder.append(res) continue ch = s[pos] pos += 1 # \x escapes if ch == '\n': pass elif ch == '\\': builder.append(u'\\') elif ch == '\'': builder.append(u'\'') elif ch == '\"': builder.append(u'\"') elif ch == 'b' : builder.append(u'\b') elif ch == 'f' : builder.append(u'\f') elif ch == 't' : builder.append(u'\t') elif ch == 'n' : builder.append(u'\n') elif ch == 'r' : builder.append(u'\r') elif ch == 'v' : builder.append(u'\v') elif ch == 'a' : builder.append(u'\a') elif '0' <= ch <= '7': x = ord(ch) - ord('0') if pos < size: ch = s[pos] if '0' <= ch <= '7': pos += 1 x = (x<<3) + ord(ch) - ord('0') if pos < size: ch = s[pos] if '0' <= ch <= '7': pos += 1 x = (x<<3) + ord(ch) - ord('0') builder.append(unichr(x)) # hex escapes # \xXX elif ch == 'x': digits = 2 message = "truncated \\xXX escape" pos = hexescape(builder, s, pos, digits, "unicodeescape", errorhandler, message, errors) # \uXXXX elif ch == 'u': digits = 4 message = "truncated \\uXXXX escape" pos = hexescape(builder, s, pos, digits, "unicodeescape", errorhandler, message, errors) # \UXXXXXXXX elif ch == 'U': digits = 8 message = "truncated \\UXXXXXXXX escape" pos = hexescape(builder, s, pos, digits, "unicodeescape", errorhandler, message, errors) # \N{name} elif ch == 'N': message = "malformed \\N character escape" look = pos if unicodedata_handler is None: message = ("\\N escapes not supported " "(can't load unicodedata module)") res, pos = errorhandler(errors, "unicodeescape", message, s, pos-1, size) builder.append(res) continue if look < size and s[look] == '{': # look for the closing brace while look < size and s[look] != '}': look += 1 if look < size and s[look] == '}': # found a name. look it up in the unicode database message = "unknown Unicode character name" name = s[pos+1:look] code = unicodedata_handler.call(name) if code < 0: res, pos = errorhandler(errors, "unicodeescape", message, s, pos-1, look+1) builder.append(res) continue pos = look + 1 if code <= MAXUNICODE: builder.append(unichr(code)) else: code -= 0x10000L builder.append(unichr(0xD800 + (code >> 10))) builder.append(unichr(0xDC00 + (code & 0x03FF))) else: res, pos = errorhandler(errors, "unicodeescape", message, s, pos-1, look+1) builder.append(res) else: res, pos = errorhandler(errors, "unicodeescape", message, s, pos-1, look+1) builder.append(res) else: builder.append(u'\\') builder.append(unichr(ord(ch))) return builder.build(), pos
def __init__(self, *args): if args: raise Exception
def __init__(self, *args): if args: raise Exception
return [InsnStop(target), InsnCannotFollowEsp()]
return [InsnStop(target)]
def walker(insn, locs): sources = [] for loc in locs: for s in insn.all_sources_of(loc): sources.append(s) for source in sources: m = re.match("DWORD PTR " + self.LABEL, source) if m: reg.append(m.group(1)) if reg: return yield tuple(sources)
res = regalloc.force_allocate_reg(op.result, selected_reg=r.r0)
regalloc.before_call()
def f(self, op, regalloc, fcond): a0 = op.getarg(0) a1 = op.getarg(1) arg1 = regalloc.make_sure_var_in_reg(a0, selected_reg=r.r0, imm_fine=False) arg2 = regalloc.make_sure_var_in_reg(a1, [a0], selected_reg=r.r1, imm_fine=False) assert arg1 == r.r0 assert arg2 == r.r1 res = regalloc.force_allocate_reg(op.result, selected_reg=r.r0) getattr(self.mc, opname)(fcond) regalloc.possibly_free_vars_for_op(op) return fcond
presentation_type = default_type
the_type = default_type
def _parse_spec(self, default_type, default_align): space = self.space self._fill_char = self._lit("\0") self._align = default_align self._alternate = False self._sign = "\0" self._thousands_sep = False self._precision = -1 presentation_type = default_type spec = self.spec if not spec: return True length = len(spec) i = 0 got_align = True if length - i >= 2 and self._is_alignment(spec[i + 1]): self._align = spec[i + 1] self._fill_char = spec[i] i += 2 elif length - i >= 1 and self._is_alignment(spec[i]): self._align = spec[i] i += 1 else: got_align = False if length - i >= 1 and self._is_sign(spec[i]): self._sign = spec[i] i += 1 if length - i >= 1 and spec[i] == "#": self._alternate = True i += 1 if self._fill_char == "\0" and length - i >= 1 and spec[i] == "0": self._fill_char = self._lit("0") if not got_align: self._align = "=" i += 1 start_i = i self._width, i = _parse_int(self.space, spec, i, length) if length - i and spec[i] == ",": self._thousands_sep = True i += 1 if length - i and spec[i] == ".": i += 1 self._precision, i = _parse_int(self.space, spec, i, length) if self._precision == -1: raise OperationError(space.w_ValueError, space.wrap("no precision given")) if length - i > 1: raise OperationError(space.w_ValueError, space.wrap("invalid format spec")) if length - i == 1: presentation_type = spec[i] i += 1 if self.is_unicode: try: the_type = presentation_type.encode("ascii") except UnicodeEncodeError: raise OperationError(space.w_ValueError, space.wrap("invalid type")) else: the_type = presentation_type self._type = the_type if self._thousands_sep: tp = self._type if (tp == "d" or tp == "e" or tp == "f" or tp == "g" or tp == "E" or tp == "G" or tp == "%" or tp == "F" or tp == "\0"): # ok pass else: raise OperationError(space.w_ValueError, space.wrap("invalid type with ','")) return False
i += 1 if self.is_unicode: try: the_type = presentation_type.encode("ascii") except UnicodeEncodeError: raise OperationError(space.w_ValueError, space.wrap("invalid type")) else: the_type = presentation_type
if self.is_unicode: try: the_type = spec[i].encode("ascii") except UnicodeEncodeError: raise OperationError(space.w_ValueError, space.wrap("invalid presentation type")) else: the_type = presentation_type i += 1
def _parse_spec(self, default_type, default_align): space = self.space self._fill_char = self._lit("\0") self._align = default_align self._alternate = False self._sign = "\0" self._thousands_sep = False self._precision = -1 presentation_type = default_type spec = self.spec if not spec: return True length = len(spec) i = 0 got_align = True if length - i >= 2 and self._is_alignment(spec[i + 1]): self._align = spec[i + 1] self._fill_char = spec[i] i += 2 elif length - i >= 1 and self._is_alignment(spec[i]): self._align = spec[i] i += 1 else: got_align = False if length - i >= 1 and self._is_sign(spec[i]): self._sign = spec[i] i += 1 if length - i >= 1 and spec[i] == "#": self._alternate = True i += 1 if self._fill_char == "\0" and length - i >= 1 and spec[i] == "0": self._fill_char = self._lit("0") if not got_align: self._align = "=" i += 1 start_i = i self._width, i = _parse_int(self.space, spec, i, length) if length - i and spec[i] == ",": self._thousands_sep = True i += 1 if length - i and spec[i] == ".": i += 1 self._precision, i = _parse_int(self.space, spec, i, length) if self._precision == -1: raise OperationError(space.w_ValueError, space.wrap("no precision given")) if length - i > 1: raise OperationError(space.w_ValueError, space.wrap("invalid format spec")) if length - i == 1: presentation_type = spec[i] i += 1 if self.is_unicode: try: the_type = presentation_type.encode("ascii") except UnicodeEncodeError: raise OperationError(space.w_ValueError, space.wrap("invalid type")) else: the_type = presentation_type self._type = the_type if self._thousands_sep: tp = self._type if (tp == "d" or tp == "e" or tp == "f" or tp == "g" or tp == "E" or tp == "G" or tp == "%" or tp == "F" or tp == "\0"): # ok pass else: raise OperationError(space.w_ValueError, space.wrap("invalid type with ','")) return False
the_type = spec[i].encode("ascii")
the_type = spec[i].encode("ascii")[0]
def _parse_spec(self, default_type, default_align): space = self.space self._fill_char = self._lit("\0")[0] self._align = default_align self._alternate = False self._sign = "\0" self._thousands_sep = False self._precision = -1 the_type = default_type spec = self.spec if not spec: return True length = len(spec) i = 0 got_align = True if length - i >= 2 and self._is_alignment(spec[i + 1]): self._align = spec[i + 1] self._fill_char = spec[i] i += 2 elif length - i >= 1 and self._is_alignment(spec[i]): self._align = spec[i] i += 1 else: got_align = False if length - i >= 1 and self._is_sign(spec[i]): self._sign = spec[i] i += 1 if length - i >= 1 and spec[i] == "#": self._alternate = True i += 1 if self._fill_char == "\0" and length - i >= 1 and spec[i] == "0": self._fill_char = self._lit("0")[0] if not got_align: self._align = "=" i += 1 start_i = i self._width, i = _parse_int(self.space, spec, i, length) if length - i and spec[i] == ",": self._thousands_sep = True i += 1 if length - i and spec[i] == ".": i += 1 self._precision, i = _parse_int(self.space, spec, i, length) if self._precision == -1: raise OperationError(space.w_ValueError, space.wrap("no precision given")) if length - i > 1: raise OperationError(space.w_ValueError, space.wrap("invalid format spec")) if length - i == 1: presentation_type = spec[i] if self.is_unicode: try: the_type = spec[i].encode("ascii") except UnicodeEncodeError: raise OperationError(space.w_ValueError, space.wrap("invalid presentation type")) else: the_type = presentation_type i += 1 self._type = the_type if self._thousands_sep: tp = self._type if (tp == "d" or tp == "e" or tp == "f" or tp == "g" or tp == "E" or tp == "G" or tp == "%" or tp == "F" or tp == "\0"): # ok pass else: raise OperationError(space.w_ValueError, space.wrap("invalid type with ','")) return False
self._adjust_sp(n, fcond=fcond)
self._adjust_sp(n, regalloc, fcond=fcond)
def emit_op_call(self, op, regalloc, fcond): locs = [] # all arguments past the 4th go on the stack # XXX support types other than int (one word types) if op.numargs() > 5: stack_args = op.numargs() - 5 n = stack_args*WORD self._adjust_sp(n, fcond=fcond) for i in range(5, op.numargs()): reg = regalloc.make_sure_var_in_reg(op.getarg(i)) self.mc.STR_ri(reg.value, r.sp.value, (i-5)*WORD) regalloc.possibly_free_var(reg)
if self._ptr is not None:
if self._ptr is not None and argtypes is self._argtypes_:
def _getfuncptr(self, argtypes, restype, thisarg=None): if self._ptr is not None: return self._ptr if restype is None or not isinstance(restype, _CDataMeta): import ctypes restype = ctypes.c_int argshapes = [arg._ffiargshape for arg in argtypes] resshape = restype._ffiargshape if self._buffer is not None: ptr = _rawffi.FuncPtr(self._buffer[0], argshapes, resshape, self._flags_) if argtypes is self._argtypes_: self._ptr = ptr return ptr
w_result = space.wrap(result[0] != '\x00')
x = rffi.cast(lltype.Signed, result[0]) w_result = space.wrap(x != 0)
def PyMember_GetOne(space, obj, w_member): addr = rffi.cast(ADDR, obj) addr += w_member.c_offset member_type = rffi.cast(lltype.Signed, w_member.c_type) for converter in integer_converters: typ, lltyp, _ = converter if typ == member_type: result = rffi.cast(rffi.CArrayPtr(lltyp), addr) if lltyp is rffi.FLOAT: w_result = space.wrap(lltype.cast_primitive(lltype.Float, result[0])) elif typ == T_BOOL: w_result = space.wrap(result[0] != '\x00') else: w_result = space.wrap(result[0]) return w_result if member_type == T_STRING: result = rffi.cast(rffi.CCHARPP, addr) if result[0]: w_result = PyString_FromString(space, result[0]) else: w_result = space.w_None elif member_type == T_STRING_INPLACE: result = rffi.cast(rffi.CCHARP, addr) w_result = PyString_FromString(space, result) elif member_type == T_CHAR: result = rffi.cast(rffi.CCHARP, addr) w_result = space.wrap(result[0]) elif member_type == T_OBJECT: obj_ptr = rffi.cast(PyObjectP, addr) if obj_ptr[0]: w_result = from_ref(space, obj_ptr[0]) else: w_result = space.w_None elif member_type == T_OBJECT_EX: obj_ptr = rffi.cast(PyObjectP, addr) if obj_ptr[0]: w_result = from_ref(space, obj_ptr[0]) else: w_name = space.wrap(rffi.charp2str(w_member.c_name)) raise OperationError(space.w_AttributeError, w_name) else: raise OperationError(space.w_SystemError, space.wrap("bad memberdescr type")) return w_result
return space.w_bool(not self.is_valid())
return space.newbool(not self.is_valid())
def closed_get(space, self): return space.w_bool(not self.is_valid())
return space.w_bool(self.flags & READABLE)
return space.newbool(bool(self.flags & READABLE))
def readable_get(space, self): return space.w_bool(self.flags & READABLE)
return space.w_bool(self.flags & WRITABLE)
return space.newbool(bool(self.flags & WRITABLE))
def writable_get(space, self): return space.w_bool(self.flags & WRITABLE)
raise mp_error(res)
raise mp_error(space, res)
def recv_bytes(self, space, maxlength=PY_SSIZE_T_MAX): self._check_readable(space) if maxlength < 0: raise OperationError(space.w_ValueError, space.wrap("maxlength < 0"))
raise mp_error(res)
raise mp_error(space, res)
def recv_bytes_into(self, space, w_buffer, offset=0): rwbuffer = space.rwbuffer_w(w_buffer) length = rwbuffer.getlength()
raise OperationError(BufferTooShort)
raise BufferTooShort(space)
def recv_bytes_into(self, space, w_buffer, offset=0): rwbuffer = space.rwbuffer_w(w_buffer) length = rwbuffer.getlength()
raise mp_error(res)
raise mp_error(space, res)
def recv(self, space): self._check_readable(space)
base_typedef = TypeDef(
W_BaseConnection.typedef = TypeDef(
def recv(self, space): self._check_readable(space)
def descr_new(space, w_subtype, fd, readable=True, writable=True):
def descr_new_file(space, w_subtype, fd, readable=True, writable=True):
def descr_new(space, w_subtype, fd, readable=True, writable=True): flags = (readable and READABLE) | (writable and WRITABLE)
self._recvall(rffi.cast(rffi.CCHARP, length_ptr), 4) length = length_ptr[0]
self._recvall(space, rffi.cast(rffi.CCHARP, length_ptr), 4) length = intmask(length_ptr[0])
def do_recv_string(self, space, maxlength): length_ptr = lltype.malloc(rffi.CArrayPtr(rffi.UINT).TO, 1, flavor='raw') self._recvall(rffi.cast(rffi.CCHARP, length_ptr), 4) length = length_ptr[0] if length > maxlength: return MP_BAD_MESSAGE_LENGTH
return MP_BAD_MESSAGE_LENGTH
return MP_BAD_MESSAGE_LENGTH, lltype.nullptr(rffi.CCHARP.TO)
def do_recv_string(self, space, maxlength): length_ptr = lltype.malloc(rffi.CArrayPtr(rffi.UINT).TO, 1, flavor='raw') self._recvall(rffi.cast(rffi.CCHARP, length_ptr), 4) length = length_ptr[0] if length > maxlength: return MP_BAD_MESSAGE_LENGTH
self._recvall(self.buffer, length) return length, None
self._recvall(space, self.buffer, length) return length, lltype.nullptr(rffi.CCHARP.TO)
def do_recv_string(self, space, maxlength): length_ptr = lltype.malloc(rffi.CArrayPtr(rffi.UINT).TO, 1, flavor='raw') self._recvall(rffi.cast(rffi.CCHARP, length_ptr), 4) length = length_ptr[0] if length > maxlength: return MP_BAD_MESSAGE_LENGTH
self._recvall(newbuf, length)
self._recvall(space, newbuf, length)
def do_recv_string(self, space, maxlength): length_ptr = lltype.malloc(rffi.CArrayPtr(rffi.UINT).TO, 1, flavor='raw') self._recvall(rffi.cast(rffi.CCHARP, length_ptr), 4) length = length_ptr[0] if length > maxlength: return MP_BAD_MESSAGE_LENGTH
def _recvall(self, buffer, length):
def _recvall(self, space, buffer, length): length = intmask(length)
def _recvall(self, buffer, length): remaining = length while remaining > 0: try: data = os.read(self.fd, remaining) except OSError, e: raise wrap_oserror(space, e) count = len(data) if count == 0: if remaining == length: return MP_END_OF_FILE else: return MP_EARLY_END_OF_FILE # XXX inefficient for i in range(count): buffer[i] = data[i] remaining -= count buffer = rffi.ptradd(buffer, count)
return MP_END_OF_FILE
raise mp_error(space, MP_END_OF_FILE)
def _recvall(self, buffer, length): remaining = length while remaining > 0: try: data = os.read(self.fd, remaining) except OSError, e: raise wrap_oserror(space, e) count = len(data) if count == 0: if remaining == length: return MP_END_OF_FILE else: return MP_EARLY_END_OF_FILE # XXX inefficient for i in range(count): buffer[i] = data[i] remaining -= count buffer = rffi.ptradd(buffer, count)
return MP_EARLY_END_OF_FILE
raise mp_error(space, MP_EARLY_END_OF_FILE)
def _recvall(self, buffer, length): remaining = length while remaining > 0: try: data = os.read(self.fd, remaining) except OSError, e: raise wrap_oserror(space, e) count = len(data) if count == 0: if remaining == length: return MP_END_OF_FILE else: return MP_EARLY_END_OF_FILE # XXX inefficient for i in range(count): buffer[i] = data[i] remaining -= count buffer = rffi.ptradd(buffer, count)