[pypy-commit] pypy less-stringly-ops: Replace FlowObjSpace.wrap() with a const() function defined in flowspace.model

rlamy noreply at buildbot.pypy.org
Mon Aug 19 23:14:53 CEST 2013


Author: Ronan Lamy <ronan.lamy at gmail.com>
Branch: less-stringly-ops
Changeset: r66225:f9a887280c0a
Date: 2013-08-09 04:23 +0100
http://bitbucket.org/pypy/pypy/changeset/f9a887280c0a/

Log:	Replace FlowObjSpace.wrap() with a const() function defined in
	flowspace.model

diff --git a/rpython/flowspace/flowcontext.py b/rpython/flowspace/flowcontext.py
--- a/rpython/flowspace/flowcontext.py
+++ b/rpython/flowspace/flowcontext.py
@@ -9,7 +9,7 @@
 from rpython.tool.stdlib_opcode import host_bytecode_spec
 from rpython.flowspace.argument import CallSpec
 from rpython.flowspace.model import (Constant, Variable, Block, Link,
-    c_last_exception, SpaceOperation)
+    c_last_exception, SpaceOperation, const)
 from rpython.flowspace.framestate import (FrameState, recursively_unflatten,
     recursively_flatten)
 from rpython.flowspace.specialcase import (rpython_print_item,
@@ -350,7 +350,7 @@
         if closure is None:
             self.closure = []
         else:
-            self.closure = [self.space.wrap(c.cell_contents) for c in closure]
+            self.closure = [const(c.cell_contents) for c in closure]
         assert len(self.closure) == len(self.pycode.co_freevars)
 
     def init_locals_stack(self, code):
@@ -420,13 +420,13 @@
         else:
             data.append(self.last_exception.w_type)
             data.append(self.last_exception.w_value)
-        recursively_flatten(self.space, data)
+        recursively_flatten(data)
         return FrameState(data, self.blockstack[:], self.last_instr)
 
     def setstate(self, state):
         """ Reset the frame to the given state. """
         data = state.mergeable[:]
-        recursively_unflatten(self.space, data)
+        recursively_unflatten(data)
         self.restore_locals_stack(data[:-2])  # Nones == undefined locals
         if data[-2] == Constant(None):
             assert data[-1] == Constant(None)
@@ -578,7 +578,7 @@
         return self.pycode.co_varnames[index]
 
     def getconstant_w(self, index):
-        return self.space.wrap(self.pycode.consts[index])
+        return const(self.pycode.consts[index])
 
     def getname_u(self, index):
         return self.pycode.names[index]
@@ -811,7 +811,7 @@
         # directly call manager.__enter__(), don't use special lookup functions
         # which don't make sense on the RPython type system.
         w_manager = self.peekvalue()
-        w_exit = self.space.getattr(w_manager, self.space.wrap("__exit__"))
+        w_exit = self.space.getattr(w_manager, const("__exit__"))
         self.settopvalue(w_exit)
         w_result = self.space.call_method(w_manager, "__enter__")
         block = WithBlock(self, next_instr + offsettoend)
@@ -1174,11 +1174,11 @@
     def nomoreblocks(self):
         raise Return(self.w_returnvalue)
 
-    def state_unpack_variables(self, space):
+    def state_unpack_variables(self):
         return [self.w_returnvalue]
 
     @staticmethod
-    def state_pack_variables(space, w_returnvalue):
+    def state_pack_variables(w_returnvalue):
         return SReturnValue(w_returnvalue)
 
 class SApplicationException(SuspendedUnroller):
@@ -1191,21 +1191,21 @@
     def nomoreblocks(self):
         raise self.operr
 
-    def state_unpack_variables(self, space):
+    def state_unpack_variables(self):
         return [self.operr.w_type, self.operr.w_value]
 
     @staticmethod
-    def state_pack_variables(space, w_type, w_value):
+    def state_pack_variables(w_type, w_value):
         return SApplicationException(FSException(w_type, w_value))
 
 class SBreakLoop(SuspendedUnroller):
     """Signals a 'break' statement."""
 
-    def state_unpack_variables(self, space):
+    def state_unpack_variables(self):
         return []
 
     @staticmethod
-    def state_pack_variables(space):
+    def state_pack_variables():
         return SBreakLoop.singleton
 
 SBreakLoop.singleton = SBreakLoop()
@@ -1217,12 +1217,12 @@
     def __init__(self, jump_to):
         self.jump_to = jump_to
 
-    def state_unpack_variables(self, space):
-        return [space.wrap(self.jump_to)]
+    def state_unpack_variables(self):
+        return [const(self.jump_to)]
 
     @staticmethod
-    def state_pack_variables(space, w_jump_to):
-        return SContinueLoop(space.int_w(w_jump_to))
+    def state_pack_variables(w_jump_to):
+        return SContinueLoop(w_jump_to.value)
 
 
 class FrameBlock(object):
diff --git a/rpython/flowspace/framestate.py b/rpython/flowspace/framestate.py
--- a/rpython/flowspace/framestate.py
+++ b/rpython/flowspace/framestate.py
@@ -106,7 +106,7 @@
 UNPICKLE_TAGS = {}
 
 
-def recursively_flatten(space, lst):
+def recursively_flatten(lst):
     from rpython.flowspace.flowcontext import SuspendedUnroller
     i = 0
     while i < len(lst):
@@ -114,7 +114,7 @@
         if not isinstance(unroller, SuspendedUnroller):
             i += 1
         else:
-            vars = unroller.state_unpack_variables(space)
+            vars = unroller.state_unpack_variables()
             key = unroller.__class__, len(vars)
             try:
                 tag = PICKLE_TAGS[key]
@@ -124,12 +124,12 @@
             lst[i:i + 1] = [tag] + vars
 
 
-def recursively_unflatten(space, lst):
+def recursively_unflatten(lst):
     for i in xrange(len(lst) - 1, -1, -1):
         item = lst[i]
         if item in UNPICKLE_TAGS:
             unrollerclass, argcount = UNPICKLE_TAGS[item]
             arguments = lst[i + 1:i + 1 + argcount]
             del lst[i + 1:i + 1 + argcount]
-            unroller = unrollerclass.state_pack_variables(space, *arguments)
+            unroller = unrollerclass.state_pack_variables(*arguments)
             lst[i] = unroller
diff --git a/rpython/flowspace/model.py b/rpython/flowspace/model.py
--- a/rpython/flowspace/model.py
+++ b/rpython/flowspace/model.py
@@ -355,6 +355,21 @@
     during its construction"""
 
 
+# method-wrappers have not enough introspection in CPython
+if hasattr(complex.real.__get__, 'im_self'):
+    type_with_bad_introspection = None     # on top of PyPy
+else:
+    type_with_bad_introspection = type(complex.real.__get__)
+
+def const(obj):
+    if isinstance(obj, (Variable, Constant)):
+        raise TypeError("already wrapped: " + repr(obj))
+    # method-wrapper have ill-defined comparison and introspection
+    # to appear in a flow graph
+    if type(obj) is type_with_bad_introspection:
+        raise WrapException
+    return Constant(obj)
+
 class SpaceOperation(object):
     __slots__ = "opname args result offset".split()
 
diff --git a/rpython/flowspace/objspace.py b/rpython/flowspace/objspace.py
--- a/rpython/flowspace/objspace.py
+++ b/rpython/flowspace/objspace.py
@@ -9,7 +9,7 @@
 
 from rpython.flowspace.argument import CallSpec
 from rpython.flowspace.model import (Constant, Variable, WrapException,
-    UnwrapException, checkgraph)
+    UnwrapException, checkgraph, const)
 from rpython.flowspace.bytecode import HostCode
 from rpython.flowspace import operation
 from rpython.flowspace.flowcontext import (FlowSpaceFrame, fixeggblocks,
@@ -23,12 +23,6 @@
 from rpython.rlib.rarithmetic import is_valid_int
 
 
-# method-wrappers have not enough introspection in CPython
-if hasattr(complex.real.__get__, 'im_self'):
-    type_with_bad_introspection = None     # on top of PyPy
-else:
-    type_with_bad_introspection = type(complex.real.__get__)
-
 # the following gives us easy access to declare more for applications:
 NOT_REALLY_CONST = {
     Constant(sys): {
@@ -136,18 +130,9 @@
         fn = types.FunctionType(code, globals, code.co_name, defaults)
         return Constant(fn)
 
-    def wrap(self, obj):
-        if isinstance(obj, (Variable, Constant)):
-            raise TypeError("already wrapped: " + repr(obj))
-        # method-wrapper have ill-defined comparison and introspection
-        # to appear in a flow graph
-        if type(obj) is type_with_bad_introspection:
-            raise WrapException
-        return Constant(obj)
-
     def exc_wrap(self, exc):
-        w_value = self.wrap(exc)
-        w_type = self.wrap(type(exc))
+        w_value = const(exc)
+        w_type = const(type(exc))
         return FSException(w_type, w_value)
 
     def int_w(self, w_obj):
@@ -191,7 +176,7 @@
             return self.exception_issubclass_w(w_exc_type, w_check_class)
         # special case for StackOverflow (see rlib/rstackovf.py)
         if check_class == rstackovf.StackOverflow:
-            w_real_class = self.wrap(rstackovf._StackOverflow)
+            w_real_class = const(rstackovf._StackOverflow)
             return self.exception_issubclass_w(w_exc_type, w_real_class)
         # checking a tuple of classes
         for w_klass in self.unpackiterable(w_check_class):
@@ -230,7 +215,7 @@
     def unpackiterable(self, w_iterable):
         if isinstance(w_iterable, Constant):
             l = w_iterable.value
-            return [self.wrap(x) for x in l]
+            return [const(x) for x in l]
         else:
             raise UnwrapException("cannot unpack a Variable iterable ")
 
@@ -239,19 +224,19 @@
             l = list(self.unwrap(w_iterable))
             if len(l) != expected_length:
                 raise ValueError
-            return [self.wrap(x) for x in l]
+            return [const(x) for x in l]
         else:
             w_len = self.len(w_iterable)
-            w_correct = self.eq(w_len, self.wrap(expected_length))
+            w_correct = self.eq(w_len, const(expected_length))
             if not self.is_true(w_correct):
                 e = self.exc_from_raise(self.w_ValueError, self.w_None)
                 raise e
-            return [self.frame.do_operation('getitem', w_iterable, self.wrap(i))
+            return [self.frame.do_operation('getitem', w_iterable, const(i))
                         for i in range(expected_length)]
 
     # ____________________________________________________________
     def not_(self, w_obj):
-        return self.wrap(not self.is_true(w_obj))
+        return const(not self.is_true(w_obj))
 
     def is_true(self, w_obj):
         if w_obj.foldable():
@@ -263,7 +248,7 @@
         if isinstance(w_iterable, Constant):
             iterable = w_iterable.value
             if isinstance(iterable, unrolling_iterable):
-                return self.wrap(iterable.get_unroller())
+                return const(iterable.get_unroller())
         w_iter = self.frame.do_operation("iter", w_iterable)
         return w_iter
 
@@ -278,7 +263,7 @@
                     raise self.exc_wrap(StopIteration())
                 else:
                     frame.replace_in_stack(it, next_unroller)
-                    return self.wrap(v)
+                    return const(v)
         w_item = frame.do_operation("next", w_iter)
         frame.handle_implicit_exceptions([StopIteration, RuntimeError])
         return w_item
@@ -302,7 +287,7 @@
                     obj, name, etype, e)
                 raise FlowingError(self.frame, msg)
             try:
-                return self.wrap(result)
+                return const(result)
             except WrapException:
                 pass
         return self.frame.do_operation_with_implicit_exceptions('getattr',
@@ -316,7 +301,7 @@
             mod = __import__(name, glob, loc, frm, level)
         except ImportError as e:
             raise self.exc_wrap(e)
-        return self.wrap(mod)
+        return const(mod)
 
     def import_from(self, w_module, w_name):
         assert isinstance(w_module, Constant)
@@ -328,13 +313,13 @@
                 return self.frame.do_operation_with_implicit_exceptions('getattr',
                                                                 w_module, w_name)
         try:
-            return self.wrap(getattr(w_module.value, w_name.value))
+            return const(getattr(w_module.value, w_name.value))
         except AttributeError:
             raise self.exc_wrap(ImportError(
                 "cannot import name '%s'" % w_name.value))
 
     def call_method(self, w_obj, methname, *arg_w):
-        w_meth = self.getattr(w_obj, self.wrap(methname))
+        w_meth = self.getattr(w_obj, const(methname))
         return self.call_function(w_meth, *arg_w)
 
     def call_function(self, w_func, *args_w):
@@ -343,7 +328,7 @@
 
     def appcall(self, func, *args_w):
         """Call an app-level RPython function directly"""
-        w_func = self.wrap(func)
+        w_func = const(func)
         return self.frame.do_operation('simple_call', w_func, *args_w)
 
     def call_args(self, w_callable, args):
@@ -351,7 +336,7 @@
             fn = w_callable.value
             if hasattr(fn, "_flowspace_rewrite_directly_as_"):
                 fn = fn._flowspace_rewrite_directly_as_
-                w_callable = self.wrap(fn)
+                w_callable = const(fn)
             try:
                 sc = self.specialcases[fn]   # TypeError if 'fn' not hashable
             except (KeyError, TypeError):
@@ -398,8 +383,8 @@
                 value = getattr(self.unwrap(self.builtin), varname)
             except AttributeError:
                 message = "global name '%s' is not defined" % varname
-                raise FlowingError(self.frame, self.wrap(message))
-        return self.wrap(value)
+                raise FlowingError(self.frame, const(message))
+        return const(value)
 
 def make_impure_op(oper):
     def generic_operator(self, *args_w):
diff --git a/rpython/flowspace/operation.py b/rpython/flowspace/operation.py
--- a/rpython/flowspace/operation.py
+++ b/rpython/flowspace/operation.py
@@ -8,7 +8,7 @@
 import operator
 from rpython.tool.sourcetools import compile2
 from rpython.rlib.rarithmetic import ovfcheck
-from rpython.flowspace.model import Constant
+from rpython.flowspace.model import Constant, const
 
 class _OpHolder(object): pass
 op = _OpHolder()


More information about the pypy-commit mailing list