Beispiel #1
0
    def test_structcopy(self):
        X2 = lltype.Struct('X2', ('x', LONG))
        X1 = lltype.Struct('X1', ('a', LONG), ('x2', X2),
                           ('p', lltype.Ptr(X2)))

        def f():
            p2 = make(X2, x=123)
            p1 = make(X1, a=5, p=p2)
            p1.x2.x = 456
            p1bis = make(X1)
            p2bis = make(X2)
            structcopy(p1bis, p1)
            assert p1bis.a == 5
            assert p1bis.x2.x == 456
            assert p1bis.p == p2
            structcopy(p2bis, p2)
            res = p2bis.x
            lltype.free(p2bis, flavor='raw')
            lltype.free(p1bis, flavor='raw')
            lltype.free(p2, flavor='raw')
            lltype.free(p1, flavor='raw')
            return res

        assert f() == 123
        res = interpret(f, [])
        assert res == 123
Beispiel #2
0
 def test_interior_ptr_with_index_and_field(self):
     py.test.skip("llptr support not really useful any more")
     S = lltype.Struct("S", ('x', lltype.Signed))
     T = lltype.Struct("T", ('s', S))
     U = lltype.GcArray(T)
     def f(x):
         u = lltype.malloc(U, 1)
         u[0].s.x = x
         return u[0].s.x
     graph = self.check(f, [int], [42], 42)
Beispiel #3
0
def test_sizeof():
    # this is mostly an "assert not raises" sort of test
    array = lltype.Array(lltype.Signed)
    struct = lltype.Struct("S", ('x', lltype.Signed))
    varstruct = lltype.Struct("S", ('x', lltype.Signed), ('y', array))
    sizeof(struct)
    sizeof(lltype.Signed)
    py.test.raises(AssertionError, "sizeof(array)")
    py.test.raises(AssertionError, "sizeof(varstruct)")
    sizeof(array, 1)
    sizeof(varstruct, 2)
Beispiel #4
0
    def test_interior_ptr_with_index_and_field(self):
        S = lltype.Struct("S", ('x', lltype.Signed))
        T = lltype.Struct("T", ('s', S))
        U = lltype.GcArray(T)

        def f(x):
            u = lltype.malloc(U, 1)
            u[0].s.x = x
            return u[0].s.x

        graph = self.check(f, [int], [42], 42)
Beispiel #5
0
    def test_indirect_recursive_struct_more(self):
        NODE = lltype.ForwardReference()
        NODE2 = lltype.Struct('NODE2', ('ping', lltype.Ptr(NODE)))
        NODE.become(lltype.Struct('NODE', ('pong', NODE2)))

        # Building NODE2 first used to fail.
        get_ctypes_type(NODE2)

        CNODEPTR = get_ctypes_type(NODE)
        pc = CNODEPTR()
        pc.pong.ping = ctypes.pointer(pc)
        p = ctypes2lltype(lltype.Ptr(NODE), ctypes.pointer(pc))
        assert p.pong.ping == p
Beispiel #6
0
def test_raw_free_with_hdr():
    from pypy.rpython.memory.gcheader import GCHeaderBuilder

    HDR = lltype.Struct('h', ('t', lltype.Signed))
    gh = GCHeaderBuilder(HDR).size_gc_header

    A = lltype.GcArray(lltype.Signed)
    adr = raw_malloc(gh + sizeof(A, 10))
    p_a = cast_adr_to_ptr(adr + gh, lltype.Ptr(A))
    p_a[0] = 1
    adr = cast_ptr_to_adr(p_a) - gh
    raw_free(adr)
    py.test.raises(RuntimeError, "p_a[0]")
    py.test.raises(RuntimeError, "p_a[0] = 2")
    repr(adr)
    str(p_a)

    S = lltype.GcStruct('S', ('x', lltype.Signed))
    adr = raw_malloc(gh + sizeof(S))
    p_s = cast_adr_to_ptr(adr + gh, lltype.Ptr(S))
    p_s.x = 1
    adr = cast_ptr_to_adr(p_s) - gh
    raw_free(adr)
    py.test.raises(RuntimeError, "p_s.x")
    py.test.raises(RuntimeError, "p_s.x = 2")
    repr(adr)
    str(p_s)

    T = lltype.GcStruct('T', ('s', S))
    adr = raw_malloc(gh + sizeof(T))
    p_s = cast_adr_to_ptr(adr + gh, lltype.Ptr(S))
    p_s.x = 1
    adr = cast_ptr_to_adr(p_s) - gh
    raw_free(adr)
    py.test.raises(RuntimeError, "p_s.x")
    py.test.raises(RuntimeError, "p_s.x = 2")
    repr(adr)
    str(p_s)

    U = lltype.Struct('U', ('y', lltype.Signed))
    T = lltype.GcStruct('T', ('x', lltype.Signed), ('u', U))
    adr = raw_malloc(gh + sizeof(T))
    p_t = cast_adr_to_ptr(adr + gh, lltype.Ptr(T))
    p_u = p_t.u
    p_u.y = 1
    adr = cast_ptr_to_adr(p_t) - gh
    raw_free(adr)
    py.test.raises(RuntimeError, "p_u.y")
    py.test.raises(RuntimeError, "p_u.y = 2")
    repr(adr)
    str(p_u)
