[pypy-svn] r4923 - in pypy/trunk/src/pypy/translator: . test

ale at codespeak.net ale at codespeak.net
Fri Jun 4 18:46:04 CEST 2004


Author: ale
Date: Fri Jun  4 18:46:03 2004
New Revision: 4923

Added:
   pypy/trunk/src/pypy/translator/test/some_snippets_test.py
Modified:
   pypy/trunk/src/pypy/translator/genpyrex.py
   pypy/trunk/src/pypy/translator/test/snippet.py
Log:
Genpyrex now handles exceptions and inpalce operators.

A little reordering of snippets.py

some_snippets_test.py compiles and run 38 of the 43 snippets correctly ( It should be folded into the other unittests)

Modified: pypy/trunk/src/pypy/translator/genpyrex.py
==============================================================================
--- pypy/trunk/src/pypy/translator/genpyrex.py	(original)
+++ pypy/trunk/src/pypy/translator/genpyrex.py	Fri Jun  4 18:46:03 2004
@@ -20,14 +20,20 @@
 
     def __call__(self):
         operator = self.gen.ops.get(self.op.opname, self.op.opname)
-        #print "operator, ", self.op.opname, operator, self.gen.ops
-
         args = self.argnames
         if not (operator[0] >= "a" and operator[0] <= "z"):
             if len(args) == 1:
                 return "%s = %s %s" % (self.resultname, operator) + args
             elif len(args) == 2:
-                return "%s = %s %s %s" % (self.resultname, args[0], operator, args[1])
+                #Inplace operators
+                inp=['+=','-=','*=','/=','%=','^=','//=','div=','**=','<<=','>>=','!=','&=']
+                if operator in inp:
+                    temp_str="temp_xx12=%s %s %s\n"%(args[0], operator[:-1], args[1])
+                    temp_str+="%s=temp_xx12\n"%args[0]
+                    temp_str+="%s=temp_xx12"%self.resultname
+                    return temp_str
+                else:
+                    return "%s = %s %s %s" % (self.resultname, args[0], operator, args[1])
             elif len(args) == 3 and operator == "**": #special case, have to handle it manually
                 return "%s = pow(%s, %s, %s)" % (self.resultname,) + args
             else:
@@ -181,7 +187,6 @@
     def gen_graph(self):
         fun = self.functiongraph
         self.entrymap = mkentrymap(fun)
-        for block in self.entrymap : check_consistent_exits(block)
         currentlines = self.lines
         self.lines = []
         self.indent += 1 
@@ -200,10 +205,10 @@
         except AttributeError:
             def function_object(): pass   # XXX!!!
         # make the function visible from the outside under its original name
-        hackedargs = ', '.join([var.name for var in fun.getargs()])
-        self.putline("def %s(%s):" % (fun.name, hackedargs))
+        args = ', '.join([var.name for var in fun.getargs()])
+        self.putline("def %s(%s):" % (fun.name, args))
         self.indent += 1
-        self.putline("return %s(%s)" % (self.getfunctionname(function_object), hackedargs))
+        self.putline("return %s(%s)" % (self.getfunctionname(function_object), args))
         self.indent -= 1
         # go ahead with the mandled header and body of the function
         self.putline("def %s(%s):" % (self.getfunctionname(function_object), params))
@@ -270,7 +275,10 @@
 
     def getclassname(self,cls):
         assert inspect.isclass(cls)
-        return '%s__%x' % (cls.__name__, id(cls))#self._hackname(cls)
+        name = cls.__name__
+        if issubclass(cls,Exception):
+            return name
+        return '%s__%x' % (name, id(cls))#self._hackname(cls)
     
     def getfunctionname(self,func):
         assert inspect.isfunction(func) or inspect.ismethod(func)
@@ -295,7 +303,7 @@
             else:
                 #fff=self._hackname(obj.value)
                 fff=repr(obj.value)
-                if isinstance(obj.value, int):
+                if isinstance(obj.value,( int,long)):
                     fff = repr(int(obj.value))
             return fff
         else:
@@ -397,10 +405,4 @@
             return '\n'.join(self.lines)
         else:
             return ''
-        
-def check_consistent_exits(block):
-    for exit in block.exits :
-        if len(exit.args) != len(exit.target.inputargs):
-            print "inconsistent block exit", block,exit,exit.args
-            print "more", exit.target,exit.target.inputargs
-            
\ No newline at end of file
+

Modified: pypy/trunk/src/pypy/translator/test/snippet.py
==============================================================================
--- pypy/trunk/src/pypy/translator/test/snippet.py	(original)
+++ pypy/trunk/src/pypy/translator/test/snippet.py	Fri Jun  4 18:46:03 2004
@@ -61,6 +61,8 @@
                    'name': 'knownkeysdict'},
  'merge_setattr': {'arg_names': ['x'],'arg_types':[object],
                    'name': 'merge_setattr'},
