[pypy-svn] r5533 - in pypy/trunk/src/pypy: interpreter objspace objspace/test tool

rxe at codespeak.net rxe at codespeak.net
Mon Jul 12 14:05:50 CEST 2004


Author: rxe
Date: Mon Jul 12 14:05:49 2004
New Revision: 5533

Modified:
   pypy/trunk/src/pypy/interpreter/baseobjspace.py
   pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py
   pypy/trunk/src/pypy/objspace/trace.py
   pypy/trunk/src/pypy/tool/traceinteractive.py
   pypy/trunk/src/pypy/tool/traceop.py
Log:
Tracespace hopefully now catches all operations.
Generally tided up tracespace code and better print function.
Had to turn base ObjectSpace into a new style class (sorry - maybe there is a better way)



Modified: pypy/trunk/src/pypy/interpreter/baseobjspace.py
==============================================================================
--- pypy/trunk/src/pypy/interpreter/baseobjspace.py	(original)
+++ pypy/trunk/src/pypy/interpreter/baseobjspace.py	Mon Jul 12 14:05:49 2004
@@ -24,7 +24,7 @@
 class Wrappable(BaseWrappable, object):
     """Same as BaseWrappable, just new-style instead."""
 
-class ObjSpace:
+class ObjSpace(object):
     """Base class for the interpreter-level implementations of object spaces.
     http://codespeak.net/moin/pypy/moin.cgi/ObjectSpace"""
     

Modified: pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py
==============================================================================
--- pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py	(original)
+++ pypy/trunk/src/pypy/objspace/test/test_traceobjspace.py	Mon Jul 12 14:05:49 2004
@@ -1,28 +1,33 @@
 import autopath
 from pypy.tool import testit
-from pypy.objspace.trace import TraceObjSpace 
+from pypy.objspace import trace 
 from pypy.interpreter.gateway import app2interp
 from pypy.tool import pydis
     
 class Test_TraceObjSpace(testit.IntTestCase):
-
+    tspace = None
+    
     def setUp(self):
-        self.space = testit.objspace()
-
+        # XXX hack so we only have one trace space
+        if Test_TraceObjSpace.tspace is None:
+            newspace = testit.objspace().__class__()
+            Test_TraceObjSpace.tspace = trace.create_trace_space(newspace)
+        
     def tearDown(self):
         pass
 
     def perform_trace(self, app_func):
-        tspace = TraceObjSpace(self.space)
+        tspace = self.tspace
         func_gw = app2interp(app_func)
         func = func_gw.get_function(tspace)
+        tspace.settrace()
         tspace.call_function(tspace.wrap(func))
         res = tspace.getresult()
         return res 
 
     def test_traceobjspace_basic(self):
-        t = TraceObjSpace(self.space)
-        self.assert_(t.is_true(t.w_builtins))
+        tspace = self.tspace
+        self.assert_(tspace.is_true(tspace.w_builtins))
         #for name, value in vars(self.space).items():
         #    if not name.startswith('_'):
         #        self.assert_(value is getattr(t, name))
@@ -34,30 +39,39 @@
         res = self.perform_trace(app_f)
         disresult = pydis.pydis(app_f)
         self.assertEquals(disresult.bytecodes, list(res.getbytecodes()))
-        #self.assertEquals(len(list(res.getoperations())), 0)
 
-    def test_some_builtin(self):
+    def test_some_builtin1(self):
+        def app_f():
+            len([1,2,3,4,5])
+        res = self.perform_trace(app_f)
+        disresult = pydis.pydis(app_f)
+        self.assertEquals(len(disresult.bytecodes), len(list(res.getbytecodes())))
+
+    def test_some_builtin2(self):
         def app_f(): 
-            filter(None, []) # mapglobals() # ("c")
+            filter(None, []) # filter implemented in appspace -> has many more bytecodes        
         res = self.perform_trace(app_f)
         disresult = pydis.pydis(app_f)