Beispiel #7
0
    def test_substructures(self):
        S1 = lltype.Struct('S1', ('x', lltype.Signed))
        BIG = lltype.Struct('BIG', ('s1a', S1), ('s1b', S1))
        s = lltype.malloc(BIG, flavor='raw')
        s.s1a.x = 123
        s.s1b.x = 456
        sc = lltype2ctypes(s)
        assert sc.contents.s1a.x == 123
        assert sc.contents.s1b.x == 456
        sc.contents.s1a.x += 1
        sc.contents.s1b.x += 10
        assert s.s1a.x == 124
        assert s.s1b.x == 466
        s.s1a.x += 3
        s.s1b.x += 30
        assert sc.contents.s1a.x == 127
        assert sc.contents.s1b.x == 496
        lltype.free(s, flavor='raw')

        s = lltype.malloc(BIG, flavor='raw')
        s1ac = lltype2ctypes(s.s1a)
        s1ac.contents.x = 53
        sc = lltype2ctypes(s)
        assert sc.contents.s1a.x == 53
        sc.contents.s1a.x += 1
        assert s1ac.contents.x == 54
        assert s.s1a.x == 54
        s.s1a.x += 2
        assert s1ac.contents.x == 56
        assert sc.contents.s1a.x == 56
        sc.contents.s1a.x += 3
        assert s1ac.contents.x == 59
        assert s.s1a.x == 59

        t = ctypes2lltype(lltype.Ptr(BIG), sc)
        assert t == s
        assert t.s1a == s.s1a
        assert t.s1a.x == 59
        s.s1b.x = 8888
        assert t.s1b == s.s1b
        assert t.s1b.x == 8888
        t1 = ctypes2lltype(lltype.Ptr(S1), s1ac)
        assert t.s1a == t1
        assert t1.x == 59
        t1.x += 1
        assert sc.contents.s1a.x == 60
        lltype.free(s, flavor='raw')
        assert not ALLOCATED  # detects memory leaks in the test
Beispiel #8
0
    def test_raw_malloc(self):
        py.test.skip("Exploding")
        S = lltype.Struct('x', ('x', lltype.Signed))
        def f():
            p = lltype.malloc(S, flavor='raw')

        hs = self.hannotate(f, [], policy=P_NOVIRTUAL)
Beispiel #9
0
 def test_struct_fields(self):
     longsize = 4 if IS_32_BIT else 8
     POINT = lltype.Struct(
         'POINT',
         ('x', rffi.LONG),
         ('y', rffi.SHORT),
         ('z', rffi.VOIDP),
     )
     y_ofs = longsize
     z_ofs = longsize * 2
     p = lltype.malloc(POINT, flavor='raw')
     p.x = 42
     p.y = rffi.cast(rffi.SHORT, -1)
     p.z = rffi.cast(rffi.VOIDP, 0x1234)
     addr = rffi.cast(rffi.VOIDP, p)
     assert struct_getfield_int(types.slong, addr, 0) == 42
     assert struct_getfield_int(types.sshort, addr, y_ofs) == -1
     assert struct_getfield_int(types.pointer, addr, z_ofs) == 0x1234
     #
     struct_setfield_int(types.slong, addr, 0, 43)
     struct_setfield_int(types.sshort, addr, y_ofs,
                         0x1234FFFE)  # 0x1234 is masked out
     struct_setfield_int(types.pointer, addr, z_ofs, 0x4321)
     assert p.x == 43
     assert p.y == -2
     assert rffi.cast(rffi.LONG, p.z) == 0x4321
     #
     lltype.free(p, flavor='raw')
