Commits

Andrew Godwin committed 87d5f20

Factored out the if variants.

Comments (0)

Files changed (2)

kugelblitz/translator/__init__.py

 from kugelblitz.translator.expressions import ExprTranslator, BinOpTranslator, BoolOpTranslator, UnaryOpTranslator, CompareTranslator
 from kugelblitz.translator.values import NumTranslator, ListTranslator, NameTranslator
 from kugelblitz.translator.assignment import AssignTranslator, AugAssignTranslator
+from kugelblitz.translator.control import IfTranslator, IfExprTranslator
 
 def wrap_old_translator(func):
     class WrappedTranslator(BaseTranslator):
             
             ast.For: None,
             ast.While: None,
-            ast.If: wrap_old_translator(translate_if),
+            ast.If: IfTranslator,
             ast.With: None,
             
             ast.Raise: wrap_old_translator(translate_raise),
             ast.BinOp: BinOpTranslator,
             ast.UnaryOp: UnaryOpTranslator,
             ast.Lambda: wrap_old_translator(translate_lambda),
-            ast.IfExp: wrap_old_translator(translate_if_exp),
+            ast.IfExp: IfExprTranslator,
             ast.Dict: None,
             #ast.Set: None, Not in 2.6
             ast.ListComp: None,
         'body_def': translate_body([node.body]),
     }
 
-def translate_if(node):
-    s = ["if (%(test_def)s) { %(body_def)s }" % {
-        'test_def': translate(node.test),
-        'body_def': translate_body(node.body),
-    }]
-    if node.orelse:
-        s.append("else { %(orelse_def)s }" % {
-            's': s,
-            'orelse_def': translate_body(node.orelse),
-        })
-    return '\n'.join(s)
-
-def translate_if_exp(node):
-    return '%(test)s ? %(body)s : %(orelse)s' % {
-        'test': translate(node.test),
-        'body': translate(node.body),
-        'orelse': translate(node.orelse),
-    }
-
 def translate_attribute(node):
     return "%(left)s.%(right)s" % {
         "left": translate(node.value),

kugelblitz/translator/control.py

+from kugelblitz.translator.base import BaseTranslator, ast
+from kugelblitz.translator.toplevel import BodyTranslator
+from kugelblitz.translator.exceptions import CompileError
+
+class IfTranslator(BodyTranslator):
+
+    def translate(self):
+        s = ["if (%(test_def)s) { %(body_def)s }" % {
+            'test_def': self.sub_translate(self.node.test),
+            'body_def': self.translate_body(self.node.body),
+        }]
+        if self.node.orelse:
+            s.append("else { %(orelse_def)s }" % {
+                's': s,
+                'orelse_def': self.translate_body(self.node.orelse),
+            })
+        return '\n'.join(s)
+
+class IfExprTranslator(BodyTranslator):
+
+    def translate(self):
+        return '%(test)s ? %(body)s : %(orelse)s' % {
+            'test': self.sub_translate(self.node.test),
+            'body': self.sub_translate(self.node.body),
+            'orelse': self.sub_translate(self.node.orelse),
+        }