示例#1
0
    def _install_multimethods(self):
        """Install all the MultiMethods into the space instance."""
        for name, mm in model.MM.__dict__.items():
            if not isinstance(mm, model.StdObjSpaceMultiMethod):
                continue
            if not hasattr(self, name):
                # int_w, str_w...: these do not return a wrapped object
                if name.endswith('_w'):
                    func = mm.install_not_sliced(self.model.typeorder,
                                                 baked_perform_call=True)
                else:
                    unsliced = mm.install_not_sliced(self.model.typeorder,
                                                     baked_perform_call=False)
                    exprargs, expr, miniglobals, fallback = unsliced
                    func = stdtypedef.make_perform_trampoline('__mm_'+name,
                                                              exprargs, expr,
                                                              miniglobals, mm)

                boundmethod = types.MethodType(func, self, self.__class__)
                setattr(self, name, boundmethod)  # store into 'space' instance
            elif self.config.objspace.std.builtinshortcut:
                if name.startswith('inplace_'):
                    fallback_name = name[len('inplace_'):]
                    if fallback_name in ('or', 'and'):
                        fallback_name += '_'
                    fallback_mm = model.MM.__dict__[fallback_name]
                else:
                    fallback_mm = None
                builtinshortcut.install(self, mm, fallback_mm)
        if self.config.objspace.std.builtinshortcut:
            builtinshortcut.install_is_true(self, model.MM.nonzero,
                                            model.MM.len)
示例#2
0
    def _install_multimethods(self):
        """Install all the MultiMethods into the space instance."""
        for name, mm in model.MM.__dict__.items():
            if not isinstance(mm, model.StdObjSpaceMultiMethod):
                continue
            if not hasattr(self, name):
                # int_w, str_w...: these do not return a wrapped object
                if name.endswith('_w'):
                    func = mm.install_not_sliced(self.model.typeorder,
                                                 baked_perform_call=True)
                else:
                    unsliced = mm.install_not_sliced(self.model.typeorder,
                                                     baked_perform_call=False)
                    exprargs, expr, miniglobals, fallback = unsliced
                    func = stdtypedef.make_perform_trampoline(
                        '__mm_' + name, exprargs, expr, miniglobals, mm)

                boundmethod = types.MethodType(func, self, self.__class__)
                setattr(self, name, boundmethod)  # store into 'space' instance
            elif self.config.objspace.std.builtinshortcut:
                if name.startswith('inplace_'):
                    fallback_name = name[len('inplace_'):]
                    if fallback_name in ('or', 'and'):
                        fallback_name += '_'
                    fallback_mm = model.MM.__dict__[fallback_name]
                else:
                    fallback_mm = None
                builtinshortcut.install(self, mm, fallback_mm)
        if self.config.objspace.std.builtinshortcut:
            builtinshortcut.install_is_true(self, model.MM.nonzero,
                                            model.MM.len)