+# 'methodcall1': {'arg_names': ['cond'],'arg_types':[int],
+#                   'name': 'methodcall1'},
  'my_bool': {'arg_names': ['x'],'arg_types':[object],
              'name': 'my_bool'},
  'my_gcd': {'arg_names': ['a', 'b'],'arg_types':[int,int],
@@ -382,13 +384,6 @@
         self.attr = 1
         return E(), y
 
-def methodcall1(cond):
-    if cond:
-        x = G()
-    else:
-        x = H()
-    return x.m(42)
-
 def knownkeysdict(b):
     if b:
         d = {'a': 0}
@@ -411,29 +406,6 @@
     z.my_attribute = v
     return z.my_method()
 
-# --------------------(Currently) Non runnable Functions ---------------------
-
-def somebug1(n):
-    l = []
-    v = l.append
-    while n:
-        l[7] = 5
-    return v
-
-def inheritance_nonrunnable():
-    d = D()
-    d.stuff = (-12, -12)
-    e = E()
-    e.stuff = (3, "world")
-    return C().stuff
-
-# --------------------(Currently) Non compillable Functions ---------------------
-
-def attrs():
-    def b(): pass
-    b.f = 4
-    b.g = 5
-    return b.f + b.g
 
 def powerset(setsize):
     """Powerset
@@ -465,5 +437,37 @@
         bitmask += 1
     return powerset
 
+# --------------------(Currently) Non runnable Functions ---------------------
+
+def somebug1(n):
+    l = []
+    v = l.append
+    while n:
+        l[7] = 5
+    return v
+
+def inheritance_nonrunnable():
+    d = D()
+    d.stuff = (-12, -12)
+    e = E()
+    e.stuff = (3, "world")
+    return C().stuff
+
+# --------------------(Currently) Non compillable Functions ---------------------
+
+def attrs():
+    def b(): pass
+    b.f = 4
+    b.g = 5
+    return b.f + b.g
+
 def getstuff(x):
     return x.stuff
+
+def methodcall1(cond):
+    if cond:
+        x = G()
+    else:
+        x = H()
+    return x.m(42)
+

Added: pypy/trunk/src/pypy/translator/test/some_snippets_test.py
==============================================================================
--- (empty file)
+++ pypy/trunk/src/pypy/translator/test/some_snippets_test.py	Fri Jun  4 18:46:03 2004
@@ -0,0 +1,100 @@
+""" 
+
+    Use all functions in snippet to test translation to pyrex
+    
+"""
+import autopath
+import traceback
+from pypy.tool import testit
+from pypy.translator.translator import Translator
+
+from pypy.translator.test import snippet
+
+import inspect
+
+def compile(func,argtypes=[]):
+    
+    t = Translator(func)
+    t.simplify()
+    t.annotate(argtypes)#.simplify()
+    #t.view()
+    compiled_function = t.compile()
+    return compiled_function
+
+def compile_by_inspecting(module):
+    bad=0
+    good=0
+    funcs={}
+    all=module.__dict__.items()
+    for fu in all:
+        if isinstance(fu[1],type(compile)):
+            func_info={}
+            func_versions={}
+            try:
+                args=inspect.getargspec(fu[1])
+                func_info['arg_names']=args[0]
+                func_info['name']=fu[0]
+                func_versions['python']=fu[1]
+                func_versions['pyrex']=compile(fu[1],[int]*len(args[0]))
+            except:
+                print fu[0]
+                bad+=1
+            else:
+                good+=1
+                funcs[fu[0]]=(func_info,func_versions)
+    print "Good: %i, Bad : %i, All: %i"%(good,bad,good+bad) 
+    return funcs
+def random_arg(arg):
+    if arg is int:
+        return 5
+    if arg is list:
+        return [1,2,3,4,5,6] # [1,'ere','fggf']Doesn't work for snippet.yast
+    if arg is str:
+        return 'python'
+    else:
+        return 'object'
+    
+def compile_by_function_info(module,info):
+    result={}
+    for func_name in info.keys():
+        func=module.__dict__[func_name]
+        arg_types=info[func_name]['arg_types']
+        try:
+            pyrex_func=compile(func,arg_types)
+        except:
+            traceback.print_exc()
+            print "Pyrex Compilation exception",func_name
+        args=tuple([random_arg(atype) for atype in arg_types])
+        try:
+            pyresult=func(*args)
+            try:
+                pyrexresult=pyrex_func(*args)
+            except:
+                print "pyrex function not runnable",func_name
+                raise
+        except:
+            print "Python Function not runnable",func_name
+            print traceback.print_exc()
+        else:
+            result[func_name]=(pyresult, pyrexresult) #or (pyresult,pyrexresult)
+        
+    return  result
+  
+def get_funcs_from_module(module):
+    info=module.__dict__.get('function_info',None)
+    if info:
+        funcs=compile_by_function_info(module,info)
+    else:    
+        funcs=compile_by_inspecting(module)
+    return funcs
+    
+if __name__=='__main__':
+    funcs=get_funcs_from_module(snippet)
+    import pprint
+    print len(funcs)
+    for f in funcs.keys():
+        assert funcs[f][0]==funcs[f][1],"%s!=%s"%(funcs[f][0],funcs[f][1])
+        print f,
+        pprint.pprint(funcs[f])
+    
+    



More information about the Pypy-commit mailing list