[pypy-svn] r44540 - in pypy/dist/pypy/translator/cli: . test

antocuni at codespeak.net antocuni at codespeak.net
Tue Jun 26 14:00:35 CEST 2007


Author: antocuni
Date: Tue Jun 26 14:00:33 2007
New Revision: 44540

Modified:
   pypy/dist/pypy/translator/cli/silverpython.py
   pypy/dist/pypy/translator/cli/test/test_silverpython.py
Log:
- @export decorator, to let the user to specify the annotation of the
  enty-points of the DLL

- a procedure to scan a file and collect all the export()ed names



Modified: pypy/dist/pypy/translator/cli/silverpython.py
==============================================================================
--- pypy/dist/pypy/translator/cli/silverpython.py	(original)
+++ pypy/dist/pypy/translator/cli/silverpython.py	Tue Jun 26 14:00:33 2007
@@ -1,8 +1,20 @@
+#! /usr/bin/env python
+"""
+Usage:  silverpython.py <module-name>.py
+
+Compiles an RPython module into a .NET dll.
+"""
+
+import sys
+import new
+import types
+import os.path
+
 from pypy.translator.driver import TranslationDriver
 from pypy.translator.cli.entrypoint import DllEntryPoint
 
 class DllDef:
-    def __init__(self, name, namespace, functions=[], classes=[]):
+    def __init__(self, name, namespace, functions=[]):
         self.name = name
         self.namespace = namespace
         self.functions = functions # [(function, annotation), ...]
@@ -20,25 +32,61 @@
             if not hasattr(func, '_namespace_'):
                 func._namespace_ = self.namespace
         driver = TranslationDriver()
+        driver.config.translation.ootype.mangle = False
         driver.setup_library(self)
         driver.proceed(['compile_cli'])
         return driver
 
-
-class MyClass:
-    def __init__(self, x):
-        self.x = x
-
-    def foo(self):
-        return self.x
-
-def main():
-    dll = DllDef('mylibrary', 'foo', [], [
-        (MyClass, [int]),
-        ])
+class export(object):
+    def __new__(self, *args, **kwds):
+        if len(args) == 1 and isinstance(args[0], types.FunctionType):
+            func = args[0]
+            func._inputtypes_ = ()
+            return func
+        return object.__new__(self, *args, **kwds)
+    
+    def __init__(self, *args, **kwds):
+        self.inputtypes = args
+        self.namespace = kwds.pop('namespace', None)
+        if len(kwds) > 0:
+            raise TypeError, "unexpected keyword argument: '%s'" % kwds.keys()[0]
+
+    def __call__(self, func):
+        func._inputtypes_ = self.inputtypes
+        if self.namespace is not None:
+            func._namespace_ = self.namespace
+        return func
+
+def collect_entrypoints(dic):
+    entrypoints = []
+    for item in dic.itervalues():
+        if isinstance(item, types.FunctionType) and hasattr(item, '_inputtypes_'):
+            entrypoints.append((item, item._inputtypes_))
+    return entrypoints
+
+def compile_dll(filename):
+    _, name = os.path.split(filename)
+    dllname, _ = os.path.splitext(name)
+
+    module = new.module(dllname)
+    execfile(filename, module.__dict__)
+    entrypoints = collect_entrypoints(module.__dict__)
+    namespace = module.__dict__.get('_namespace_', dllname)
+    
+    dll = DllDef(dllname, namespace, entrypoints)
     driver = dll.compile()
     driver.copy_cli_dll()
-    
+
+def main(argv):
+    if len(argv) != 2:
+        print >> sys.stderr, __doc__
+        sys.exit(2)
+    filename = argv[1]
+    if not os.path.exists(filename):
+        print >> sys.stderr, "Cannot find file %s" % filename
+        sys.exit(1)
+    compile_dll(filename)    
 
 if __name__ == '__main__':
-    main()
+    main(sys.argv)
+

Modified: pypy/dist/pypy/translator/cli/test/test_silverpython.py
==============================================================================
--- pypy/dist/pypy/translator/cli/test/test_silverpython.py	(original)
+++ pypy/dist/pypy/translator/cli/test/test_silverpython.py	Tue Jun 26 14:00:33 2007
@@ -1,6 +1,6 @@
 from pypy.tool import udir
 from pypy.translator.cli.rte import Target
-from pypy.translator.cli.silverpython import DllDef
+from pypy.translator.cli.silverpython import DllDef, export, collect_entrypoints
 from pypy.translator.cli.test.runtest import CliFunctionWrapper, CliTest
 
 TEMPLATE = """
@@ -31,7 +31,6 @@
         func = CliFunctionWrapper(MyTarget.get())
         return func()
 
-
     def test_compilation(self):
         res = self._csharp(None, 'Console.WriteLine(42);')
         assert res == 42
@@ -56,3 +55,30 @@
         dll.compile()
         res = self._csharp('test', 'Console.WriteLine("{0}, {1}", Test.foo(42), Test.bar(42));')
         assert res == (43, 84)
+
+    def test_export(self):
+        @export(int, float)
+        def foo(x, y):
+            pass
+        @export(int, float, namespace='test')
+        def bar(x, y):
+            pass
+        @export
+        def baz():
+            pass
+
+        assert foo._inputtypes_ == (int, float)
+        assert not hasattr(foo, '_namespace_')
+        assert bar._inputtypes_ == (int, float)
+        assert bar._namespace_ == 'test'
+        assert baz._inputtypes_ == ()
+
+    def test_collect_entrypoints(self):
+        @export(int, float)
+        def foo(x, y):
+            pass
+        def bar(x, y):
+            pass
+        mydict = dict(foo=foo, bar=bar, x=42)
+        entrypoints = collect_entrypoints(mydict)
+        assert entrypoints == [(foo, (int, float))]



More information about the Pypy-commit mailing list