-        self.assertEquals(disresult.bytecodes, list(res.getbytecodes()))
-        #self.assertEquals(len(list(res.getoperations())), 0)
+        self.failUnless(len(disresult.bytecodes) < len(list(res.getbytecodes())))
 
+    def get_operation(self, iter, optype, name):
+        for op in iter:
+            if isinstance(op, optype):
+                if op.callinfo.name == name:
+                    return op
+                
     def test_trace_oneop(self):
         def app_f(): 
             1 + 1
-        w = self.space.wrap
         res = self.perform_trace(app_f)
         disresult = pydis.pydis(app_f)
-        self.assertEquals(disresult.bytecodes, list(res.getbytecodes()))
-        ops = list(res.getoperations())
-        self.assert_(len(ops) > 0)
-        #op = ops[0]
-        #self.assertEquals(pydis.getbytecodename(op.bytecode), 'binary_add') # XXX 
-        #self.assertEquals(op.name, 'add')
-        #expected_w = (w(1), w(1))
-        #self.assertEquals_w(op.args_w, expected_w)
+        uw = self.tspace.unwrap
+        ops = res.getoperations()
+        op_start = self.get_operation(ops, trace.CallBegin, "add")
+        args = [uw(x) for x in op_start.callinfo.args]
+        self.assertEquals(args, [1, 1])
+        op_end = self.get_operation(ops, trace.CallFinished, "add")        
+        self.assertEquals(uw(op_end.res), 2)
 
 if __name__ == '__main__':
     testit.main()

Modified: pypy/trunk/src/pypy/objspace/trace.py
==============================================================================
--- pypy/trunk/src/pypy/objspace/trace.py	(original)
+++ pypy/trunk/src/pypy/objspace/trace.py	Mon Jul 12 14:05:49 2004
@@ -1,51 +1,87 @@
 """ 
-   trace object space traces operations and bytecode execution
+   Trace object space traces operations and bytecode execution
    in frames. 
 
 """
-from __future__ import generators
+
 from pypy.tool import pydis 
+from pypy.interpreter.baseobjspace import ObjSpace
 
 # __________________________________________________________________________
 #
 # Tracing Events 
 # __________________________________________________________________________
+#
 
-class ExecBytecode:
+class ExecBytecode(object):
     """ bytecode trace. """
     def __init__(self, frame):
         self.frame = frame 
         self.code = frame.code 
         self.index = frame.next_instr
-        #assert self.index < len(frame.code.co_code)
 
-class EnterFrame:
+class EnterFrame(object):
     def __init__(self, frame):
         self.frame = frame
 
-class LeaveFrame:
+class LeaveFrame(object):
     def __init__(self, frame):
         self.frame = frame
 
-class CallBegin:
+class CallBegin(object):
     def __init__(self, callinfo):
         self.callinfo = callinfo
 
-class CallFinished:
-    def __init__(self, callinfo):
+class CallFinished(object):
+    def __init__(self, callinfo, res):
         self.callinfo = callinfo
-
-class CallException:
-    def __init__(self, e, callinfo):
-        self.ex = e
+        self.res = res
+        
+class CallException(object):
+    def __init__(self, callinfo, e):
         self.callinfo = callinfo
+        self.ex = e
+
+class TraceResult(object):
+    """ this is the state of tracing-in-progress. """
+    def __init__(self, tracespace):
+        self.events = []  
+        self.tracespace = tracespace
+
+    def append(self, arg):
+        self.events.append(arg)
+
+    def getdisresult(self, frame, _cache = {}):
+        """ return (possibly cached) pydis result for the given frame. """
+        try:
+            return _cache[id(frame.code)]
+        except KeyError:
+            res = _cache[id(frame.code)] = pydis.pydis(frame.code)
+            assert res is not None
+            return res
+
+    def getbytecodes(self):
+        for event in self.events:
+            if isinstance(event, ExecBytecode):
+                disres = self.getdisresult(event.frame)
+                yield disres.getbytecode(event.index)
+               
+    def getoperations(self):
+        for event in self.events:
+            if isinstance(event, (CallBegin, CallFinished, CallException)):
+                yield event
+                
+    def getevents(self):
+        for event in self.events:
+            yield event
 
 # __________________________________________________________________________
 #
 # Tracer Proxy objects 
 # __________________________________________________________________________
 #
