Exemple #1
0
    def test_interior_ptrs(self):
        from pypy.rpython.lltypesystem.lltype import Struct, GcStruct, GcArray
        from pypy.rpython.lltypesystem.lltype import Array, Signed, malloc

        S1 = Struct("S1", ('x', Signed))
        T1 = GcStruct("T1", ('s', S1))

        def f1():
            t = malloc(T1)
            t.s.x = 1
            return t.s.x

        S2 = Struct("S2", ('x', Signed))
        T2 = GcArray(S2)

        def f2():
            t = malloc(T2, 1)
            t[0].x = 1
            return t[0].x

        S3 = Struct("S3", ('x', Signed))
        T3 = GcStruct("T3", ('items', Array(S3)))

        def f3():
            t = malloc(T3, 1)
            t.items[0].x = 1
            return t.items[0].x

        S4 = Struct("S4", ('x', Signed))
        T4 = Struct("T4", ('s', S4))
        U4 = GcArray(T4)

        def f4():
            u = malloc(U4, 1)
            u[0].s.x = 1
            return u[0].s.x

        S5 = Struct("S5", ('x', Signed))
        T5 = GcStruct("T5", ('items', Array(S5)))

        def f5():
            t = malloc(T5, 1)
            return len(t.items)

        T6 = GcStruct("T6", ('s', Array(Signed)))

        def f6():
            t = malloc(T6, 1)
            t.s[0] = 1
            return t.s[0]

        def func():
            return (f1() * 100000 + f2() * 10000 + f3() * 1000 + f4() * 100 +
                    f5() * 10 + f6())

        assert func() == 111111
        run = self.runner(func)
        res = run([])
        assert res == 111111
Exemple #2
0
    def setup_vtable(self, vtable, rsubcls):
        """Initialize the 'self' portion of the 'vtable' belonging to the
        given subclass."""
        if self.classdef is None:
            # initialize the 'subclassrange_*' and 'name' fields
            if rsubcls.classdef is not None:
                #vtable.parenttypeptr = rsubcls.rbase.getvtable()
                vtable.subclassrange_min = rsubcls.classdef.minid
                vtable.subclassrange_max = rsubcls.classdef.maxid
            else: #for the root class
                vtable.subclassrange_min = 0
                vtable.subclassrange_max = sys.maxint
            rinstance = getinstancerepr(self.rtyper, rsubcls.classdef)
            rinstance.setup()
            if rinstance.gcflavor == 'gc':
                vtable.rtti = getRuntimeTypeInfo(rinstance.object_type)
            if rsubcls.classdef is None:
                name = 'object'
            else:
                name = rsubcls.classdef.shortname
            vtable.name = malloc(Array(Char), len(name)+1, immortal=True)
            for i in range(len(name)):
                vtable.name[i] = name[i]
            vtable.name[len(name)] = '\x00'
            if hasattr(rsubcls.classdef, 'my_instantiate_graph'):
                graph = rsubcls.classdef.my_instantiate_graph
                vtable.instantiate = self.rtyper.getcallable(graph)
            #else: the classdef was created recently, so no instantiate()
            #      could reach it
        else:
            # setup class attributes: for each attribute name at the level
            # of 'self', look up its value in the subclass rsubcls
            def assign(mangled_name, value):
                if isinstance(value, Constant) and isinstance(value.value, staticmethod):
                    value = Constant(value.value.__get__(42))   # staticmethod => bare function
                llvalue = r.convert_desc_or_const(value)
                setattr(vtable, mangled_name, llvalue)

            mro = list(rsubcls.classdef.getmro())
            for fldname in self.clsfields:
                mangled_name, r = self.clsfields[fldname]
                if r.lowleveltype is Void:
                    continue
                value = rsubcls.classdef.classdesc.read_attribute(fldname, None)
                if value is not None:
                    assign(mangled_name, value)
            # extra PBC attributes
            for (access_set, attr), (mangled_name, r) in self.pbcfields.items():
                if rsubcls.classdef.classdesc not in access_set.descs:
                    continue   # only for the classes in the same pbc access set
                if r.lowleveltype is Void:
                    continue
                attrvalue = rsubcls.classdef.classdesc.read_attribute(attr, None)
                if attrvalue is not None:
                    assign(mangled_name, attrvalue)

            # then initialize the 'super' portion of the vtable
            self.rbase.setup_vtable(vtable.super, rsubcls)