Beispiel #10
0
def test_del_basic():
    for gcpolicy in ["ref"]:  #, "framework"]:
        S = lltype.GcStruct('S', ('x', lltype.Signed), rtti=True)
        TRASH = lltype.GcStruct('TRASH', ('x', lltype.Signed))
        GLOBAL = lltype.Struct('GLOBAL', ('x', lltype.Signed))
        glob = lltype.malloc(GLOBAL, immortal=True)

        def destructor(s):
            glob.x = s.x + 1

        def type_info_S(s):
            return lltype.getRuntimeTypeInfo(S)

        def g(n):
            s = lltype.malloc(S)
            s.x = n
            # now 's' should go away
        def entrypoint(n):
            g(n)
            # llop.gc__collect(lltype.Void)
            return glob.x

        t = TranslationContext()
        t.buildannotator().build_types(entrypoint, [int])
        rtyper = t.buildrtyper()
        destrptr = rtyper.annotate_helper_fn(destructor, [lltype.Ptr(S)])
        rtyper.attachRuntimeTypeInfoFunc(S, type_info_S, destrptr=destrptr)
        rtyper.specialize()
        fn = compile_func(entrypoint, None, t, gcpolicy=gcpolicy)

        res = fn(123)
        assert res == 124
Beispiel #11
0
 def test_arrayofstruct(self):
     S1 = lltype.Struct('S1', ('x', lltype.Signed))
     A = lltype.Array(S1, hints={'nolength': True})
     a = lltype.malloc(A, 5, flavor='raw')
     a[0].x = 100
     a[1].x = 101
     a[2].x = 102
     a[3].x = 103
     a[4].x = 104
     ac = lltype2ctypes(a, normalize=False)
     assert ac.contents.items[0].x == 100
     assert ac.contents.items[2].x == 102
     ac.contents.items[3].x += 500
     assert a[3].x == 603
     a[4].x += 600
     assert ac.contents.items[4].x == 704
     a1 = ctypes2lltype(lltype.Ptr(A), ac)
     assert a1 == a
     assert a1[2].x == 102
     aitem1 = ctypes2lltype(lltype.Ptr(S1),
                            ctypes.pointer(ac.contents.items[1]))
     assert aitem1.x == 101
     assert aitem1 == a1[1]
     lltype.free(a, flavor='raw')
     assert not ALLOCATED  # detects memory leaks in the test
Beispiel #12
0
 def test_cstruct_to_ll(self):
     S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
     s = lltype.malloc(S, flavor='raw')
     s2 = lltype.malloc(S, flavor='raw')
     s.x = 123
     sc = lltype2ctypes(s)
     t = ctypes2lltype(lltype.Ptr(S), sc)
     assert lltype.typeOf(t) == lltype.Ptr(S)
     assert s == t
     assert not (s != t)
     assert t == s
     assert not (t != s)
     assert t != lltype.nullptr(S)
     assert not (t == lltype.nullptr(S))
     assert lltype.nullptr(S) != t
     assert not (lltype.nullptr(S) == t)
     assert t != s2
     assert not (t == s2)
     assert s2 != t
     assert not (s2 == t)
     assert t.x == 123
     t.x += 1
     assert s.x == 124
     s.x += 1
     assert t.x == 125
     lltype.free(s, flavor='raw')
     lltype.free(s2, flavor='raw')
     assert not ALLOCATED  # detects memory leaks in the test