-class ExecutionContextTracer:
+
+class ExecutionContextTracer(object):
     def __init__(self, result, ec):
         self.__ec = ec
         self.__result = result
@@ -66,7 +102,7 @@
         return self.__ec.leave(previous_ec)
 
     def bytecode_trace(self, frame):
-        "called just before execution of a bytecode."
+        """ called just before execution of a bytecode. """
         self.__result.append(ExecBytecode(frame))
 
     #def exception_trace(self, operror):
@@ -74,7 +110,7 @@
     #    print "exception trace", operror
     #    return self.__ec.exception_trace(operror)
 
-class CallInfo:
+class CallInfo(object):
     """ encapsulates a function call with its arguments. """
     def __init__(self, name, func, args, kwargs):
         self.name = name
@@ -82,7 +118,7 @@
         self.args = args
         self.kwargs = kwargs
 
-class CallableTracer:
+class CallableTracer(object):
     def __init__(self, result, name, func):
         self.__result = result
         self.__name = name
@@ -91,129 +127,77 @@
     def __call__(self, *args, **kwargs):
         callinfo = CallInfo(self.__name, self.__func, args, kwargs) 
         self.__result.append(CallBegin(callinfo))
-        #print "calling into", self.__name, [type(x).__name__ for x in args]
-        #print args
+
         try:
             res = self.__func(*args, **kwargs)
         except Exception, e:
-            #self.__result.append(CallException(e, callinfo))
+            self.__result.append(CallException(callinfo, e))
             raise 
         else:
-            self.__result.append(CallFinished(callinfo))
+            self.__result.append(CallFinished(callinfo, res))
             return res
 
     def __getattr__(self, name):
         """ generically pass through everything we don't intercept. """
         return getattr(self.__func, name)
 
-class TraceObjSpace:
-    def __init__(self, space=None):
-        self.generalcache = {}
-        if space is None:
-            # make up a TrivialObjSpace by default
-            # ultimately, remove this hack and fix the -P option of tests
-            from pypy.objspace import trivial
-            space = trivial.TrivialObjSpace()
-        self.__space = space
-        self.settrace()
-
-    def settrace(self):
-        self.__result = TraceResult(self)
-
-    def getresult(self):
-        return self.__result
-
-    def loadfromcache(self, key, builder):
-        # hiding self.__cache.loadfromcache so that builder() can be called
-        # on self instead of self.__space, ignore the operations it performs
-        try:
-            return self.generalcache[key]
-        except KeyError:
-            saved = self.__result
-            self.settrace()
-            try:
-                return self.generalcache.setdefault(key, builder(key, self))
-            finally:
-                self.__result = saved
-
-    def getexecutioncontext(self):
-        ec = self.__space.getexecutioncontext()
-        if isinstance(ec, ExecutionContextTracer):
-            return ec
-        return ExecutionContextTracer(self.__result, ec)
-
-    def createexecutioncontext(self):
-        ec = self.__space.createexecutioncontext()
-        return ExecutionContextTracer(self.__result, ec)
-
-    def __getattr__(self, name):
-        obj = getattr(self.__space, name)
-        if callable(obj) and not hasattr(obj, '__bases__'):
-            return CallableTracer(self.__result, name, obj)
-        return obj
-
-class TraceResult:
-    """ this is the state of tracing-in-progress. """
-    def __init__(self, tracespace):
-        self.tracespace = tracespace
-        self.events = []  
-
-    def append(self, arg):
-        self.events.append(arg)
-
-    def getdisresult(self, frame, _cache = {}):
-        """ return (possibly cached) pydis result for the given frame. """
-        try:
-            return _cache[id(frame.code)]
-        except KeyError:
-            res = _cache[id(frame.code)] = pydis.pydis(frame.code)
-            assert res is not None
-            return res
-
-    def getbytecodes(self):
-        lastframe = None
-        for event in self.events:
-            #if isinstance(event, EnterFrame):
-            #    lastframe = event.frame
-            if isinstance(event, ExecBytecode):
-                disres = self.getdisresult(event.frame)
-                yield disres.getbytecode(event.index)
-
-    def getoperations(self):
-        for event in self.events:
-            #if isinstance(event, EnterFrame):
-            #    lastframe = event.frame
-            if isinstance(event, CallBegin):
-                yield event.callinfo
+    def __str__(self):
+        return "%s - CallableTracer(%s)" % (self.__name, self.__func)
+    __repr = __str__
+# __________________________________________________________________________
+#
+# Tracer factory 
+# __________________________________________________________________________
+#            
 
