def test_r_singlefloat_eq(): x = r_singlefloat(2.5) # exact number y = r_singlefloat(2.5) assert x == y assert not x != y assert not x == 2.5 assert x != 2.5 py.test.raises(TypeError, "x>y")
def test_cast(self): res = cast(SIZE_T, -1) assert type(res) is r_size_t assert res == r_size_t(-1) # res = cast(lltype.Signed, 42.5) assert res == 42 res = cast(lltype.SingleFloat, 12.3) assert res == r_singlefloat(12.3) res = cast(lltype.SingleFloat, res) assert res == r_singlefloat(12.3) res = cast(lltype.Float, r_singlefloat(12.)) assert res == 12.
def test_single_float_args(self): """ float sum_xy_float(float x, float y) { return x+y; } """ from ctypes import c_float # this is used only to compute the expected result libfoo = self.get_libfoo() func = (libfoo, 'sum_xy_float', [types.float, types.float], types.float) x = r_singlefloat(12.34) y = r_singlefloat(56.78) res = self.call(func, [x, y], rffi.FLOAT, jitif=["singlefloats"]) expected = c_float(c_float(12.34).value + c_float(56.78).value).value assert float(res) == expected
def test_contains_unsupported_variable_type(): def f(x): return x graph = support.getgraph(f, [5]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: assert not contains_unsupported_variable_type(graph, sf, sll, ssf) # graph = support.getgraph(f, [5.5]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: res = contains_unsupported_variable_type(graph, sf, sll, ssf) assert res is not sf # graph = support.getgraph(f, [r_singlefloat(5.5)]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: res = contains_unsupported_variable_type(graph, sf, sll, ssf) assert res == (not ssf) # graph = support.getgraph(f, [r_longlong(5)]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: res = contains_unsupported_variable_type(graph, sf, sll, ssf) assert res == (sys.maxint == 2147483647 and not sll)
def _singlefloat(self, w_ffitype, w_obj): # a separate function, which can be seen by the jit or not, # depending on whether singlefloats are supported from pypy.rlib.rarithmetic import r_singlefloat floatval = self.space.float_w(w_obj) singlefloatval = r_singlefloat(floatval) self.handle_singlefloat(w_ffitype, w_obj, singlefloatval)
def test_wrap(): def _is(box1, box2): return box1.__class__ == box2.__class__ and box1.value == box2.value p = lltype.malloc(lltype.GcStruct("S")) po = lltype.cast_opaque_ptr(llmemory.GCREF, p) assert _is(wrap(None, 42), BoxInt(42)) assert _is(wrap(None, 42.5), boxfloat(42.5)) assert _is(wrap(None, p), BoxPtr(po)) assert _is(wrap(None, 42, in_const_box=True), ConstInt(42)) assert _is(wrap(None, 42.5, in_const_box=True), constfloat(42.5)) assert _is(wrap(None, p, in_const_box=True), ConstPtr(po)) if longlong.supports_longlong: import sys from pypy.rlib.rarithmetic import r_longlong, r_ulonglong value = r_longlong(-sys.maxint * 17) assert _is(wrap(None, value), BoxFloat(value)) assert _is(wrap(None, value, in_const_box=True), ConstFloat(value)) value_unsigned = r_ulonglong(-sys.maxint * 17) assert _is(wrap(None, value_unsigned), BoxFloat(value)) sfval = r_singlefloat(42.5) ival = longlong.singlefloat2int(sfval) assert _is(wrap(None, sfval), BoxInt(ival)) assert _is(wrap(None, sfval, in_const_box=True), ConstInt(ival))
def pack_float(fmtiter): doubleval = fmtiter.accept_float_arg() floatval = r_singlefloat(doubleval) float_buf[0] = floatval p = rffi.cast(rffi.CCHARP, float_buf) for i in range(sizeof_float): fmtiter.result.append(p[i])
def test_contains_unsupported_variable_type(): def f(x): return x graph = support.getgraph(f, [5]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: assert not contains_unsupported_variable_type( graph, sf, sll, ssf) # graph = support.getgraph(f, [5.5]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: res = contains_unsupported_variable_type(graph, sf, sll, ssf) assert res is not sf # graph = support.getgraph(f, [r_singlefloat(5.5)]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: res = contains_unsupported_variable_type(graph, sf, sll, ssf) assert res == (not ssf) # graph = support.getgraph(f, [r_longlong(5)]) for sf in [False, True]: for sll in [False, True]: for ssf in [False, True]: res = contains_unsupported_variable_type(graph, sf, sll, ssf) assert res == (sys.maxint == 2147483647 and not sll)
def detect_floatformat(): from pypy.rpython.lltypesystem import rffi, lltype buf = lltype.malloc(rffi.CCHARP.TO, 8, flavor='raw') rffi.cast(rffi.DOUBLEP, buf)[0] = 9006104071832581.0 packed = rffi.charpsize2str(buf, 8) if packed == "\x43\x3f\xff\x01\x02\x03\x04\x05": double_format = 'IEEE, big-endian' elif packed == "\x05\x04\x03\x02\x01\xff\x3f\x43": double_format = 'IEEE, little-endian' else: double_format = 'unknown' lltype.free(buf, flavor='raw') # buf = lltype.malloc(rffi.CCHARP.TO, 4, flavor='raw') rffi.cast(rffi.FLOATP, buf)[0] = rarithmetic.r_singlefloat(16711938.0) packed = rffi.charpsize2str(buf, 4) if packed == "\x4b\x7f\x01\x02": float_format = 'IEEE, big-endian' elif packed == "\x02\x01\x7f\x4b": float_format = 'IEEE, little-endian' else: float_format = 'unknown' lltype.free(buf, flavor='raw') return double_format, float_format
def test_annotation_to_lltype(): from pypy.rlib.rarithmetic import r_uint, r_singlefloat s_i = SomeInteger() s_pos = SomeInteger(nonneg=True) s_1 = SomeInteger(nonneg=True); s_1.const = 1 s_m1 = SomeInteger(nonneg=False); s_m1.const = -1 s_u = SomeInteger(nonneg=True, unsigned=True); s_u1 = SomeInteger(nonneg=True, unsigned=True); s_u1.const = r_uint(1) assert annotation_to_lltype(s_i) == lltype.Signed assert annotation_to_lltype(s_pos) == lltype.Signed assert annotation_to_lltype(s_1) == lltype.Signed assert annotation_to_lltype(s_m1) == lltype.Signed assert annotation_to_lltype(s_u) == lltype.Unsigned assert annotation_to_lltype(s_u1) == lltype.Unsigned assert annotation_to_lltype(SomeBool()) == lltype.Bool assert annotation_to_lltype(SomeChar()) == lltype.Char PS = lltype.Ptr(lltype.GcStruct('s')) s_p = SomePtr(ll_ptrtype=PS) assert annotation_to_lltype(s_p) == PS py.test.raises(ValueError, "annotation_to_lltype(si0)") C = ootype.Instance('C', ROOT, {}) ref = SomeOOInstance(C) assert annotation_to_lltype(ref) == C s_singlefloat = SomeSingleFloat() s_singlefloat.const = r_singlefloat(0.0) assert annotation_to_lltype(s_singlefloat) == lltype.SingleFloat
def test_annotation_to_lltype(): from pypy.rlib.rarithmetic import r_uint, r_singlefloat s_i = SomeInteger() s_pos = SomeInteger(nonneg=True) s_1 = SomeInteger(nonneg=True) s_1.const = 1 s_m1 = SomeInteger(nonneg=False) s_m1.const = -1 s_u = SomeInteger(nonneg=True, unsigned=True) s_u1 = SomeInteger(nonneg=True, unsigned=True) s_u1.const = r_uint(1) assert annotation_to_lltype(s_i) == lltype.Signed assert annotation_to_lltype(s_pos) == lltype.Signed assert annotation_to_lltype(s_1) == lltype.Signed assert annotation_to_lltype(s_m1) == lltype.Signed assert annotation_to_lltype(s_u) == lltype.Unsigned assert annotation_to_lltype(s_u1) == lltype.Unsigned assert annotation_to_lltype(SomeBool()) == lltype.Bool assert annotation_to_lltype(SomeChar()) == lltype.Char PS = lltype.Ptr(lltype.GcStruct('s')) s_p = SomePtr(ll_ptrtype=PS) assert annotation_to_lltype(s_p) == PS py.test.raises(ValueError, "annotation_to_lltype(si0)") C = ootype.Instance('C', ROOT, {}) ref = SomeOOInstance(C) assert annotation_to_lltype(ref) == C s_singlefloat = SomeSingleFloat() s_singlefloat.const = r_singlefloat(0.0) assert annotation_to_lltype(s_singlefloat) == lltype.SingleFloat
def arg_singlefloat(self, space, argchain, w_arg): # a separate function, which can be seen by the jit or not, # depending on whether singlefloats are supported from pypy.rlib.rarithmetic import r_singlefloat fval = space.float_w(w_arg) sfval = r_singlefloat(fval) argchain.arg(sfval)
def test_specialize_value(): assert specialize_value(lltype.Char, 0x41) == '\x41' if longlong.supports_longlong: import sys value = longlong.r_float_storage(sys.maxint*17) assert specialize_value(lltype.SignedLongLong, value) == sys.maxint*17 sfval = r_singlefloat(42.5) ival = longlong.singlefloat2int(sfval) assert specialize_value(rffi.FLOAT, ival) == sfval
def test_specialize_value(): assert specialize_value(lltype.Char, 0x41) == '\x41' if longlong.supports_longlong: import sys value = longlong.r_float_storage(sys.maxint * 17) assert specialize_value(lltype.SignedLongLong, value) == sys.maxint * 17 sfval = r_singlefloat(42.5) ival = longlong.singlefloat2int(sfval) assert specialize_value(rffi.FLOAT, ival) == sfval
def test_call_with_singlefloats(self): cpu = self.cpu if not cpu.supports_floats or not cpu.supports_singlefloats: py.test.skip('requires floats and singlefloats') import random from pypy.rlib.libffi import types from pypy.rlib.rarithmetic import r_singlefloat def func(*args): res = 0.0 for i, x in enumerate(args): res += (i + 1.1) * float(x) return res F = lltype.Float S = lltype.SingleFloat I = lltype.Signed floats = [random.random() - 0.5 for i in range(8)] singlefloats = [r_singlefloat(random.random() - 0.5) for i in range(8)] ints = [random.randrange(-99, 99) for i in range(8)] for repeat in range(100): args = [] argvalues = [] argslist = [] local_floats = list(floats) local_singlefloats = list(singlefloats) local_ints = list(ints) for i in range(8): case = random.randrange(0, 3) if case == 0: args.append(F) arg = local_floats.pop() argslist.append(boxfloat(arg)) elif case == 1: args.append(S) arg = local_singlefloats.pop() argslist.append(BoxInt(longlong.singlefloat2int(arg))) else: args.append(I) arg = local_ints.pop() argslist.append(BoxInt(arg)) argvalues.append(arg) FUNC = self.FuncType(args, F) FPTR = self.Ptr(FUNC) func_ptr = llhelper(FPTR, func) calldescr = cpu.calldescrof(FUNC, FUNC.ARGS, FUNC.RESULT, EffectInfo.MOST_GENERAL) funcbox = self.get_funcbox(cpu, func_ptr) res = self.execute_operation(rop.CALL, [funcbox] + argslist, 'float', descr=calldescr) expected = func(*argvalues) assert abs(res.getfloat() - expected) < 0.0001
def pack_float(fmtiter): doubleval = fmtiter.accept_float_arg() floatval = r_singlefloat(doubleval) value = longlong2float.singlefloat2uint(floatval) value = widen(value) if fmtiter.bigendian: for i in range_4_unroll: x = (value >> (8*i)) & 0xff fmtiter.result.append(chr(x)) else: for i in range_4_unroll: fmtiter.result.append(chr(value & 0xff)) value >>= 8
def pack_float(fmtiter): doubleval = fmtiter.accept_float_arg() floatval = r_singlefloat(doubleval) value = longlong2float.singlefloat2uint(floatval) value = widen(value) if fmtiter.bigendian: for i in range_4_unroll: x = (value >> (8 * i)) & 0xff fmtiter.result.append(chr(x)) else: for i in range_4_unroll: fmtiter.result.append(chr(value & 0xff)) value >>= 8
def ctypes2lltype(T, cobj): """Convert the ctypes object 'cobj' to its lltype equivalent. 'T' is the expected lltype type. """ if isinstance(T, lltype.Ptr): if not cobj: # NULL pointer return lltype.nullptr(T.TO) if isinstance(T.TO, lltype.Struct): if T.TO._arrayfld is not None: lgt = getattr(cobj.contents, T.TO._arrayfld).length container = lltype._struct(T.TO, lgt) else: container = lltype._struct(T.TO) struct_use_ctypes_storage(container, cobj.contents) elif isinstance(T.TO, lltype.Array): if T.TO._hints.get('nolength', False): container = _array_of_unknown_length(T.TO) container._storage = cobj.contents else: raise NotImplementedError("array with an explicit length") elif isinstance(T.TO, lltype.FuncType): _callable = get_ctypes_trampoline(T.TO, cobj) return lltype.functionptr(T.TO, getattr(cobj, '__name__', '?'), _callable=_callable) elif isinstance(T.TO, lltype.OpaqueType): container = lltype._opaque(T.TO) else: raise NotImplementedError(T) llobj = lltype._ptr(T, container, solid=True) elif T is lltype.Char: llobj = chr(cobj) elif T is lltype.UniChar: llobj = unichr(cobj) elif T is lltype.Signed: llobj = cobj elif T is lltype.SingleFloat: if isinstance(cobj, ctypes.c_float): cobj = cobj.value llobj = r_singlefloat(cobj) else: from pypy.rpython.lltypesystem import rffi try: inttype = rffi.platform.numbertype_to_rclass[T] except KeyError: llobj = cobj else: llobj = inttype(cobj) assert lltype.typeOf(llobj) == T return llobj
def test_call_stubs_single_float(): from pypy.rlib.longlong2float import uint2singlefloat, singlefloat2uint from pypy.rlib.rarithmetic import r_singlefloat, intmask # c0 = GcCache(False) ARGS = [lltype.SingleFloat, lltype.SingleFloat, lltype.SingleFloat] RES = lltype.SingleFloat def f(a, b, c): a = float(a) b = float(b) c = float(c) x = a - (b / c) return r_singlefloat(x) fnptr = llhelper(lltype.Ptr(lltype.FuncType(ARGS, RES)), f) descr2 = get_call_descr(c0, ARGS, RES) a = intmask(singlefloat2uint(r_singlefloat(-10.0))) b = intmask(singlefloat2uint(r_singlefloat(3.0))) c = intmask(singlefloat2uint(r_singlefloat(2.0))) res = descr2.call_stub_i(rffi.cast(lltype.Signed, fnptr), [a, b, c], [], []) assert float(uint2singlefloat(rffi.r_uint(res))) == -11.5
def test_call_stubs_single_float(): from pypy.rlib.longlong2float import uint2singlefloat, singlefloat2uint from pypy.rlib.rarithmetic import r_singlefloat, intmask # c0 = GcCache(False) ARGS = [lltype.SingleFloat, lltype.SingleFloat, lltype.SingleFloat] RES = lltype.SingleFloat def f(a, b, c): a = float(a) b = float(b) c = float(c) x = a - (b / c) return r_singlefloat(x) fnptr = llhelper(lltype.Ptr(lltype.FuncType(ARGS, RES)), f) descr2 = get_call_descr(c0, ARGS, RES) a = intmask(singlefloat2uint(r_singlefloat(-10.0))) b = intmask(singlefloat2uint(r_singlefloat(3.0))) c = intmask(singlefloat2uint(r_singlefloat(2.0))) res = descr2.call_stub(rffi.cast(lltype.Signed, fnptr), [a, b, c], [], []) assert float(uint2singlefloat(rffi.r_uint(res))) == -11.5
def ctypes2lltype(T, cobj): """Convert the ctypes object 'cobj' to its lltype equivalent. 'T' is the expected lltype type. """ if isinstance(T, lltype.Ptr): if not cobj: # NULL pointer return lltype.nullptr(T.TO) if isinstance(T.TO, lltype.Struct): if T.TO._arrayfld is not None: raise NotImplementedError("XXX var-sized structs") container = lltype._struct(T.TO) struct_use_ctypes_storage(container, cobj.contents) elif isinstance(T.TO, lltype.Array): if T.TO._hints.get('nolength', False): container = _array_of_unknown_length(T.TO) container._storage = cobj.contents else: raise NotImplementedError("array with an explicit length") elif isinstance(T.TO, lltype.FuncType): _callable = get_ctypes_trampoline(T.TO, cobj) return lltype.functionptr(T.TO, getattr(cobj, '__name__', '?'), _callable=_callable) elif isinstance(T.TO, lltype.OpaqueType): container = lltype._opaque(T.TO) else: raise NotImplementedError(T) llobj = lltype._ptr(T, container, solid=True) elif T is lltype.Char: llobj = chr(cobj) elif T is lltype.UniChar: llobj = unichr(cobj) elif T is lltype.Signed: llobj = cobj elif T is lltype.SingleFloat: if isinstance(cobj, ctypes.c_float): cobj = cobj.value llobj = r_singlefloat(cobj) else: from pypy.rpython.lltypesystem import rffi try: inttype = rffi.platform.numbertype_to_rclass[T] except KeyError: llobj = cobj else: llobj = inttype(cobj) assert lltype.typeOf(llobj) == T return llobj
def test_struct_fields_singlefloat(self): POINT = lltype.Struct('POINT', ('x', rffi.FLOAT), ('y', rffi.FLOAT) ) y_ofs = 4 p = lltype.malloc(POINT, flavor='raw') p.x = r_singlefloat(123.4) p.y = r_singlefloat(567.8) addr = rffi.cast(rffi.VOIDP, p) assert struct_getfield_singlefloat(types.double, addr, 0) == r_singlefloat(123.4) assert struct_getfield_singlefloat(types.double, addr, y_ofs) == r_singlefloat(567.8) # struct_setfield_singlefloat(types.double, addr, 0, r_singlefloat(321.0)) struct_setfield_singlefloat(types.double, addr, y_ofs, r_singlefloat(876.5)) assert p.x == r_singlefloat(321.0) assert p.y == r_singlefloat(876.5) # lltype.free(p, flavor='raw')
def test_struct_fields_singlefloat(self): POINT = lltype.Struct('POINT', ('x', rffi.FLOAT), ('y', rffi.FLOAT)) y_ofs = 4 p = lltype.malloc(POINT, flavor='raw') p.x = r_singlefloat(123.4) p.y = r_singlefloat(567.8) addr = rffi.cast(rffi.VOIDP, p) assert struct_getfield_singlefloat(types.double, addr, 0) == r_singlefloat(123.4) assert struct_getfield_singlefloat(types.double, addr, y_ofs) == r_singlefloat(567.8) # struct_setfield_singlefloat(types.double, addr, 0, r_singlefloat(321.0)) struct_setfield_singlefloat(types.double, addr, y_ofs, r_singlefloat(876.5)) assert p.x == r_singlefloat(321.0) assert p.y == r_singlefloat(876.5) # lltype.free(p, flavor='raw')
def test_wrap(): def _is(box1, box2): return (box1.__class__ == box2.__class__ and box1.value == box2.value) p = lltype.malloc(lltype.GcStruct('S')) po = lltype.cast_opaque_ptr(llmemory.GCREF, p) assert _is(wrap(None, 42), BoxInt(42)) assert _is(wrap(None, 42.5), boxfloat(42.5)) assert _is(wrap(None, p), BoxPtr(po)) assert _is(wrap(None, 42, in_const_box=True), ConstInt(42)) assert _is(wrap(None, 42.5, in_const_box=True), constfloat(42.5)) assert _is(wrap(None, p, in_const_box=True), ConstPtr(po)) if longlong.supports_longlong: import sys from pypy.rlib.rarithmetic import r_longlong, r_ulonglong value = r_longlong(-sys.maxint * 17) assert _is(wrap(None, value), BoxFloat(value)) assert _is(wrap(None, value, in_const_box=True), ConstFloat(value)) value_unsigned = r_ulonglong(-sys.maxint * 17) assert _is(wrap(None, value_unsigned), BoxFloat(value)) sfval = r_singlefloat(42.5) ival = longlong.singlefloat2int(sfval) assert _is(wrap(None, sfval), BoxInt(ival)) assert _is(wrap(None, sfval, in_const_box=True), ConstInt(ival))
def test_int_as_singlefloat(): for x in enum_floats(): res = fnsingle(x) assert repr(res) == repr(float(r_singlefloat(x)))
def f(a, b, c): a = float(a) b = float(b) c = float(c) x = a - (b / c) return r_singlefloat(x)
def test_compiled_single(): fn2 = compile(fnsingle, [float]) for x in enum_floats(): res = fn2(x) assert repr(res) == repr(float(r_singlefloat(x)))
def f(x): a = r_singlefloat(x) b = r_singlefloat(x+1) return a == b
def test_r_singlefloat(): x = r_singlefloat(2.5) # exact number assert float(x) == 2.5 x = r_singlefloat(2.1) # approximate number, bits are lost assert float(x) != 2.1 assert abs(float(x) - 2.1) < 1E-6
from pypy.rpython import rclass from pypy.rpython.rmodel import inputconst from pypy.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong from pypy.rlib.rarithmetic import r_singlefloat from pypy.rlib.debug import ll_assert from pypy.annotation import model as annmodel from pypy.rpython.annlowlevel import MixLevelHelperAnnotator from pypy.tool.sourcetools import func_with_new_name PrimitiveErrorValue = { lltype.Signed: -1, lltype.Unsigned: r_uint(-1), lltype.SignedLongLong: r_longlong(-1), lltype.UnsignedLongLong: r_ulonglong(-1), lltype.Float: -1.0, lltype.SingleFloat: r_singlefloat(-1.0), lltype.Char: chr(255), lltype.UniChar: unichr(0xFFFF), # XXX is this always right? lltype.Bool: True, llmemory.Address: llmemory.NULL, lltype.Void: None } for TYPE in rffi.NUMBER_TYPES: PrimitiveErrorValue[TYPE] = lltype.cast_primitive(TYPE, -1) del TYPE def error_value(T): if isinstance(T, lltype.Primitive): return PrimitiveErrorValue[T]
def f(x): a = r_singlefloat(x) b = r_singlefloat(x + 1) return a == b
def test_float_and_double(self): space = self.space self.check(app_types.float, space.wrap(12.34), r_singlefloat(12.34)) self.check(app_types.double, space.wrap(12.34), 12.34)
def ctypes2lltype(T, cobj): """Convert the ctypes object 'cobj' to its lltype equivalent. 'T' is the expected lltype type. """ if T is lltype.Void: return None if isinstance(T, lltype.Ptr): if not cobj: # NULL pointer return lltype.nullptr(T.TO) if T is base_ptr_lltype(): return _opaque_list[ctypes.cast(cobj, ctypes.c_void_p).value] if isinstance(T.TO, lltype.Struct): if T.TO._arrayfld is not None: carray = getattr(cobj.contents, T.TO._arrayfld) container = lltype._struct(T.TO, carray.length) else: # special treatment of 'OBJECT' subclasses if get_rtyper() and lltype._castdepth(T.TO, OBJECT) > 0: ctypes_object = get_ctypes_type(lltype.Ptr(OBJECT)) as_obj = ctypes2lltype(lltype.Ptr(OBJECT), ctypes.cast(cobj, ctypes_object)) TObj = get_rtyper().get_type_for_typeptr(as_obj.typeptr) if TObj != T.TO: ctypes_instance = get_ctypes_type(lltype.Ptr(TObj)) return lltype.cast_pointer(T, ctypes2lltype(lltype.Ptr(TObj), ctypes.cast(cobj, ctypes_instance))) container = lltype._struct(T.TO) struct_use_ctypes_storage(container, cobj.contents) elif isinstance(T.TO, lltype.Array): if T.TO._hints.get('nolength', False): container = _array_of_unknown_length(T.TO) container._storage = cobj.contents else: container = _array_of_known_length(T.TO) container._storage = cobj.contents elif isinstance(T.TO, lltype.FuncType): cobjkey = ctypes.cast(cobj, ctypes.c_void_p).value if cobjkey in _callback2obj: container = _callback2obj[cobjkey] else: _callable = get_ctypes_trampoline(T.TO, cobj) return lltype.functionptr(T.TO, getattr(cobj, '__name__', '?'), _callable=_callable) elif isinstance(T.TO, lltype.OpaqueType): if T == llmemory.GCREF: # XXX obscure hack return _llgcref(cobj) else: container = lltype._opaque(T.TO) else: raise NotImplementedError(T) llobj = lltype._ptr(T, container, solid=True) elif T is llmemory.Address: if cobj is None: llobj = llmemory.NULL else: llobj = _lladdress(cobj) elif T is lltype.Char: llobj = chr(cobj) elif T is lltype.UniChar: llobj = unichr(cobj) elif T is lltype.Signed: llobj = cobj elif T is lltype.SingleFloat: if isinstance(cobj, ctypes.c_float): cobj = cobj.value llobj = r_singlefloat(cobj) elif T is lltype.Void: llobj = cobj else: from pypy.rpython.lltypesystem import rffi try: inttype = rffi.platform.numbertype_to_rclass[T] except KeyError: llobj = cobj else: llobj = inttype(cobj) assert lltype.typeOf(llobj) == T return llobj
def fn(x): y = r_singlefloat(x) return float(y)
def fnsingle(f1): sf1 = r_singlefloat(f1) ii = singlefloat2uint(sf1) sf2 = uint2singlefloat(ii) f2 = float(sf2) return f2
def ctypes2lltype(T, cobj): """Convert the ctypes object 'cobj' to its lltype equivalent. 'T' is the expected lltype type. """ if T is lltype.Void: return None if isinstance(T, lltype.Ptr): if not cobj: # NULL pointer return lltype.nullptr(T.TO) if T is base_ptr_lltype(): return _opaque_list[ctypes.cast(cobj, ctypes.c_void_p).value] if isinstance(T.TO, lltype.Struct): if T.TO._arrayfld is not None: carray = getattr(cobj.contents, T.TO._arrayfld) container = lltype._struct(T.TO, carray.length) else: # special treatment of 'OBJECT' subclasses if get_rtyper() and lltype._castdepth(T.TO, OBJECT) > 0: ctypes_object = get_ctypes_type(lltype.Ptr(OBJECT)) as_obj = ctypes2lltype(lltype.Ptr(OBJECT), ctypes.cast(cobj, ctypes_object)) TObj = get_rtyper().get_type_for_typeptr(as_obj.typeptr) if TObj != T.TO: ctypes_instance = get_ctypes_type(lltype.Ptr(TObj)) return lltype.cast_pointer( T, ctypes2lltype(lltype.Ptr(TObj), ctypes.cast(cobj, ctypes_instance))) container = lltype._struct(T.TO) struct_use_ctypes_storage(container, cobj.contents) addr = ctypes.addressof(cobj.contents) if addr in _parent_cache: setparentstructure(container, _parent_cache[addr]) elif isinstance(T.TO, lltype.Array): if T.TO._hints.get('nolength', False): container = _array_of_unknown_length(T.TO) container._storage = cobj.contents else: container = _array_of_known_length(T.TO) container._storage = cobj.contents elif isinstance(T.TO, lltype.FuncType): cobjkey = ctypes.cast(cobj, ctypes.c_void_p).value if cobjkey in _callback2obj: container = _callback2obj[cobjkey] else: _callable = get_ctypes_trampoline(T.TO, cobj) return lltype.functionptr(T.TO, getattr(cobj, '__name__', '?'), _callable=_callable) elif isinstance(T.TO, lltype.OpaqueType): if T == llmemory.GCREF: container = _llgcopaque(cobj) else: container = lltype._opaque(T.TO) else: raise NotImplementedError(T) llobj = lltype._ptr(T, container, solid=True) elif T is llmemory.Address: if cobj is None: llobj = llmemory.NULL else: llobj = _lladdress(cobj) elif T is lltype.Char: llobj = chr(cobj) elif T is lltype.UniChar: llobj = unichr(cobj) elif T is lltype.Signed: llobj = cobj elif T is lltype.Bool: assert cobj == True or cobj == False # 0 and 1 work too llobj = bool(cobj) elif T is lltype.SingleFloat: if isinstance(cobj, ctypes.c_float): cobj = cobj.value llobj = r_singlefloat(cobj) elif T is lltype.Void: llobj = cobj else: from pypy.rpython.lltypesystem import rffi try: inttype = rffi.platform.numbertype_to_rclass[T] except KeyError: llobj = cobj else: llobj = inttype(cobj) assert lltype.typeOf(llobj) == T return llobj
def f(a): a = float(r_singlefloat(a)) a *= 4.25 return float(r_singlefloat(a))
def __init__(self, space, default): if default: fval = float(rfloat.rstring_to_float(default)) else: fval = float(0.) self.default = r_singlefloat(fval)
from pypy.rpython.lltypesystem import lloperation from pypy.rpython.lltypesystem.llmemory import NULL from pypy.rpython import rtyper from pypy.rpython import rclass from pypy.rpython.rmodel import inputconst from pypy.rlib.rarithmetic import r_uint, r_longlong, r_ulonglong from pypy.rlib.rarithmetic import r_singlefloat from pypy.annotation import model as annmodel from pypy.rpython.annlowlevel import MixLevelHelperAnnotator PrimitiveErrorValue = {lltype.Signed: -1, lltype.Unsigned: r_uint(-1), lltype.SignedLongLong: r_longlong(-1), lltype.UnsignedLongLong: r_ulonglong(-1), lltype.Float: -1.0, lltype.SingleFloat: r_singlefloat(-1.0), lltype.Char: chr(255), lltype.UniChar: unichr(0xFFFF), # XXX is this always right? lltype.Bool: True, llmemory.Address: NULL, lltype.Void: None} for TYPE in rffi.NUMBER_TYPES: PrimitiveErrorValue[TYPE] = lltype.cast_primitive(TYPE, -1) del TYPE def error_value(T): if isinstance(T, lltype.Primitive): return PrimitiveErrorValue[T] elif isinstance(T, lltype.Ptr): return lltype.nullptr(T.TO)
def ctypes2lltype(T, cobj): """Convert the ctypes object 'cobj' to its lltype equivalent. 'T' is the expected lltype type. """ if T is lltype.Void: return None if isinstance(T, lltype.Ptr): if not cobj: # NULL pointer return lltype.nullptr(T.TO) if isinstance(T.TO, lltype.Struct): REAL_TYPE = T.TO if T.TO._arrayfld is not None: carray = getattr(cobj.contents, T.TO._arrayfld) container = lltype._struct(T.TO, carray.length) else: # special treatment of 'OBJECT' subclasses if get_rtyper() and lltype._castdepth(REAL_TYPE, OBJECT) >= 0: # figure out the real type of the object containerheader = lltype._struct(OBJECT) cobjheader = ctypes.cast( cobj, get_ctypes_type(lltype.Ptr(OBJECT))) struct_use_ctypes_storage(containerheader, cobjheader.contents) REAL_TYPE = get_rtyper().get_type_for_typeptr( containerheader.typeptr) REAL_T = lltype.Ptr(REAL_TYPE) cobj = ctypes.cast(cobj, get_ctypes_type(REAL_T)) container = lltype._struct(REAL_TYPE) struct_use_ctypes_storage(container, cobj.contents) if REAL_TYPE != T.TO: p = container._as_ptr() container = lltype.cast_pointer(T, p)._as_obj() # special treatment of 'OBJECT_VTABLE' subclasses if get_rtyper() and lltype._castdepth(REAL_TYPE, OBJECT_VTABLE) >= 0: # figure out the real object that this vtable points to, # and just return that p = get_rtyper().get_real_typeptr_for_typeptr( container._as_ptr()) container = lltype.cast_pointer(T, p)._as_obj() elif isinstance(T.TO, lltype.Array): if T.TO._hints.get('nolength', False): container = _array_of_unknown_length(T.TO) container._storage = cobj.contents else: container = _array_of_known_length(T.TO) container._storage = cobj.contents elif isinstance(T.TO, lltype.FuncType): cobjkey = ctypes.cast(cobj, ctypes.c_void_p).value if cobjkey in _callback2obj: container = _callback2obj[cobjkey] else: _callable = get_ctypes_trampoline(T.TO, cobj) return lltype.functionptr(T.TO, getattr(cobj, '__name__', '?'), _callable=_callable) elif isinstance(T.TO, lltype.OpaqueType): if T == llmemory.GCREF: container = _llgcopaque(cobj) else: container = lltype._opaque(T.TO) else: raise NotImplementedError(T) llobj = lltype._ptr(T, container, solid=True) elif T is llmemory.Address: if cobj is None: llobj = llmemory.NULL else: llobj = _lladdress(cobj) elif T is lltype.Char: llobj = chr(cobj) elif T is lltype.UniChar: llobj = unichr(cobj) elif T is lltype.Signed: llobj = cobj elif T is lltype.Bool: assert cobj == True or cobj == False # 0 and 1 work too llobj = bool(cobj) elif T is lltype.SingleFloat: if isinstance(cobj, ctypes.c_float): cobj = cobj.value llobj = r_singlefloat(cobj) elif T is lltype.Void: llobj = cobj else: from pypy.rpython.lltypesystem import rffi try: inttype = rffi.platform.numbertype_to_rclass[T] except KeyError: llobj = cobj else: llobj = inttype(cobj) assert lltype.typeOf(llobj) == T return llobj
def ctypes2lltype(T, cobj): """Convert the ctypes object 'cobj' to its lltype equivalent. 'T' is the expected lltype type. """ if T is lltype.Void: return None if isinstance(T, lltype.Typedef): T = T.OF if isinstance(T, lltype.Ptr): ptrval = ctypes.cast(cobj, ctypes.c_void_p).value if not cobj or not ptrval: # NULL pointer # CFunctionType.__nonzero__ is broken before Python 2.6 return lltype.nullptr(T.TO) if isinstance(T.TO, lltype.Struct): if T.TO._gckind == 'gc' and ptrval & 1: # a tagged pointer gcref = _opaque_objs[ptrval // 2].hide() return lltype.cast_opaque_ptr(T, gcref) REAL_TYPE = T.TO if T.TO._arrayfld is not None: carray = getattr(cobj.contents, T.TO._arrayfld) container = lltype._struct(T.TO, carray.length) else: # special treatment of 'OBJECT' subclasses if get_rtyper() and lltype._castdepth(REAL_TYPE, OBJECT) >= 0: # figure out the real type of the object containerheader = lltype._struct(OBJECT) cobjheader = ctypes.cast(cobj, get_ctypes_type(lltype.Ptr(OBJECT))) struct_use_ctypes_storage(containerheader, cobjheader) REAL_TYPE = get_rtyper().get_type_for_typeptr( containerheader.typeptr) REAL_T = lltype.Ptr(REAL_TYPE) cobj = ctypes.cast(cobj, get_ctypes_type(REAL_T)) container = lltype._struct(REAL_TYPE) struct_use_ctypes_storage(container, cobj) if REAL_TYPE != T.TO: p = container._as_ptr() container = lltype.cast_pointer(T, p)._as_obj() # special treatment of 'OBJECT_VTABLE' subclasses if get_rtyper() and lltype._castdepth(REAL_TYPE, OBJECT_VTABLE) >= 0: # figure out the real object that this vtable points to, # and just return that p = get_rtyper().get_real_typeptr_for_typeptr( container._as_ptr()) container = lltype.cast_pointer(T, p)._as_obj() elif isinstance(T.TO, lltype.Array): if T.TO._hints.get('nolength', False): container = _array_of_unknown_length(T.TO) container._storage = type(cobj)(cobj.contents) else: container = _array_of_known_length(T.TO) container._storage = type(cobj)(cobj.contents) elif isinstance(T.TO, lltype.FuncType): cobjkey = intmask(ctypes.cast(cobj, ctypes.c_void_p).value) if cobjkey in _int2obj: container = _int2obj[cobjkey] else: _callable = get_ctypes_trampoline(T.TO, cobj) return lltype.functionptr(T.TO, getattr(cobj, '__name__', '?'), _callable=_callable) elif isinstance(T.TO, lltype.OpaqueType): if T == llmemory.GCREF: container = _llgcopaque(cobj) else: container = lltype._opaque(T.TO) cbuf = ctypes.cast(cobj, ctypes.c_void_p) add_storage(container, _parentable_mixin, cbuf) else: raise NotImplementedError(T) llobj = lltype._ptr(T, container, solid=True) elif T is llmemory.Address: if cobj is None: llobj = llmemory.NULL else: llobj = _lladdress(cobj) elif T is lltype.Char: llobj = chr(cobj) elif T is lltype.UniChar: try: llobj = unichr(cobj) except (ValueError, OverflowError): for tc in 'HIL': if array(tc).itemsize == array('u').itemsize: import struct cobj &= 256 ** struct.calcsize(tc) - 1 llobj = array('u', array(tc, (cobj,)).tostring())[0] break else: raise elif T is lltype.Signed: llobj = cobj elif T is lltype.Bool: assert cobj == True or cobj == False # 0 and 1 work too llobj = bool(cobj) elif T is lltype.SingleFloat: if isinstance(cobj, ctypes.c_float): cobj = cobj.value llobj = r_singlefloat(cobj) elif T is lltype.LongFloat: if isinstance(cobj, ctypes.c_longdouble): cobj = cobj.value llobj = r_longfloat(cobj) elif T is lltype.Void: llobj = cobj else: from pypy.rpython.lltypesystem import rffi try: inttype = rffi.platform.numbertype_to_rclass[T] except KeyError: llobj = cobj else: llobj = inttype(cobj) assert lltype.typeOf(llobj) == T return llobj
def _unwrap_object(self, space, w_obj): return r_singlefloat(space.float_w(w_obj))