示例#3
0
    def initialize(self):
        "NOT_RPYTHON: only for initializing the space."
        self._typecache = Cache()

        # Import all the object types and implementations
        self.model = StdTypeModel(self.config)

        class StdObjSpaceFrame(pyframe.PyFrame):
            if self.config.objspace.std.optimized_int_add:
                if self.config.objspace.std.withsmallint:
                    def BINARY_ADD(f, oparg, *ignored):
                        from pypy.objspace.std.smallintobject import \
                             W_SmallIntObject, add__SmallInt_SmallInt
                        w_2 = f.popvalue()
                        w_1 = f.popvalue()
                        if type(w_1) is W_SmallIntObject and type(w_2) is W_SmallIntObject:
                            try:
                                w_result = add__SmallInt_SmallInt(f.space, w_1, w_2)
                            except FailedToImplement:
                                w_result = f.space.add(w_1, w_2)
                        else:
                            w_result = f.space.add(w_1, w_2)
                        f.pushvalue(w_result)
                else:
                    def BINARY_ADD(f, oparg, *ignored):
                        from pypy.objspace.std.intobject import \
                             W_IntObject, add__Int_Int
                        w_2 = f.popvalue()
                        w_1 = f.popvalue()
                        if type(w_1) is W_IntObject and type(w_2) is W_IntObject:
                            try:
                                w_result = add__Int_Int(f.space, w_1, w_2)
                            except FailedToImplement:
                                w_result = f.space.add(w_1, w_2)
                        else:
                            w_result = f.space.add(w_1, w_2)
                        f.pushvalue(w_result)

            if self.config.objspace.std.optimized_list_getitem:
                def BINARY_SUBSCR(f, *ignored):
                    w_2 = f.popvalue()
                    w_1 = f.popvalue()
                    if type(w_1) is W_ListObject and type(w_2) is W_IntObject:
                        try:
                            w_result = w_1.wrappeditems[w_2.intval]
                        except IndexError:
                            raise OperationError(f.space.w_IndexError,
                                f.space.wrap("list index out of range"))
                    else:
                        w_result = f.space.getitem(w_1, w_2)
                    f.pushvalue(w_result)

            def LIST_APPEND(f, *ignored):
                w = f.popvalue()
                v = f.popvalue()
                if type(v) is W_ListObject:
                    v.append(w)
                else:
                    f.space.call_method(v, 'append', w)

            if self.config.objspace.opcodes.CALL_LIKELY_BUILTIN:
                def CALL_LIKELY_BUILTIN(f, oparg, *ignored):
                    from pypy.module.__builtin__ import OPTIMIZED_BUILTINS, Module
                    from pypy.objspace.std.dictmultiobject import W_DictMultiObject
                    w_globals = f.w_globals
                    num = oparg >> 8
                    assert isinstance(w_globals, W_DictMultiObject)
                    w_value = w_globals.implementation.get_builtin_indexed(num)
                    if w_value is None:
                        builtins = f.get_builtin()
                        assert isinstance(builtins, Module)
                        w_builtin_dict = builtins.w_dict
                        assert isinstance(w_builtin_dict, W_DictMultiObject)
                        w_value = w_builtin_dict.implementation.get_builtin_indexed(num)
        ##                 if w_value is not None:
        ##                     print "CALL_LIKELY_BUILTIN fast"
                    if w_value is None:
                        varname = OPTIMIZED_BUILTINS[num]
                        message = "global name '%s' is not defined" % varname
                        raise OperationError(f.space.w_NameError,
                                             f.space.wrap(message))
                    nargs = oparg & 0xff
                    w_function = w_value
                    try:
                        w_result = f.space.call_valuestack(w_function, nargs, f)
                        # XXX XXX fix the problem of resume points!
                        #rstack.resume_point("CALL_FUNCTION", f, nargs, returns=w_result)
                    finally:
                        f.dropvalues(nargs)
                    f.pushvalue(w_result)

            if self.config.objspace.opcodes.CALL_METHOD:
                # def LOOKUP_METHOD(...):
                from pypy.objspace.std.callmethod import LOOKUP_METHOD
                # def CALL_METHOD(...):
                from pypy.objspace.std.callmethod import CALL_METHOD

            if self.config.objspace.std.logspaceoptypes:
                _space_op_types = []
                for name, func in pyframe.PyFrame.__dict__.iteritems():
                    if hasattr(func, 'binop'):
                        operationname = func.binop
                        def make_opimpl(operationname):
                            def opimpl(f, *ignored):
                                operation = getattr(f.space, operationname)
                                w_2 = f.popvalue()
                                w_1 = f.popvalue()
                                if we_are_translated():
                                    s = operationname + ' ' + str(w_1) + ' ' + str(w_2)
                                else:
                                    s = operationname + ' ' + w_1.__class__.__name__ + ' ' + w_2.__class__.__name__
                                f._space_op_types.append(s)
                                w_result = operation(w_1, w_2)
                                f.pushvalue(w_result)
                            return func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)
                        locals()[name] = make_opimpl(operationname)
                    elif hasattr(func, 'unaryop'):
                        operationname = func.unaryop
                        def make_opimpl(operationname):
                            def opimpl(f, *ignored):
                                operation = getattr(f.space, operationname)
                                w_1 = f.popvalue()
                                if we_are_translated():
                                    s = operationname + ' ' + str(w_1)
                                else:
                                    s = operationname + ' ' + w_1.__class__.__name__
                                f._space_op_types.append(s)
                                w_result = operation(w_1)
                                f.pushvalue(w_result)
                            return func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)
                        locals()[name] = make_opimpl(operationname)

        self.FrameClass = StdObjSpaceFrame

        # XXX store the dict class on the space to access it in various places
        if self.config.objspace.std.withmultidict:
            from pypy.objspace.std import dictmultiobject
            self.DictObjectCls = dictmultiobject.W_DictMultiObject
            self.emptydictimpl = dictmultiobject.EmptyDictImplementation(self)
            if self.config.objspace.std.withbucketdict:
                from pypy.objspace.std import dictbucket
                self.DefaultDictImpl = dictbucket.BucketDictImplementation
            else:
                self.DefaultDictImpl = dictmultiobject.RDictImplementation
        else:
            from pypy.objspace.std import dictobject
            self.DictObjectCls = dictobject.W_DictObject
        assert self.DictObjectCls in self.model.typeorder

        if not self.config.objspace.std.withrope:
            from pypy.objspace.std import stringobject
            self.StringObjectCls = stringobject.W_StringObject
        else:
            from pypy.objspace.std import ropeobject
            self.StringObjectCls = ropeobject.W_RopeObject
        assert self.StringObjectCls in self.model.typeorder

        # install all the MultiMethods into the space instance
        for name, mm in self.MM.__dict__.items():
            if isinstance(mm, StdObjSpaceMultiMethod) and not hasattr(self, name):
                if name.endswith('_w'): # int_w, str_w...: these do not return a wrapped object
                    func = mm.install_not_sliced(self.model.typeorder, baked_perform_call=True)
                else:               
                    exprargs, expr, miniglobals, fallback = (
                        mm.install_not_sliced(self.model.typeorder, baked_perform_call=False))

                    func = stdtypedef.make_perform_trampoline('__mm_'+name,
                                                              exprargs, expr, miniglobals,
                                                              mm)
                
                                                  # e.g. add(space, w_x, w_y)
                def make_boundmethod(func=func):
                    def boundmethod(*args):
                        return func(self, *args)
                    return func_with_new_name(boundmethod, 'boundmethod_'+name)
                boundmethod = make_boundmethod()
                setattr(self, name, boundmethod)  # store into 'space' instance

        # hack to avoid imports in the time-critical functions below
        for cls in self.model.typeorder:
            globals()[cls.__name__] = cls
        for cls in self.model.imported_but_not_registered:
            globals()[cls.__name__] = cls

        # singletons
        self.w_None  = W_NoneObject.w_None
        self.w_False = W_BoolObject.w_False
        self.w_True  = W_BoolObject.w_True
        from pypy.interpreter.special import NotImplemented, Ellipsis
        self.w_NotImplemented = self.wrap(NotImplemented(self))  
        self.w_Ellipsis = self.wrap(Ellipsis(self))  

        # types
        for typedef in self.model.pythontypes:
            w_type = self.gettypeobject(typedef)
            setattr(self, 'w_' + typedef.name, w_type)

        # exceptions & builtins
        w_mod = self.setup_exceptions()
        self.make_builtins()
        self.sys.setmodule(w_mod)

        # dummy old-style classes types
        self.w_classobj = W_TypeObject(self, 'classobj', [self.w_object], {})
        self.w_instance = W_TypeObject(self, 'instance', [self.w_object], {})
        self.setup_old_style_classes()

        # fix up a problem where multimethods apparently don't 
        # like to define this at interp-level 
        # HACK HACK HACK
        from pypy.objspace.std.typeobject import _HEAPTYPE
        old_flags = self.w_dict.__flags__
        self.w_dict.__flags__ |= _HEAPTYPE
        self.appexec([self.w_dict], """
            (dict): 
                def fromkeys(cls, seq, value=None):
                    r = cls()
                    for s in seq:
                        r[s] = value
                    return r
                dict.fromkeys = classmethod(fromkeys)
        """)
        self.w_dict.__flags__ = old_flags

        if self.config.objspace.std.oldstyle:
            self.enable_old_style_classes_as_default_metaclass()

        # final setup
        self.setup_builtin_modules()
        # Adding transparent proxy call
        if self.config.objspace.std.withtproxy:
            w___pypy__ = self.getbuiltinmodule("__pypy__")
            from pypy.objspace.std.transparent import app_proxy, app_proxy_controller
        
            self.setattr(w___pypy__, self.wrap('tproxy'),
                          self.wrap(app_proxy))
            self.setattr(w___pypy__, self.wrap('get_tproxy_controller'),
                          self.wrap(app_proxy_controller))