-    def getevents(self):
-        for event in self.events:
-            yield event
-            
+operations = None
+def get_operations():
+    global operations
+    if operations is None:
+        operations = dict([(r[0], r[0]) for r in ObjSpace.MethodTable])
+        for name in ["is_true", "newtuple", "newlist", "newstring", "newdict",
+                     "newslice", "call_args", "is_", "get_and_call_function",
+                     "wrap", "unwrap"]:
+            operations[name] = name
+
+    return operations
+
+def create_trace_space(space = None, operations = None):    
+    """ Will create a trace object space if no space supplied.  Otherwise
+    the object."""
+    
+    if space is None:
+        # make up a TrivialObjSpace by default
+        # ultimately, remove this hack and fix the -P option of tests
+        from pypy.objspace import trivial
+        space = trivial.TrivialObjSpace()
+
+    if operations is None:
+        operations = get_operations()
+
+    class TraceObjSpace(space.__class__):
+        def __getattribute__(self, name):
+            obj = super(TraceObjSpace, self).__getattribute__(name)
+            if callable(obj) and name in operations:
+                return CallableTracer(self.__result, name, obj)
+            return obj
+
+        def settrace(self):
+            self.__result = TraceResult(self)
+
+        def getresult(self):
+            return self.__result
+
+        def getexecutioncontext(self):
+            ec = super(TraceObjSpace, self).getexecutioncontext()
+            assert not isinstance(ec, ExecutionContextTracer)
+            return ExecutionContextTracer(self.__result, ec)
+    space.__class__ = TraceObjSpace
+    space.settrace()
+    return space
 
-Space = TraceObjSpace
+TraceObjSpace = Space = create_trace_space
 
 # ______________________________________________________________________
 # End of trace.py
 
-"""
-def display(bytecodedict, codeobject):
-    for i in range(len(codeobject.co_bytecode)):
-        print display_bytecode(codeobject, i)
-        if i in bytecodedict:
-            for opinfo in bytecodedict[i]:
-                print display(*opinfo)
-           
-class FrameIndex:
-    def __init__(self, frame, index):
-        self.frame = frame
-        self.index = index
-
-    def __hash__(self):
-        return hash((id(frame), index))
-    def _getframeindex(self):
-        frame = self.tracespace.space.getexecutioncontext().framestack[-1] 
-        index = frame.next_instr 
-        return FrameIndex(frame, index)
-            
-"""

Modified: pypy/trunk/src/pypy/tool/traceinteractive.py
==============================================================================
--- pypy/trunk/src/pypy/tool/traceinteractive.py	(original)
+++ pypy/trunk/src/pypy/tool/traceinteractive.py	Mon Jul 12 14:05:49 2004
@@ -12,7 +12,6 @@
 except:
     have_readline = False
     
-
 # PyPy imports
 import autopath
 
@@ -24,9 +23,6 @@
 
 from pypy.objspace import trace
 
-
-#//////////////////////////////////////////////////////////////////////////
-
 if have_readline:
 
     class Completer:
@@ -46,7 +42,6 @@
             except IndexError:
                 return None
 
-
         def global_matches(self, text):
             
             import __builtin__            
