changeset 164:0cdf99ec5204

runtime_sugar: first approximation
author Sigurd Meldgaard <stm@daimi.au.dk>
date Wed, 09 Dec 2009 12:52:40 +0100
parents 0b1c4d4961af
children 6cad00158f8a
files pysmcl/runtime_sugar.py
diffstat 1 files changed, 37 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pysmcl/runtime_sugar.py	Wed Dec 09 12:52:40 2009 +0100
@@ -0,0 +1,37 @@
+import pysmcl.ast_wrapper as ast
+
+
+def runtime_sugar(f):
+    """ *f* is the AST of a function written in pysmcl (after
+    desuaring if's) and makes an implicit parameter out of the
+    runtime, and makes any input, output, get, etc calls use that."""
+
+    def make_runtime_name(loc, ctx=ast.Load):
+        r = ast.Name(id = "runtime", ctx=ctx)
+        ast.copy_location(loc, r)
+        return r
+
+    name = make_runtime_name(f, ctx=ast.Param)
+    f.args.args = [name]
+
+    class Rewriter(ast.NodeVisitor):
+
+        def visit_Call(self, node):
+            runtime = make_runtime_name(node.func)
+            if(self.is_function(node, "output")):
+                r = ast.Attribute(value=runtime,
+                                  identifier="output")
+                ast.copy_location(node.func, r)
+                node.func = r
+            if(self.is_function(node, "input")):
+                r = ast.Attribute(value=runtime,
+                                  identifier="input")
+                ast.copy_location(node.func, r)
+                node.func = r
+            if(self.is_function(node, "get")):
+                node.args.insert(0, name)
+
+        def is_function(self, node, fname):
+            return isinstance(node.func, ast.Name) and node.func.id == fname
+
+    Rewriter().visit(f)