示例#4
0
    def initialize(self):
        "NOT_RPYTHON: only for initializing the space."
        self._typecache = Cache()

        # Import all the object types and implementations
        self.model = StdTypeModel(self.config)

        from pypy.objspace.std.celldict import get_global_cache

        class StdObjSpaceFrame(pyframe.PyFrame):
            if self.config.objspace.std.withcelldict:

                def __init__(self, space, code, w_globals, closure):
                    pyframe.PyFrame.__init__(self, space, code, w_globals,
                                             closure)
                    self.cache_for_globals = get_global_cache(
                        space, code, w_globals)

                from pypy.objspace.std.celldict import LOAD_GLOBAL

            if self.config.objspace.std.optimized_int_add:
                if self.config.objspace.std.withsmallint:

                    def BINARY_ADD(f, oparg, *ignored):
                        from pypy.objspace.std.smallintobject import \
                             W_SmallIntObject, add__SmallInt_SmallInt
                        w_2 = f.popvalue()
                        w_1 = f.popvalue()
                        if type(w_1) is W_SmallIntObject and type(
                                w_2) is W_SmallIntObject:
                            try:
                                w_result = add__SmallInt_SmallInt(
                                    f.space, w_1, w_2)
                            except FailedToImplement:
                                w_result = f.space.add(w_1, w_2)
                        else:
                            w_result = f.space.add(w_1, w_2)
                        f.pushvalue(w_result)
                else:

                    def BINARY_ADD(f, oparg, *ignored):
                        from pypy.objspace.std.intobject import \
                             W_IntObject, add__Int_Int
                        w_2 = f.popvalue()
                        w_1 = f.popvalue()
                        if type(w_1) is W_IntObject and type(
                                w_2) is W_IntObject:
                            try:
                                w_result = add__Int_Int(f.space, w_1, w_2)
                            except FailedToImplement:
                                w_result = f.space.add(w_1, w_2)
                        else:
                            w_result = f.space.add(w_1, w_2)
                        f.pushvalue(w_result)

            if self.config.objspace.std.optimized_list_getitem:

                def BINARY_SUBSCR(f, *ignored):
                    w_2 = f.popvalue()
                    w_1 = f.popvalue()
                    if type(w_1) is W_ListObject and type(w_2) is W_IntObject:
                        try:
                            w_result = w_1.wrappeditems[w_2.intval]
                        except IndexError:
                            raise OperationError(
                                f.space.w_IndexError,
                                f.space.wrap("list index out of range"))
                    else:
                        w_result = f.space.getitem(w_1, w_2)
                    f.pushvalue(w_result)

            def LIST_APPEND(f, *ignored):
                w = f.popvalue()
                v = f.popvalue()
                if type(v) is W_ListObject:
                    v.append(w)
                else:
                    f.space.call_method(v, 'append', w)

            if self.config.objspace.opcodes.CALL_LIKELY_BUILTIN:

                def CALL_LIKELY_BUILTIN(f, oparg, *ignored):
                    from pypy.module.__builtin__ import OPTIMIZED_BUILTINS, Module
                    from pypy.objspace.std.dictmultiobject import W_DictMultiObject
                    w_globals = f.w_globals
                    num = oparg >> 8
                    assert isinstance(w_globals, W_DictMultiObject)
                    w_value = w_globals.implementation.get_builtin_indexed(num)
                    if w_value is None:
                        builtins = f.get_builtin()
                        assert isinstance(builtins, Module)
                        w_builtin_dict = builtins.w_dict
                        assert isinstance(w_builtin_dict, W_DictMultiObject)
                        w_value = w_builtin_dict.implementation.get_builtin_indexed(
                            num)

        ##                 if w_value is not None:
        ##                     print "CALL_LIKELY_BUILTIN fast"
                    if w_value is None:
                        varname = OPTIMIZED_BUILTINS[num]
                        message = "global name '%s' is not defined" % varname
                        raise OperationError(f.space.w_NameError,
                                             f.space.wrap(message))
                    nargs = oparg & 0xff
                    w_function = w_value
                    try:
                        w_result = f.call_likely_builtin(w_function, nargs)
                        # XXX XXX fix the problem of resume points!
                        #rstack.resume_point("CALL_FUNCTION", f, nargs, returns=w_result)
                    finally:
                        f.dropvalues(nargs)
                    f.pushvalue(w_result)

                def call_likely_builtin(f, w_function, nargs):
                    if isinstance(w_function, function.Function):
                        executioncontext = self.getexecutioncontext()
                        executioncontext.c_call_trace(f, w_function)
                        res = w_function.funccall_valuestack(nargs, f)
                        executioncontext.c_return_trace(f, w_function)
                        return res
                    args = f.make_arguments(nargs)
                    return f.space.call_args(w_function, args)

            if self.config.objspace.opcodes.CALL_METHOD:
                # def LOOKUP_METHOD(...):
                from pypy.objspace.std.callmethod import LOOKUP_METHOD
                # def CALL_METHOD(...):
                from pypy.objspace.std.callmethod import CALL_METHOD

            if self.config.objspace.std.optimized_comparison_op:

                def COMPARE_OP(f, testnum, *ignored):
                    import operator
                    w_2 = f.popvalue()
                    w_1 = f.popvalue()
                    w_result = None
                    if (type(w_2) is W_IntObject and type(w_1) is W_IntObject
                            and testnum < len(compare_table)):
                        for i, attr in unrolling_compare_ops:
                            if i == testnum:
                                op = getattr(operator, attr)
                                w_result = f.space.newbool(
                                    op(w_1.intval, w_2.intval))
                                break
                    else:
                        for i, attr in unrolling_compare_dispatch_table:
                            if i == testnum:
                                w_result = getattr(f, attr)(w_1, w_2)
                                break
                        else:
                            raise BytecodeCorruption, "bad COMPARE_OP oparg"
                    f.pushvalue(w_result)

            if self.config.objspace.std.logspaceoptypes:
                _space_op_types = []
                for name, func in pyframe.PyFrame.__dict__.iteritems():
                    if hasattr(func, 'binop'):
                        operationname = func.binop

                        def make_opimpl(operationname):
                            def opimpl(f, *ignored):
                                operation = getattr(f.space, operationname)
                                w_2 = f.popvalue()
                                w_1 = f.popvalue()
                                if we_are_translated():
                                    s = operationname + ' ' + str(
                                        w_1) + ' ' + str(w_2)
                                else:
                                    s = operationname + ' ' + w_1.__class__.__name__ + ' ' + w_2.__class__.__name__
                                f._space_op_types.append(s)
                                w_result = operation(w_1, w_2)
                                f.pushvalue(w_result)

                            return func_with_new_name(
                                opimpl, "opcode_impl_for_%s" % operationname)

                        locals()[name] = make_opimpl(operationname)
                    elif hasattr(func, 'unaryop'):
                        operationname = func.unaryop

                        def make_opimpl(operationname):
                            def opimpl(f, *ignored):
                                operation = getattr(f.space, operationname)
                                w_1 = f.popvalue()
                                if we_are_translated():
                                    s = operationname + ' ' + str(w_1)
                                else:
                                    s = operationname + ' ' + w_1.__class__.__name__
                                f._space_op_types.append(s)
                                w_result = operation(w_1)
                                f.pushvalue(w_result)

                            return func_with_new_name(
                                opimpl, "opcode_impl_for_%s" % operationname)

                        locals()[name] = make_opimpl(operationname)

        self.FrameClass = StdObjSpaceFrame

        # XXX store the dict class on the space to access it in various places
        from pypy.objspace.std import dictmultiobject
        self.DictObjectCls = dictmultiobject.W_DictMultiObject
        self.emptydictimpl = dictmultiobject.EmptyDictImplementation(self)
        if self.config.objspace.std.withbucketdict:
            from pypy.objspace.std import dictbucket
            self.DefaultDictImpl = dictbucket.BucketDictImplementation
        else:
            self.DefaultDictImpl = dictmultiobject.RDictImplementation
        assert self.DictObjectCls in self.model.typeorder

        from pypy.objspace.std import tupleobject
        self.TupleObjectCls = tupleobject.W_TupleObject

        if not self.config.objspace.std.withrope:
            from pypy.objspace.std import stringobject
            self.StringObjectCls = stringobject.W_StringObject
        else:
            from pypy.objspace.std import ropeobject
            self.StringObjectCls = ropeobject.W_RopeObject
        assert self.StringObjectCls in self.model.typeorder

        # install all the MultiMethods into the space instance
        for name, mm in self.MM.__dict__.items():
            if not isinstance(mm, StdObjSpaceMultiMethod):
                continue
            if not hasattr(self, name):
                if name.endswith(
                        '_w'
                ):  # int_w, str_w...: these do not return a wrapped object
                    func = mm.install_not_sliced(self.model.typeorder,
                                                 baked_perform_call=True)
                else:
                    exprargs, expr, miniglobals, fallback = (
                        mm.install_not_sliced(self.model.typeorder,
                                              baked_perform_call=False))

                    func = stdtypedef.make_perform_trampoline(
                        '__mm_' + name, exprargs, expr, miniglobals, mm)

                    # e.g. add(space, w_x, w_y)
                def make_boundmethod(func=func):
                    def boundmethod(*args):
                        return func(self, *args)

                    return func_with_new_name(boundmethod,
                                              'boundmethod_' + name)

                boundmethod = make_boundmethod()
                setattr(self, name, boundmethod)  # store into 'space' instance
            elif self.config.objspace.std.builtinshortcut:
                from pypy.objspace.std import builtinshortcut
                if name.startswith('inplace_'):
                    fallback_name = name[len('inplace_'):]
                    if fallback_name in ('or', 'and'):
                        fallback_name += '_'
                    fallback_mm = self.MM.__dict__[fallback_name]
                else:
                    fallback_mm = None
                builtinshortcut.install(self, mm, fallback_mm)

        if self.config.objspace.std.builtinshortcut:
            from pypy.objspace.std import builtinshortcut
            builtinshortcut.install_is_true(self, self.MM.nonzero, self.MM.len)

        # set up the method cache
        if self.config.objspace.std.withmethodcache:
            SIZE = 1 << self.config.objspace.std.methodcachesizeexp
            self.method_cache_versions = [None] * SIZE
            self.method_cache_names = [None] * SIZE
            self.method_cache_lookup_where = [(None, None)] * SIZE
            if self.config.objspace.std.withmethodcachecounter:
                self.method_cache_hits = {}
                self.method_cache_misses = {}

        # hack to avoid imports in the time-critical functions below
        for cls in self.model.typeorder:
            globals()[cls.__name__] = cls
        for cls in self.model.imported_but_not_registered:
            globals()[cls.__name__] = cls

        # singletons
        self.w_None = W_NoneObject.w_None
        self.w_False = W_BoolObject.w_False
        self.w_True = W_BoolObject.w_True
        from pypy.interpreter.special import NotImplemented, Ellipsis
        self.w_NotImplemented = self.wrap(NotImplemented(self))
        self.w_Ellipsis = self.wrap(Ellipsis(self))

        # types
        for typedef in self.model.pythontypes:
            w_type = self.gettypeobject(typedef)
            setattr(self, 'w_' + typedef.name, w_type)

        # exceptions & builtins
        w_mod = self.setup_exceptions()
        self.make_builtins()
        self.sys.setmodule(w_mod)

        # the type of old-style classes
        self.w_classobj = self.builtin.get('__metaclass__')

        # fix up a problem where multimethods apparently don't
        # like to define this at interp-level
        # HACK HACK HACK
        from pypy.objspace.std.typeobject import _HEAPTYPE
        old_flags = self.w_dict.__flags__
        self.w_dict.__flags__ |= _HEAPTYPE
        self.appexec([self.w_dict], """
            (dict): 
                def fromkeys(cls, seq, value=None):
                    r = cls()
                    for s in seq:
                        r[s] = value
                    return r
                dict.fromkeys = classmethod(fromkeys)
        """)
        self.w_dict.__flags__ = old_flags

        # final setup
        self.setup_builtin_modules()
        # Adding transparent proxy call
        if self.config.objspace.std.withtproxy:
            w___pypy__ = self.getbuiltinmodule("__pypy__")
            from pypy.objspace.std.transparent import app_proxy, app_proxy_controller

            self.setattr(w___pypy__, self.wrap('tproxy'), self.wrap(app_proxy))
            self.setattr(w___pypy__, self.wrap('get_tproxy_controller'),
                         self.wrap(app_proxy_controller))