@@ -85,40 +80,33 @@
 
             return matches
 
-
-#//////////////////////////////////////////////////////////////////////////
-
 class TraceConsole(code.InteractiveConsole):
     def __init__(self, space):
         code.InteractiveConsole.__init__(self)
-        s = self.space = trace.TraceObjSpace(space)
+        s = self.space = trace.create_trace_space(space)
         s.setitem(s.w_globals, s.wrap("__pytrace__"), s.w_True)
-        self.objspacename = space.__class__.__name__
-
+        self.objspacename = space.__class__.__bases__[0].__name__
 
     def interact(self, banner=None):
         if banner is None:
-            banner = "Python %s in pypy(trace)\n%s / %s - %s" % (
-                sys.version, self.__class__.__name__,
-                self.space,
-                " [Use  __pytrace__ flag to turn off tracing.]" )
+            banner = "PyPy in TraceObjSpace(%s) on top of %s\n%s" % (
+                self.objspacename, sys.version.split()[0],
+                " [Use  __pytrace__ flag to turn off tracing]" )
         code.InteractiveConsole.interact(self, banner)
 
-
     def raw_input(self, prompt=""):
         # add a character to the PyPy prompt so that you know where you
         # are when you debug it with "python -i py.py"
         return code.InteractiveConsole.raw_input(self, prompt[0] + prompt)
 
-
     def runcode(self, code):
         # 'code' is a CPython code object
         from pypy.interpreter.pycode import PyCode
         pycode = PyCode()._from_code(code)
 
         s = self.space
-        trace_flag = s.unwrap(s.getitem(s.w_globals,
-                                        s.wrap("__pytrace__")))
+        trace_flag = s.is_true(s.getitem(s.w_globals,
+                                         s.wrap("__pytrace__")))
         if trace_flag:
             s.settrace()
 
@@ -127,23 +115,24 @@
             if trace_flag:
                 res = s.getresult()
                 s.settrace()
-                print_result(res)
+                print_result(s, res)
                 
         except baseobjspace.OperationError, operationerr:
             if trace_flag:
                 res = s.getresult()
                 s.settrace()
-                print_result(res)
+                print_result(s, res)
 
             # XXX insert exception info into the application-level sys.last_xxx
             print
-            operationerr.print_detailed_traceback(self.space)
+            operationerr.print_application_traceback(self.space)
 
         else:
             print
 
     def runsource(self, source, ignored_filename = "<input>", symbol = "single"):
-        hacked_filename = '<inline>\n' + source
+        hacked_filename = '<inline> ' + source[:80] + "..."
+        hacked_filename = hacked_filename.replace("\n", r"\n")
         try:
             code = self.compile(source, hacked_filename, symbol)
 
@@ -157,9 +146,6 @@
         self.runcode(code)
         return False
 
-
-#//////////////////////////////////////////////////////////////////////////
-
 def trace_interactive(space, banner = None):
     s = space
 
@@ -172,7 +158,6 @@
 
     if have_readline:
         # Keep here to save windoze tears
-
         readline.set_completer(Completer(s).complete)
         readline.parse_and_bind("tab: complete")
         readline.set_history_length(25000)
@@ -188,15 +173,11 @@
 
     console.interact(banner)
 
-
-#//////////////////////////////////////////////////////////////////////////
-
 if __name__ == '__main__':
     from pypy.tool import option
     args = option.process_options(option.get_standard_options(),
                                   option.Options)
 
-
     # Create objspace...
     space = option.objspace()
     trace_interactive(space)

Modified: pypy/trunk/src/pypy/tool/traceop.py
==============================================================================
--- pypy/trunk/src/pypy/tool/traceop.py	(original)
+++ pypy/trunk/src/pypy/tool/traceop.py	Mon Jul 12 14:05:49 2004
@@ -1,33 +1,9 @@
+
 import autopath
 
 from pypy.tool import pydis
-from pypy.interpreter.baseobjspace import ObjSpace
 from pypy.objspace import trace
 