Exemple #3
0
def conversion_table(r_from, r_to):
    if r_to in r_from._conversion_tables:
        return r_from._conversion_tables[r_to]
    else:
        t = malloc(Array(Char), len(r_from.descriptions), immortal=True)
        l = []
        for i, d in enumerate(r_from.descriptions):
            if d in r_to.descriptions:
                j = r_to.descriptions.index(d)
                l.append(j)
                t[i] = chr(j)
            else:
                l.append(None)
        if l == range(len(r_from.descriptions)):
            r = None
        else:
            r = inputconst(Ptr(Array(Char)), t)
        r_from._conversion_tables[r_to] = r
        return r
Exemple #4
0
def test_scoped_allocator():
    from pypy.rpython.lltypesystem.lltype import scoped_alloc, Array, Signed
    T = Array(Signed)
    
    def f():
        x = 0
        with scoped_alloc(T, 1) as array:
            array[0] = -42
            x = array[0]
        assert x == -42

    res = interpret(f, [])
Exemple #5
0
 def _setup_repr(self):
     if self.s_pbc.subset_of:
         assert self.s_pbc.can_be_None == self.s_pbc.subset_of.can_be_None
         r = self.rtyper.getrepr(self.s_pbc.subset_of)
         if r is not self:
             r.setup()
             self.descriptions = r.descriptions
             self.c_pointer_table = r.c_pointer_table
             return
     self.descriptions = list(self.s_pbc.descriptions)
     if self.s_pbc.can_be_None:
         self.descriptions.insert(0, None)
     POINTER_TABLE = Array(self.pointer_repr.lowleveltype)
     pointer_table = malloc(POINTER_TABLE, len(self.descriptions),
                            immortal=True)
     for i, desc in enumerate(self.descriptions):
         if desc is not None:
             pointer_table[i] = self.pointer_repr.convert_desc(desc)
         else:
             pointer_table[i] = self.pointer_repr.convert_const(None)
     self.c_pointer_table = inputconst(Ptr(POINTER_TABLE), pointer_table)
Exemple #6
0
mallocstr = new_malloc(STR)
mallocunicode = new_malloc(UNICODE)


def emptystrfun():
    return emptystr


def emptyunicodefun():
    return emptyunicode


STR.become(
    GcStruct('rpy_string', ('hash', Signed),
             ('chars', Array(Char, hints={'immutable': True})),
             adtmeths={
                 'malloc': staticAdtMethod(mallocstr),
                 'empty': staticAdtMethod(emptystrfun)
             }))
UNICODE.become(
    GcStruct('rpy_unicode', ('hash', Signed),
             ('chars', Array(UniChar, hints={'immutable': True})),
             adtmeths={
                 'malloc': staticAdtMethod(mallocunicode),
                 'empty': staticAdtMethod(emptyunicodefun)
             }))
SIGNED_ARRAY = GcArray(Signed)
CONST_STR_CACHE = WeakValueDictionary()
CONST_UNICODE_CACHE = WeakValueDictionary()
Exemple #7
0
def alloc_array_name(name):
    p = malloc(Array(Char), len(name) + 1, immortal=True)
    for i in range(len(name)):
        p[i] = name[i]
    p[len(name)] = '\x00'
    return p
Exemple #8
0
OBJECT = GcStruct('object', ('typeptr', CLASSTYPE),
                  hints={
                      'immutable': True,
                      'shouldntbenull': True,
                      'typeptr': True
                  },
                  rtti=True)
OBJECTPTR = Ptr(OBJECT)
OBJECT_VTABLE.become(
    Struct(
        'object_vtable',
        #('parenttypeptr', CLASSTYPE),
        ('subclassrange_min', Signed),
        ('subclassrange_max', Signed),
        ('rtti', Ptr(RuntimeTypeInfo)),
        ('name', Ptr(Array(Char))),
        ('instantiate', Ptr(FuncType([], OBJECTPTR))),
        hints={'immutable': True}))