Beispiel #13
0
    def test_uninitialized2ctypes(self):
        # for now, uninitialized fields are filled with 0xDD in the ctypes data
        def checkobj(o, size):
            p = ctypes.cast(ctypes.c_void_p(ctypes.addressof(o)),
                            ctypes.POINTER(ctypes.c_ubyte * size))
            for i in range(size):
                assert p.contents[i] == 0xDD

        def checkval(v, fmt):
            res = struct.pack(fmt, v)
            assert res == "\xDD" * len(res)

        checkval(uninitialized2ctypes(rffi.CHAR), 'B')
        checkval(uninitialized2ctypes(rffi.SHORT), 'h')
        checkval(uninitialized2ctypes(rffi.INT), 'i')
        checkval(uninitialized2ctypes(rffi.UINT), 'I')
        checkval(uninitialized2ctypes(rffi.LONGLONG), 'q')
        checkval(uninitialized2ctypes(rffi.DOUBLE), 'd')
        checkobj(uninitialized2ctypes(rffi.INTP),
                 ctypes.sizeof(ctypes.c_void_p))
        checkobj(uninitialized2ctypes(rffi.CCHARP),
                 ctypes.sizeof(ctypes.c_void_p))

        S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
        s = lltype.malloc(S, flavor='raw')
        sc = lltype2ctypes(s)
        checkval(sc.contents.x, 'l')
        checkval(sc.contents.y, 'l')
        lltype.free(s, flavor='raw')
        assert not ALLOCATED  # detects memory leaks in the test
Beispiel #14
0
    def test_degenerated_merge_cross_substructure(self):
        py.test.skip("no longer a valid test")
        from pypy.rlib import objectmodel
        S = lltype.Struct('S', ('n', lltype.Signed))
        T = lltype.GcStruct('T', ('s', S), ('s1', S), ('n', lltype.Float))

        def ll_function(flag):
            t = lltype.malloc(T)
            t.s.n = 3
            t.s1.n = 3
            if flag:
                s = t.s
            else:
                s = t.s1
            objectmodel.keepalive_until_here(t)
            return s, t
        hs = self.hannotate(ll_function, [bool])    
        assert isinstance(hs, SomeLLAbstractContainer)
        assert not hs.contentdef.degenerated
        assert len(hs.contentdef.fields) == 2
        hs0 = hs.contentdef.fields['item0'].s_value       # 's'
        assert isinstance(hs0, SomeLLAbstractContainer)
        assert hs0.contentdef.degenerated
        hs1 = hs.contentdef.fields['item1'].s_value       # 't'
        assert isinstance(hs1, SomeLLAbstractContainer)
        assert hs1.contentdef.degenerated
Beispiel #15
0
 def test_array_fields(self):
     POINT = lltype.Struct(
         "POINT",
         ("x", lltype.Float),
         ("y", lltype.Float),
     )
     points = lltype.malloc(rffi.CArray(POINT), 2, flavor="raw")
     points[0].x = 1.0
     points[0].y = 2.0
     points[1].x = 3.0
     points[1].y = 4.0
     points = rffi.cast(rffi.CArrayPtr(lltype.Char), points)
     assert array_getitem(types.double, 16, points, 0, 0) == 1.0
     assert array_getitem(types.double, 16, points, 0, 8) == 2.0
     assert array_getitem(types.double, 16, points, 1, 0) == 3.0
     assert array_getitem(types.double, 16, points, 1, 8) == 4.0
     #
     array_setitem(types.double, 16, points, 0, 0, 10.0)
     array_setitem(types.double, 16, points, 0, 8, 20.0)
     array_setitem(types.double, 16, points, 1, 0, 30.0)
     array_setitem(types.double, 16, points, 1, 8, 40.0)
     #
     assert array_getitem(types.double, 16, points, 0, 0) == 10.0
     assert array_getitem(types.double, 16, points, 0, 8) == 20.0
     assert array_getitem(types.double, 16, points, 1, 0) == 30.0
     assert array_getitem(types.double, 16, points, 1, 8) == 40.0
     #
     lltype.free(points, flavor="raw")