-from pypy.objspace.trace import TraceObjSpace
-from pypy.objspace.trivial import TrivialObjSpace
-from pypy.objspace.std import StdObjSpace
-
-from pypy.interpreter.gateway import app2interp
-
-# Global
-operations = dict([(r[0], r[0]) for r in ObjSpace.MethodTable])
-
-
-def perform_trace(space, app_func, *args, **kwds):
-    # Wrap up our space, with a trace space
-    tspace = TraceObjSpace(space)
-
-    # Add our function
-    func_gw = app2interp(app_func) 
-    func = func_gw.get_function(tspace)
-
-    # Run the func in the trace space and return results
-    tspace.settrace()
-    funcres = func(*args, **kwds) 
-    traceres = tspace.getresult()
-    return funcres, traceres  
-
 def getdisresult(obj, _cache={}):
     """ return dissassemble result for the given obj which can be a
         pyframe or function or a code object. 
@@ -40,236 +16,137 @@
         disresult = _cache[obj] = pydis.pydis(obj)
         return disresult
 
-import repr
-def get_repr():
-    " Our own repr function for pretty print. "
-    repr_obj = repr.Repr()
-    repr_obj.maxstring = 120
-    repr_obj.maxother = 120
-
-    def our_repr(*args):
-        try:
-            return repr_obj.repr(*args)
-
-        except:
-            return "ERROR"
-
-    return our_repr
-Repr = get_repr()
-
 def line_begin(indent):
     if indent:
         return ("  " * indent) + "|-"
     else:
         return ""
     
-def print_result(traceres):
+def print_result(space, traceres, operations_level = 1000):
+    # XXX Refactor this - make more configurable.
     indentor = '    '
     lastframe = None
     frame_count = 0
     indent = ""
+    skip_frame_count = None
+    stack_info = []
     for event in traceres.getevents():
+        
         if isinstance(event, trace.EnterFrame):
-            print line_begin(frame_count) + ("<<<<<enter %s >>>>>>>" % event.frame)
+            if not skip_frame_count:
+                print line_begin(frame_count) + ("<<<<<enter %s @ %s>>>>>>>" % (event.frame.code.co_filename, event.frame.code.co_firstlineno))
+
             lastframe = event.frame
             frame_count += 1
+
         elif isinstance(event, trace.LeaveFrame):
             frame_count -= 1
-            print line_begin(frame_count) + ("<<<<<leave %s >>>>>>>" % lastframe)
-        elif isinstance(event, trace.ExecBytecode):
-            disresult = getdisresult(event.frame) 
-            print line_begin(frame_count), "%2d" % event.index, "      ", disresult.getbytecode(event.index)
-            lastframe = event.frame
 
-        elif isinstance(event, trace.CallBegin):
-            info = event.callinfo
-            if info.name in operations:
-                print line_begin(frame_count), " " * 40, info.name, repr_args(lastframe, info.args)
-                indent += indentor 
-        elif isinstance(event, trace.CallFinished):
-            indent = indent[:-len(indentor)]
-        else:
-            pass
-    
+            # No more bytecodes to skip at this level
+            if frame_count < skip_frame_count:
+                skip_frame_count = 0
 
-def trace_function(space, fn, *arg, **kwds):
-    
-    funcres, traceres = perform_trace(space, fn, *arg, **kwds)
-    indentor = '    '
-    indent = ' '
-    lastframe = None
-    for event in traceres.getevents():
-        if isinstance(event, trace.EnterFrame):
-            lastframe = event.frame
+            if not skip_frame_count:
+                print line_begin(frame_count) + ("<<<<<leave %s >>>>>>>" % lastframe.code.co_filename)
+        elif isinstance(event, trace.ExecBytecode):
+
+            if frame_count == skip_frame_count:
+                skip_frame_count = 0
 
-        if isinstance(event, trace.ExecBytecode):
             disresult = getdisresult(event.frame) 
-            print indent, event.index, "      ", disresult.getbytecode(event.index)
+            bytecode = disresult.getbytecode(event.index)
+
+            if not skip_frame_count:
+                print line_begin(frame_count), "%2d" % event.index, "      ", bytecode
             lastframe = event.frame
 
+            if bytecode.name in ["PRINT_EXPR", "PRINT_ITEM", "PRINT_NEWLINE"]:
+                print line_begin(frame_count + 1), "..."
+                skip_frame_count = frame_count           
+
         elif isinstance(event, trace.CallBegin):
             info = event.callinfo
-            if info.name in operations:
-                print indent, " " * 40, info.name, repr_args(lastframe, info.args)
-                indent += indentor 
+            if not skip_frame_count:
+                stack_info.append(info)
+                if len(stack_info) <= operations_level:
+                    print line_begin(frame_count), " " * 17 + ">> ", info.name, repr_args(space, lastframe, info.args)
+                frame_count += 1
+                    
         elif isinstance(event, trace.CallFinished):
-            indent = indent[:-len(indentor)]
+            info = event.callinfo
+            if not skip_frame_count:
+                assert stack_info.pop(-1) == event.callinfo
+                frame_count -= 1
+                if len(stack_info) < operations_level:
+                    print line_begin(frame_count), " " * 20, info.name, "=: ", repr_value(space, event.res)
+        
+        elif isinstance(event, trace.CallException):
+            info = event.callinfo
+            if not skip_frame_count:
+                assert stack_info.pop(-1) == event.callinfo
+                frame_count -= 1
+                if len(stack_info) < operations_level:
+                    print line_begin(frame_count), " " * 17 + "x= ", info.name, event.ex
         else:
             pass
-    return funcres, traceres
+    
+def repr_value(space, value):
+##     try:
+##         res = str(space.unwrap(value))
+##     except:
+##         res = str(value)
+    res = str(value)
+    return res[:240]
 
-def repr_args(frame, args):
+def repr_args(space, frame, args):
     l = []
-    
-    space = frame and frame.space or None
     for arg in args:
         if frame and space.is_true(space.is_(arg, frame.w_globals)):
             l.append('w_globals')
         elif frame and space.is_true(space.is_(arg, space.w_builtins)):
             l.append('w_builtins')
         else:
-            l.append(Repr(arg) [:50])
-    return ", ".join(l)
+            l.append(repr_value(space, arg))
+            
+    return "(" + ", ".join(l) + ")"
 
-def app_test():
-    a = 1
-    for i in range(10):
-        print i
-    
 
-def test():
-    space = TrivialObjSpace()
-    #space = StdObjSpace()
-    
+def perform_trace(tspace, app_func, *args_w, **kwds_w):
+    from pypy.interpreter.gateway import app2interp
+    from pypy.interpreter.argument import Arguments    
 
-    funcres, traceres =  trace_function(space, app_test)
-    print "function result -->", funcres
+    # Create our function
+    func_gw = app2interp(app_func)
+    func = func_gw.get_function(tspace)
+    w_func = tspace.wrap(func)
+    args = Arguments(tspace, args_w, kwds_w)
 
-## from earthenware.utils.stacktrace
-## try:
-##     test()
-## except:
-##     earthenware.utils.stacktrace.print_exception(sys.
- 
-## def rpretty_print(spacedump):
-##     " Pretty print for rdump() calls to Trace object spaces. "
-
-##     Repr = get_repr()
-##     for operation, bytecodes in spacedump:
-##         for opcode, opname, oparg, ins_idx in bytecodes:
-##             print "\t%s\t%s\t\t%s"  % (ins_idx, opname, oparg) 
-
-##         if operation is not None:
-##             op_name = operation[0]
-##             args = operation[1:]
-##             print " ***\t", op_name, " ->",
-##             for a in args:
-##                 print Repr(a),
-##             print
-
-
-## def add_func(space, func, w_globals):
-##     """ Add a function to globals. """
-##     func_name = func.func_name
-##     w_func_name = space.wrap(func_name)
-##     w_func = space.wrap(func)
-##     space.setitem(w_globals, w_func_name, w_func)
-
-
-## def run_in_space(space, func, *args):
-##     # Get execution context and globals
-##     ec = space.getexecutioncontext()
-##     w_globals = ec.make_standard_w_globals()
-
-##     # Add the function to globals
-##     add_func(space, func, w_globals)
-
-##     # Create wrapped args
-##     args_w = [space.wrap(ii) for ii in args]
-##     code = func.func_code
-##     code = PyCode()._from_code(code)
-
-##     # Create frame
-##     frame = code.create_frame(space, w_globals)
-##     frame.setfastscope(args_w)
-    
-##     # start/stop tracing while running frame
-##     space.start_tracing()
-##     res = frame.run()
-##     space.stop_tracing()
-
-##     return res
-
-
-## def pretty_print(spacedump):
-##     " Pretty print for rdump() calls to Trace object spaces. "
-##     Repr = get_repr()
-
-##     for line in spacedump:
-##         ((opcode, opname, arg, ins_idx), spaceops) = line
-##         start = "%4i %s " % (ins_idx, opname)
-##         start = start + " " * (20 - len(start)) + str(arg)
-##         start = start + " " * (30 - len(start))
-##         if not spaceops:
-##             print start
-##         else:
-##             op = spaceops.pop(0)
-##             print start
-##             for op_name, args in spaceops:
-##                 print " " * 30, op_name, Repr(args)
-
-
-## def _trace_function(space, reverse_pretty_print_flag, fn, *arg, **kwds):
-##     res = run_in_space(space, fn, *arg, **kwds)
-##     if reverse_pretty_print_flag:
-##         # Get reverse dump
-##         spacedump = space.rdump()
-
-##         # Pretty print dump
-##         rpretty_print(spacedump)
-##     else:
-##         # Get dump
-##         spacedump = space.dump()
-
-##         # Pretty dump
-##         pretty_print(spacedump)
-
-##     return res
-
-## def trace_function(trace_space, fn, *arg, **kwds):
-##     return _trace_function(trace_space, False, fn, *arg, **kwds)
-
-## def rtrace_function(trace_space, fn, *arg, **kwds):
-##     return _trace_function(trace_space, True, fn, *arg, **kwds)
-
-
-## def trace_function2(space, fn, *arg, **kwds):
-##     return _trace_function(Trace(space), False, fn, *arg, **kwds)
-
-## def rtrace_function2(space, fn, *arg, **kwds):
-##     return _trace_function(Trace(space), True, fn, *arg, **kwds)
-
-
-                   
- 
-## ## # Create space
-## ## if __name__ == "__main__":
-## ##     try:
-## ##         import readline
-## ##     except ImportError:
-## ##         pass
-
-## ##     from pypy.tool import option
-## ##     from pypy.tool import testit
-## ##     args = option.process_options(option.get_standard_options(),
-## ##                                   option.Options)
-## ##     objspace = option.objspace()
-
-
-## ##     def run(*args, **kwds):
-## ##     def run_function(space, func, *args):
-## ##     from pypy.objspace.std import StdObjSpace
-## ##     space = Trace(StdObjSpace)
+    # Run the func in the trace space and return results
+    tspace.settrace()
+    w_result = tspace.call_args(w_func, args)
+    trace_result = tspace.getresult()
+    tspace.settrace()
+    return w_result, trace_result
+
+
+if __name__ == '__main__':
+    from pypy.tool import option
+    args = option.process_options(option.get_standard_options(),
+                                  option.Options)
+
+    # Create objspace...
+    space = option.objspace()
+
+    # Wrap up our space, with a trace space
+    tspace = trace.create_trace_space(space)
 
+    def app_test(x):
+        count = 0
+        for ii in range(x):
+            count += ii
+        return count
 
+    res, traceres = perform_trace(tspace, app_test, tspace.wrap(5))
+    print_result(tspace, traceres)
 
+    print "Result", res



More information about the Pypy-commit mailing list