# non-gc case
NONGCOBJECT = Struct('nongcobject', ('typeptr', CLASSTYPE))
NONGCOBJECTPTR = Ptr(NONGCOBJECT)

OBJECT_BY_FLAVOR = {'gc': OBJECT, 'raw': NONGCOBJECT}

LLFLAVOR = {
    'gc': 'gc',
    'raw': 'raw',
    'stack': 'raw',
}

Exemple #9
0
            i //= 10
            len += 1
    len += sign
    result = mallocstr(len)
    result.hash = 0
    if sign:
        result.chars[0] = '-'
        j = 1
    else:
        j = 0
    while j < len:
        result.chars[j] = temp[len-j-1]
        j += 1
    return result

hex_chars = malloc(Array(Char), 16, immortal=True)

for i in range(16):
    hex_chars[i] = "%x"%i

def ll_int2hex(i, addPrefix):
    from pypy.rpython.lltypesystem.rstr import mallocstr
    temp = malloc(CHAR_ARRAY, 20)
    len = 0
    sign = 0
    if i < 0:
        sign = 1
        i = r_uint(-i)
    else:
        i = r_uint(i)
    if i == 0:
Exemple #10
0
    def make_pyexcclass2exc(self, rtyper):
        # ll_pyexcclass2exc(python_exception_class) -> exception_instance
        table = {}
        Exception_def = rtyper.annotator.bookkeeper.getuniqueclassdef(
            Exception)
        for clsdef in rtyper.class_reprs:
            if (clsdef and clsdef is not Exception_def
                    and clsdef.issubclass(Exception_def)):
                if not hasattr(clsdef.classdesc, 'pyobj'):
                    continue
                cls = clsdef.classdesc.pyobj
                if cls in self.standardexceptions and cls not in FORCE_ATTRIBUTES_INTO_CLASSES:
                    is_standard = True
                    assert not clsdef.attrs, (
                        "%r should not have grown attributes" % (cls, ))
                else:
                    is_standard = (cls.__module__ == 'exceptions'
                                   and not clsdef.attrs)
                if is_standard:
                    example = self.get_standard_ll_exc_instance(rtyper, clsdef)
                    table[cls] = example
                #else:
                #    assert cls.__module__ != 'exceptions', (
                #        "built-in exceptions should not grow attributes")
        r_inst = rclass.getinstancerepr(rtyper, None)
        r_inst.setup()
        default_excinst = malloc(self.lltype_of_exception_value.TO,
                                 immortal=True)
        default_excinst.typeptr = r_inst.rclass.getvtable()

        # build the table in order base classes first, subclasses last
        sortedtable = []

        def add_class(cls):
            if cls in table:
                for base in cls.__bases__:
                    add_class(base)
                sortedtable.append((cls, table[cls]))
                del table[cls]

        for cls in table.keys():
            add_class(cls)
        assert table == {}
        #print sortedtable

        A = Array(('pycls', Ptr(PyObject)),
                  ('excinst', self.lltype_of_exception_value))
        pycls2excinst = malloc(A, len(sortedtable), immortal=True)
        for i in range(len(sortedtable)):
            cls, example = sortedtable[i]
            pycls2excinst[i].pycls = pyobjectptr(cls)
            pycls2excinst[i].excinst = example

        FUNCTYPE = FuncType([Ptr(PyObject), Ptr(PyObject)], Signed)
        PyErr_GivenExceptionMatches = functionptr(
            FUNCTYPE,
            "PyErr_GivenExceptionMatches",
            external="C",
            _callable=lambda pyobj1, pyobj2: int(
                issubclass(pyobj1._obj.value, pyobj2._obj.value)))

        initial_value_of_i = len(pycls2excinst) - 1

        def ll_pyexcclass2exc(python_exception_class):
            """Return an RPython instance of the best approximation of the
            Python exception identified by its Python class.
            """
            i = initial_value_of_i
            while i >= 0:
                if PyErr_GivenExceptionMatches(python_exception_class,
                                               pycls2excinst[i].pycls):
                    return pycls2excinst[i].excinst
                i -= 1
            return default_excinst

        s_pyobj = annmodel.SomePtr(Ptr(PyObject))
        helper_fn = rtyper.annotate_helper_fn(ll_pyexcclass2exc, [s_pyobj])
        return helper_fn