示例#5
0
def Space(*args, **kwds):
    try:
        # for now, always make up a wrapped StdObjSpace
        from pypy.objspace import std
        space = std.Space(*args, **kwds)

        # multimethods hack
        space.model.typeorder[W_Var] = [(W_Var, None),
                                        (W_Root, None)] # None means no conversion
        space.model.typeorder[W_Future] = [(W_Future, None), (W_Var, None), (W_Root, None)]
        space.model.typeorder[W_CVar] = [(W_CVar, None), (W_Var, None), (W_Root, None)]

        for name in all_mms.keys():
            exprargs, expr, miniglobals, fallback = (
                all_mms[name].install_not_sliced(space.model.typeorder, baked_perform_call=False))
            func = stdtypedef.make_perform_trampoline('__mm_' + name,
                                                      exprargs, expr, miniglobals,
                                                      all_mms[name])
            # e.g. add(space, w_x, w_y)
            def make_boundmethod(func=func):
                def boundmethod(*args):
                    return func(space, *args)
                return func_with_new_name(boundmethod, 'boundmethod_'+name)
            boundmethod = make_boundmethod()
            setattr(space, name, boundmethod)  # store into 'space' instance
        # /multimethods hack

        #-- BUILTINS
        #-- variable -------
        space.setitem(space.builtin.w_dict, space.wrap('newvar'),
                      space.wrap(app_newvar))
        space.setitem(space.builtin.w_dict, space.wrap('domain'),
                      space.wrap(app_domain))
        space.setitem(space.builtin.w_dict, space.wrap('domain_of'),
                      space.wrap(app_domain_of))
        space.setitem(space.builtin.w_dict, space.wrap('name_of'),
                      space.wrap(app_name_of))
        space.setitem(space.builtin.w_dict, space.wrap('is_free'),
                      space.wrap(app_is_free))
        space.setitem(space.builtin.w_dict, space.wrap('is_bound'),
                      space.wrap(app_is_bound))
        space.setitem(space.builtin.w_dict, space.wrap('alias_of'),
                      space.wrap(app_alias_of))
        space.setitem(space.builtin.w_dict, space.wrap('is_aliased'),
                      space.wrap(app_is_aliased))
        space.setitem(space.builtin.w_dict, space.wrap('bind'),
                     space.wrap(app_bind))
        space.setitem(space.builtin.w_dict, space.wrap('entail'),
                     space.wrap(app_entail))
        space.setitem(space.builtin.w_dict, space.wrap('unify'),
                     space.wrap(app_unify))
        #-- variables & threading --
        space.setitem(space.builtin.w_dict, space.wrap('wait'),
                     space.wrap(app_wait))
        space.setitem(space.builtin.w_dict, space.wrap('wait_needed'),
                      space.wrap(app_wait_needed))
        #-- misc -----
        space.setitem(space.builtin.w_dict, space.wrap('interp_id'),
                      space.wrap(app_interp_id))

        # make sure that _stackless is imported
        w_modules = space.getbuiltinmodule('_stackless')
        # cleanup func called from space.finish()
        def exitfunc():
            pass

        app_exitfunc = gateway.interp2app(exitfunc, unwrap_spec=[])
        space.setitem(space.sys.w_dict, space.wrap("exitfunc"), space.wrap(app_exitfunc))

        # capture one non-blocking op
        space.is_nb_ = space.is_

        # do the magic
        patch_space_in_place(space, 'logic', proxymaker)
        # instantiate singleton scheduler
        sched.main_thread = AppCoroutine.w_getcurrent(space)
        tg = W_ThreadGroupScheduler(space)
        sched.uler = TopLevelScheduler(space, tg)
        tg._init_head(sched.main_thread)

    except:
        import traceback
        traceback.print_exc()
        raise
    
    return space