Beispiel #16
0
    def test_prebuilt_list_of_addresses(self):
        from pypy.rpython.lltypesystem import llmemory
        
        TP = lltype.Struct('x', ('y', lltype.Signed))
        a = lltype.malloc(TP, flavor='raw', immortal=True)
        b = lltype.malloc(TP, flavor='raw', immortal=True)
        c = lltype.malloc(TP, flavor='raw', immortal=True)
        a_a = llmemory.cast_ptr_to_adr(a)
        a0 = llmemory.cast_ptr_to_adr(a)
        assert a_a is not a0
        assert a_a == a0
        a_b = llmemory.cast_ptr_to_adr(b)
        a_c = llmemory.cast_ptr_to_adr(c)

        d = {a_a: 3, a_b: 4, a_c: 5}
        d[a0] = 8
        
        def func(i):
            if i == 0:
                ptr = a
            else:
                ptr = b
            return d[llmemory.cast_ptr_to_adr(ptr)]

        py.test.raises(TypeError, self.interpret, func, [0])
Beispiel #17
0
    def test_compiled_arena_protect(self):
        import os
        from pypy.translator.c.test.test_genc import compile
        S = lltype.Struct('S', ('x', lltype.Signed))

        #
        def fn(argv):
            testrun = int(argv[1])
            a = arena_malloc(65536, False)
            arena_reserve(a, llmemory.sizeof(S))
            p = llmemory.cast_adr_to_ptr(a + 23432, lltype.Ptr(S))
            p.x = 123
            assert p.x == 123
            arena_protect(a, 65536, True)
            result = 0
            if testrun == 1:
                print p.x  # segfault
            if testrun == 2:
                p.x = 124  # segfault
            arena_protect(a, 65536, False)
            p.x += 10
            print p.x
            return 0

        #
        t, cbuilder = self.compile(fn)
        data = cbuilder.cmdexec('0')
        assert data == '133\n'
        if has_protect:
            cbuilder.cmdexec('1', expect_crash=True)
            cbuilder.cmdexec('2', expect_crash=True)
Beispiel #18
0
def test_get_call_descr_not_translated():
    c0 = GcCache(False)
    descr1 = get_call_descr(c0, [lltype.Char, lltype.Signed], lltype.Char)
    assert descr1.get_result_size() == rffi.sizeof(lltype.Char)
    assert descr1.get_result_type() == history.INT
    assert descr1.arg_classes == "ii"
    #
    T = lltype.GcStruct('T')
    descr2 = get_call_descr(c0, [lltype.Ptr(T)], lltype.Ptr(T))
    assert descr2.get_result_size() == rffi.sizeof(lltype.Ptr(T))
    assert descr2.get_result_type() == history.REF
    assert descr2.arg_classes == "r"
    #
    U = lltype.GcStruct('U', ('x', lltype.Signed))
    assert descr2 == get_call_descr(c0, [lltype.Ptr(U)], lltype.Ptr(U))
    #
    V = lltype.Struct('V', ('x', lltype.Signed))
    assert (get_call_descr(c0, [],
                           lltype.Ptr(V)).get_result_type() == history.INT)
    #
    assert (get_call_descr(c0, [],
                           lltype.Void).get_result_type() == history.VOID)
    #
    descr4 = get_call_descr(c0, [lltype.Float, lltype.Float], lltype.Float)
    assert descr4.get_result_size() == rffi.sizeof(lltype.Float)
    assert descr4.get_result_type() == history.FLOAT
    assert descr4.arg_classes == "ff"
    #
    descr5 = get_call_descr(c0, [lltype.SingleFloat], lltype.SingleFloat)
    assert descr5.get_result_size() == rffi.sizeof(lltype.SingleFloat)
    assert descr5.get_result_type() == "S"
    assert descr5.arg_classes == "S"