示例#6
0
    def initialize(self):
        "NOT_RPYTHON: only for initializing the space."
        self._typecache = Cache()

        # Import all the object types and implementations
        self.model = StdTypeModel(self.config)

        from pypy.objspace.std.celldict import get_global_cache

        class StdObjSpaceFrame(pyframe.PyFrame):
            if self.config.objspace.std.withcelldict:
                def __init__(self, space, code, w_globals, closure):
                    pyframe.PyFrame.__init__(self, space, code, w_globals, closure)
                    self.cache_for_globals = get_global_cache(space, code, w_globals)

                from pypy.objspace.std.celldict import LOAD_GLOBAL

            if self.config.objspace.std.optimized_int_add:
                if self.config.objspace.std.withsmallint:
                    def BINARY_ADD(f, oparg, *ignored):
                        from pypy.objspace.std.smallintobject import \
                             W_SmallIntObject, add__SmallInt_SmallInt
                        w_2 = f.popvalue()
                        w_1 = f.popvalue()
                        if type(w_1) is W_SmallIntObject and type(w_2) is W_SmallIntObject:
                            try:
                                w_result = add__SmallInt_SmallInt(f.space, w_1, w_2)
                            except FailedToImplement:
                                w_result = f.space.add(w_1, w_2)
                        else:
                            w_result = f.space.add(w_1, w_2)
                        f.pushvalue(w_result)
                else:
                    def BINARY_ADD(f, oparg, *ignored):
                        from pypy.objspace.std.intobject import \
                             W_IntObject, add__Int_Int
                        w_2 = f.popvalue()
                        w_1 = f.popvalue()
                        if type(w_1) is W_IntObject and type(w_2) is W_IntObject:
                            try:
                                w_result = add__Int_Int(f.space, w_1, w_2)
                            except FailedToImplement:
                                w_result = f.space.add(w_1, w_2)
                        else:
                            w_result = f.space.add(w_1, w_2)
                        f.pushvalue(w_result)

            if self.config.objspace.std.optimized_list_getitem:
                def BINARY_SUBSCR(f, *ignored):
                    w_2 = f.popvalue()
                    w_1 = f.popvalue()
                    if type(w_1) is W_ListObject and type(w_2) is W_IntObject:
                        try:
                            w_result = w_1.wrappeditems[w_2.intval]
                        except IndexError:
                            raise OperationError(f.space.w_IndexError,
                                f.space.wrap("list index out of range"))
                    else:
                        w_result = f.space.getitem(w_1, w_2)
                    f.pushvalue(w_result)

            def LIST_APPEND(f, *ignored):
                w = f.popvalue()
                v = f.popvalue()
                if type(v) is W_ListObject:
                    v.append(w)
                else:
                    f.space.call_method(v, 'append', w)

            if self.config.objspace.opcodes.CALL_LIKELY_BUILTIN:
                def CALL_LIKELY_BUILTIN(f, oparg, *ignored):
                    from pypy.module.__builtin__ import OPTIMIZED_BUILTINS, Module
                    from pypy.objspace.std.dictmultiobject import W_DictMultiObject
                    w_globals = f.w_globals
                    num = oparg >> 8
                    assert isinstance(w_globals, W_DictMultiObject)
                    w_value = w_globals.implementation.get_builtin_indexed(num)
                    if w_value is None:
                        builtins = f.get_builtin()
                        assert isinstance(builtins, Module)
                        w_builtin_dict = builtins.w_dict
                        assert isinstance(w_builtin_dict, W_DictMultiObject)
                        w_value = w_builtin_dict.implementation.get_builtin_indexed(num)
        ##                 if w_value is not None:
        ##                     print "CALL_LIKELY_BUILTIN fast"
                    if w_value is None:
                        varname = OPTIMIZED_BUILTINS[num]
                        message = "global name '%s' is not defined" % varname
                        raise OperationError(f.space.w_NameError,
                                             f.space.wrap(message))
                    nargs = oparg & 0xff
                    w_function = w_value
                    try:
                        w_result = f.call_likely_builtin(w_function, nargs)
                        # XXX XXX fix the problem of resume points!
                        #rstack.resume_point("CALL_FUNCTION", f, nargs, returns=w_result)
                    finally:
                        f.dropvalues(nargs)
                    f.pushvalue(w_result)

                def call_likely_builtin(f, w_function, nargs):
                    if isinstance(w_function, function.Function):
                        executioncontext = self.getexecutioncontext()
                        executioncontext.c_call_trace(f, w_function)
                        res = w_function.funccall_valuestack(nargs, f)
                        executioncontext.c_return_trace(f, w_function)
                        return res
                    args = f.make_arguments(nargs)
                    try:
                        return f.space.call_args(w_function, args)
                    finally:
                        if isinstance(args, argument.ArgumentsFromValuestack):
                            args.frame = None

            if self.config.objspace.opcodes.CALL_METHOD:
                # def LOOKUP_METHOD(...):
                from pypy.objspace.std.callmethod import LOOKUP_METHOD
                # def CALL_METHOD(...):
                from pypy.objspace.std.callmethod import CALL_METHOD

            if self.config.objspace.std.optimized_comparison_op:
                def COMPARE_OP(f, testnum, *ignored):
                    import operator
                    w_2 = f.popvalue()
                    w_1 = f.popvalue()
                    w_result = None
                    if (type(w_2) is W_IntObject and type(w_1) is W_IntObject
                        and testnum < len(compare_table)):
                        for i, attr in unrolling_compare_ops:
                            if i == testnum:
                                op = getattr(operator, attr)
                                w_result = f.space.newbool(op(w_1.intval,
                                                              w_2.intval))
                                break
                    else:
                        for i, attr in unrolling_compare_dispatch_table:
                            if i == testnum:
                                w_result = getattr(f, attr)(w_1, w_2)
                                break
                        else:
                            raise BytecodeCorruption, "bad COMPARE_OP oparg"
                    f.pushvalue(w_result)

            if self.config.objspace.std.logspaceoptypes:
                _space_op_types = []
                for name, func in pyframe.PyFrame.__dict__.iteritems():
                    if hasattr(func, 'binop'):
                        operationname = func.binop
                        def make_opimpl(operationname):
                            def opimpl(f, *ignored):
                                operation = getattr(f.space, operationname)
                                w_2 = f.popvalue()
                                w_1 = f.popvalue()
                                if we_are_translated():
                                    s = operationname + ' ' + str(w_1) + ' ' + str(w_2)
                                else:
                                    s = operationname + ' ' + w_1.__class__.__name__ + ' ' + w_2.__class__.__name__
                                f._space_op_types.append(s)
                                w_result = operation(w_1, w_2)
                                f.pushvalue(w_result)
                            return func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)
                        locals()[name] = make_opimpl(operationname)
                    elif hasattr(func, 'unaryop'):
                        operationname = func.unaryop
                        def make_opimpl(operationname):
                            def opimpl(f, *ignored):
                                operation = getattr(f.space, operationname)
                                w_1 = f.popvalue()
                                if we_are_translated():
                                    s = operationname + ' ' + str(w_1)
                                else:
                                    s = operationname + ' ' + w_1.__class__.__name__
                                f._space_op_types.append(s)
                                w_result = operation(w_1)
                                f.pushvalue(w_result)
                            return func_with_new_name(opimpl, "opcode_impl_for_%s" % operationname)
                        locals()[name] = make_opimpl(operationname)                    

        self.FrameClass = StdObjSpaceFrame

        # XXX store the dict class on the space to access it in various places
        if self.config.objspace.std.withmultidict:
            from pypy.objspace.std import dictmultiobject
            self.DictObjectCls = dictmultiobject.W_DictMultiObject
            self.emptydictimpl = dictmultiobject.EmptyDictImplementation(self)
            if self.config.objspace.std.withbucketdict:
                from pypy.objspace.std import dictbucket
                self.DefaultDictImpl = dictbucket.BucketDictImplementation
            else:
                self.DefaultDictImpl = dictmultiobject.RDictImplementation
        else:
            from pypy.objspace.std import dictobject
            self.DictObjectCls = dictobject.W_DictObject
        assert self.DictObjectCls in self.model.typeorder

        from pypy.objspace.std import tupleobject
        self.TupleObjectCls = tupleobject.W_TupleObject

        if not self.config.objspace.std.withrope:
            from pypy.objspace.std import stringobject
            self.StringObjectCls = stringobject.W_StringObject
        else:
            from pypy.objspace.std import ropeobject
            self.StringObjectCls = ropeobject.W_RopeObject
        assert self.StringObjectCls in self.model.typeorder

        # install all the MultiMethods into the space instance
        for name, mm in self.MM.__dict__.items():
            if not isinstance(mm, StdObjSpaceMultiMethod):
                continue
            if not hasattr(self, name):
                if name.endswith('_w'): # int_w, str_w...: these do not return a wrapped object
                    func = mm.install_not_sliced(self.model.typeorder, baked_perform_call=True)
                else:               
                    exprargs, expr, miniglobals, fallback = (
                        mm.install_not_sliced(self.model.typeorder, baked_perform_call=False))

                    func = stdtypedef.make_perform_trampoline('__mm_'+name,
                                                              exprargs, expr, miniglobals,
                                                              mm)
                
                                                  # e.g. add(space, w_x, w_y)
                def make_boundmethod(func=func):
                    def boundmethod(*args):
                        return func(self, *args)
                    return func_with_new_name(boundmethod, 'boundmethod_'+name)
                boundmethod = make_boundmethod()
                setattr(self, name, boundmethod)  # store into 'space' instance
            elif self.config.objspace.std.builtinshortcut:
                from pypy.objspace.std import builtinshortcut
                if name.startswith('inplace_'):
                    fallback_name = name[len('inplace_'):]
                    if fallback_name in ('or', 'and'):
                        fallback_name += '_'
                    fallback_mm = self.MM.__dict__[fallback_name]
                else:
                    fallback_mm = None
                builtinshortcut.install(self, mm, fallback_mm)

        if self.config.objspace.std.builtinshortcut:
            from pypy.objspace.std import builtinshortcut
            builtinshortcut.install_is_true(self, self.MM.nonzero, self.MM.len)

        # set up the method cache
        if self.config.objspace.std.withmethodcache:
            SIZE = 1 << self.config.objspace.std.methodcachesizeexp
            self.method_cache_versions = [None] * SIZE
            self.method_cache_names = [None] * SIZE
            self.method_cache_lookup_where = [(None, None)] * SIZE
            if self.config.objspace.std.withmethodcachecounter:
                self.method_cache_hits = {}
                self.method_cache_misses = {}

        # hack to avoid imports in the time-critical functions below
        for cls in self.model.typeorder:
            globals()[cls.__name__] = cls
        for cls in self.model.imported_but_not_registered:
            globals()[cls.__name__] = cls

        # singletons
        self.w_None  = W_NoneObject.w_None
        self.w_False = W_BoolObject.w_False
        self.w_True  = W_BoolObject.w_True
        from pypy.interpreter.special import NotImplemented, Ellipsis
        self.w_NotImplemented = self.wrap(NotImplemented(self))  
        self.w_Ellipsis = self.wrap(Ellipsis(self))  

        # types
        for typedef in self.model.pythontypes:
            w_type = self.gettypeobject(typedef)
            setattr(self, 'w_' + typedef.name, w_type)

        # exceptions & builtins
        w_mod = self.setup_exceptions()
        self.make_builtins()
        self.sys.setmodule(w_mod)

        # the type of old-style classes
        self.w_classobj = self.builtin.get('__metaclass__')

        # fix up a problem where multimethods apparently don't 
        # like to define this at interp-level 
        # HACK HACK HACK
        from pypy.objspace.std.typeobject import _HEAPTYPE
        old_flags = self.w_dict.__flags__
        self.w_dict.__flags__ |= _HEAPTYPE
        self.appexec([self.w_dict], """
            (dict): 
                def fromkeys(cls, seq, value=None):
                    r = cls()
                    for s in seq:
                        r[s] = value
                    return r
                dict.fromkeys = classmethod(fromkeys)
        """)
        self.w_dict.__flags__ = old_flags

        # final setup
        self.setup_builtin_modules()
        # Adding transparent proxy call
        if self.config.objspace.std.withtproxy:
            w___pypy__ = self.getbuiltinmodule("__pypy__")
            from pypy.objspace.std.transparent import app_proxy, app_proxy_controller
        
            self.setattr(w___pypy__, self.wrap('tproxy'),
                          self.wrap(app_proxy))
            self.setattr(w___pypy__, self.wrap('get_tproxy_controller'),
                          self.wrap(app_proxy_controller))