Beispiel #19
0
    def test_primitive(self):
        assert lltype2ctypes(5) == 5
        assert lltype2ctypes('?') == ord('?')
        assert lltype2ctypes('\xE0') == 0xE0
        assert lltype2ctypes(unichr(1234)) == 1234
        assert ctypes2lltype(lltype.Signed, 5) == 5
        assert ctypes2lltype(lltype.Char, ord('a')) == 'a'
        assert ctypes2lltype(lltype.UniChar, ord(u'x')) == u'x'
        assert ctypes2lltype(lltype.Char, 0xFF) == '\xFF'
        assert lltype2ctypes(5.25) == 5.25
        assert ctypes2lltype(lltype.Float, 5.25) == 5.25
        assert lltype2ctypes(u'x') == ord(u'x')
        res = lltype2ctypes(rffi.r_singlefloat(-3.5))
        assert isinstance(res, ctypes.c_float)
        assert res.value == -3.5
        res = ctypes2lltype(lltype.SingleFloat, ctypes.c_float(-3.5))
        assert isinstance(res, rffi.r_singlefloat)
        assert float(res) == -3.5
        assert lltype2ctypes(rffi.r_ulong(-1)) == sys.maxint * 2 + 1
        res = ctypes2lltype(lltype.Unsigned, sys.maxint * 2 + 1)
        assert (res, type(res)) == (rffi.r_ulong(-1), rffi.r_ulong)

        res = lltype2ctypes(llmemory.sizeof(lltype.Signed))
        assert res == struct.calcsize("l")
        S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
        res = lltype2ctypes(llmemory.sizeof(S))
        assert res == struct.calcsize("ll")

        p = lltype.nullptr(S)
        cptr = lltype2ctypes(p)
        assert not cptr
        py.test.raises(ValueError, 'cptr.contents')  # NULL pointer access
        res = ctypes2lltype(lltype.Ptr(S), cptr)
        assert res == p
        assert not ALLOCATED  # detects memory leaks in the test
Beispiel #20
0
    def test_propagate_exception(self):
        S = lltype.Struct('S', ('flag', lltype.Signed))
        s = lltype.malloc(S, immortal=True)

        def ll_two(x):
            if x == 0:
                raise ValueError
            return x + 7

        def ll_function(y):
            res = ll_two(y)
            s.flag = 1
            return res

        s.flag = 0
        self.timeshift_raises(ValueError,
                              ll_function, [0], [],
                              policy=P_NOVIRTUAL)
        assert s.flag == 0

        s.flag = 0
        self.timeshift_raises(ValueError,
                              ll_function, [0], [0],
                              policy=P_NOVIRTUAL)
        assert s.flag == 0

        s.flag = 0
        res = self.timeshift(ll_function, [17], [0], policy=P_NOVIRTUAL)
        assert res == 24
        if self.__class__ is TestException:  # no chance to work with genc
            assert s.flag == 1
        self.check_insns({'setfield': 1})
Beispiel #21
0
 def test_recursive_struct(self):
     SX = lltype.ForwardReference()
     S1 = lltype.Struct('S1', ('p', lltype.Ptr(SX)), ('x', lltype.Signed))
     SX.become(S1)
     # a chained list
     s1 = lltype.malloc(S1, flavor='raw')
     s2 = lltype.malloc(S1, flavor='raw')
     s3 = lltype.malloc(S1, flavor='raw')
     s1.x = 111
     s2.x = 222
     s3.x = 333
     s1.p = s2
     s2.p = s3
     s3.p = lltype.nullptr(S1)
     sc1 = lltype2ctypes(s1)
     sc2 = sc1.contents.p
     sc3 = sc2.contents.p
     assert not sc3.contents.p
     assert sc1.contents.x == 111
     assert sc2.contents.x == 222
     assert sc3.contents.x == 333
     sc3.contents.x += 1
     assert s3.x == 334
     s3.x += 2
     assert sc3.contents.x == 336
     lltype.free(s1, flavor='raw')
     lltype.free(s2, flavor='raw')
     lltype.free(s3, flavor='raw')
     # a self-cycle
     s1 = lltype.malloc(S1, flavor='raw')
     s1.x = 12
     s1.p = s1
     sc1 = lltype2ctypes(s1)
     assert sc1.contents.x == 12
     assert (ctypes.addressof(sc1.contents.p.contents) == ctypes.addressof(
         sc1.contents))
     s1.x *= 5
     assert sc1.contents.p.contents.p.contents.p.contents.x == 60
     lltype.free(s1, flavor='raw')
     # a longer cycle
     s1 = lltype.malloc(S1, flavor='raw')
     s2 = lltype.malloc(S1, flavor='raw')
     s1.x = 111
     s1.p = s2
     s2.x = 222
     s2.p = s1
     sc1 = lltype2ctypes(s1)
     assert sc1.contents.x == 111
     assert sc1.contents.p.contents.x == 222
     assert (ctypes.addressof(sc1.contents.p.contents) != ctypes.addressof(
         sc1.contents))
     assert (ctypes.addressof(
         sc1.contents.p.contents.p.contents) == ctypes.addressof(
             sc1.contents))
     lltype.free(s1, flavor='raw')
     lltype.free(s2, flavor='raw')
     assert not ALLOCATED  # detects memory leaks in the test
Beispiel #22
0
def test_recursive_llhelper():
    from pypy.rpython.annlowlevel import llhelper
    from pypy.rpython.lltypesystem import lltype
    from pypy.rlib.objectmodel import specialize
    from pypy.rlib.nonconst import NonConstant
    FT = lltype.ForwardReference()
    FTPTR = lltype.Ptr(FT)
    STRUCT = lltype.Struct("foo", ("bar", FTPTR))
    FT.become(lltype.FuncType([lltype.Ptr(STRUCT)], lltype.Signed))

    class A:
        def __init__(self, func, name):
            self.func = func
            self.name = name

        def _freeze_(self):
            return True

        @specialize.memo()
        def make_func(self):
            f = getattr(self, "_f", None)
            if f is not None:
                return f
            f = lambda *args: self.func(*args)
            f.c_name = self.name
            f.relax_sig_check = True
            f.__name__ = "WRAP%s" % (self.name, )
            self._f = f
            return f

        def get_llhelper(self):
            return llhelper(FTPTR, self.make_func())

    def f(s):
        if s.bar == t.bar:
            lltype.free(s, flavor="raw")
            return 1
        lltype.free(s, flavor="raw")
        return 0

    def g(x):
        return 42

    def chooser(x):
        s = lltype.malloc(STRUCT, flavor="raw")
        if x:
            s.bar = llhelper(FTPTR, a_f.make_func())
        else:
            s.bar = llhelper(FTPTR, a_g.make_func())
        return f(s)

    a_f = A(f, "f")
    a_g = A(g, "g")
    t = lltype.malloc(STRUCT, flavor="raw", immortal=True)
    t.bar = llhelper(FTPTR, a_f.make_func())
    fn = compile(chooser, [bool])
    assert fn(True)
Beispiel #23
0
    def create_lowlevel_type(self):
        entry_methods = {
            "valid": LLOrderedDict.ll_valid_from_flag,
            "everused": LLOrderedDict.ll_everused_from_flag,
            "mark_deleted": LLOrderedDict.ll_mark_deleted_in_flag,
            "must_clear_key": self._must_clear(self.key_repr.lowleveltype),
            "must_clear_value": self._must_clear(self.value_repr.lowleveltype),
        }
        fields = [
            ("key", self.key_repr.lowleveltype),
            ("value", self.value_repr.lowleveltype),
            ("next", lltype.Signed),
            ("prev", lltype.Signed),
            ("everused", lltype.Bool),
            ("valid", lltype.Bool),
        ]
        fast_hash_func = None
        if not self.hash_func_repr:
            fast_hash_func = self.key_repr.get_ll_hash_function()
        if fast_hash_func is None:
            fields.append(("hash", lltype.Signed))
            entry_methods["hash"] = LLOrderedDict.ll_hash_from_cache
        else:
            entry_methods["hash"] = LLOrderedDict.ll_hash_recompute
            entry_methods["fast_hash_func"] = fast_hash_func
        DICTENTRY = lltype.Struct("ORDEREDDICTENTRY", *fields)

        fields = [
            ("num_items", lltype.Signed),
            ("resize_counter", lltype.Signed),
            ("first_entry", lltype.Signed),
            ("last_entry", lltype.Signed),
            ("entries",
             lltype.Ptr(lltype.GcArray(DICTENTRY, adtmeths=entry_methods))),
        ]
        dict_methods = {}
        if self.eq_func_repr and self.hash_func_repr:
            dict_methods["paranoia"] = True
            dict_methods["hashkey"] = LLOrderedDict.ll_hashkey_custom
            dict_methods["keyeq"] = LLOrderedDict.ll_keyeq_custom

            dict_methods["r_hashkey"] = self.hash_func_repr
            dict_methods["r_keyeq"] = self.eq_func_repr

            fields.append(("hashkey_func", self.hash_func_repr.lowleveltype))
            fields.append(("keyeq_func", self.eq_func_repr.lowleveltype))
        else:
            dict_methods["paranoia"] = False
            dict_methods["hashkey"] = lltype.staticAdtMethod(
                self.key_repr.get_ll_hash_function())
            ll_keyeq = self.key_repr.get_ll_eq_function()
            if ll_keyeq is not None:
                ll_keyeq = lltype.staticAdtMethod(ll_keyeq)
            dict_methods["keyeq"] = ll_keyeq

        DICT = lltype.GcStruct("ORDEREDDICT", *fields, adtmeths=dict_methods)
        return lltype.Ptr(DICT)
Beispiel #24
0
 def test_interior_ptr_with_field_and_index(self):
     py.test.skip("llptr support not really useful any more")
     S = lltype.Struct("S", ('x', lltype.Signed))
     T = lltype.GcStruct("T", ('items', lltype.Array(S)))
     def f(x):
         t = lltype.malloc(T, 1)
         t.items[0].x = x
         return t.items[0].x
     graph = self.check(f, [int], [42], 42)
Beispiel #25
0
 def test_interior_ptr(self):
     py.test.skip("llptr support not really useful any more")
     S = lltype.Struct("S", ('x', lltype.Signed))
     T = lltype.GcStruct("T", ('s', S))
     def f(x):
         t = lltype.malloc(T)
         t.s.x = x
         return t.s.x
     graph = self.check(f, [int], [42], 42)
Beispiel #26
0
 def test_varsized_struct(self):
     STR = lltype.Struct(
         'rpy_string', ('hash', lltype.Signed),
         ('chars', lltype.Array(lltype.Char, hints={'immutable': True})))
     s = lltype.malloc(STR, 3, flavor='raw')
     one = force_cast(rffi.VOIDP, s)
     # sanity check
     #assert lltype2ctypes(one).contents.items._length_ > 0
     two = force_cast(lltype.Ptr(STR), one)
     assert s == two
Beispiel #27
0
def test_complex_struct():
    A = lltype.Array(lltype.Signed)
    # XXX WHY cant we create a varsize array as last elemen here? :-(
    S2 = lltype.Struct('s2', ('a', lltype.Signed))  # ('a', A)
    S3 = lltype.Struct('s3', ('s', lltype.Signed), ('s2', S2))
    SBASE = lltype.GcStruct('base', ('a', lltype.Signed), ('b', S3))
    SBASEPTR = lltype.Ptr(SBASE)

    sizeofsbase = llmemory.sizeof(SBASE)
    offset_toa = offsetofs(SBASE, 'b', 's2', 'a')

    def complex_struct():
        adr = llmemory.raw_malloc(sizeofsbase)
        s = llmemory.cast_adr_to_ptr(adr, SBASEPTR)
        s.b.s2.a = 42
        return (adr + offset_toa).signed[0]

    fn = compile_function(complex_struct, [])
    assert fn() == 42
Beispiel #28
0
def test_structarray_add():
    S = lltype.Struct("S", ("x", lltype.Signed))
    for a in [lltype.malloc(lltype.GcArray(S), 5),
              lltype.malloc(lltype.FixedSizeArray(S, 5), immortal=True)]:
        a[3].x = 42
        adr_s = cast_ptr_to_adr(a)
        adr_s += itemoffsetof(lltype.typeOf(a).TO, 0)
        adr_s += sizeof(S) * 3
        s = cast_adr_to_ptr(adr_s, lltype.Ptr(S))
        assert s.x == 42
Beispiel #29
0
    def test_interior_ptr_with_index(self):
        S = lltype.Struct("S", ('x', lltype.Signed))
        T = lltype.GcArray(S)

        def f(x):
            t = lltype.malloc(T, 1)
            t[0].x = x
            return t[0].x

        graph = self.check(f, [int], [42], 42)
Beispiel #30
0
    def test_interior_ptr_with_field_and_index(self):
        S = lltype.Struct("S", ('x', lltype.Signed))
        T = lltype.GcStruct("T", ('items', lltype.Array(S)))

        def f(x):
            t = lltype.malloc(T, 1)
            t.items[0].x = x
            return t.items[0].x

        graph = self.check(f, [int], [42], 42)