Commits

Andrew Godwin committed 72e863e

Much nicer indentation for a few of the structures.

  • Participants
  • Parent commits 9eb2030

Comments (0)

Files changed (6)

File kugelblitz/translator/__init__.py

 def translate(node):
     return get_translator(node).translate()
 
-def get_translator(node):
+def get_translator(node, **kwargs):
     try:
         return {
             # mod
             ast.List: ListTranslator,
             ast.Tuple: ListTranslator,
             
-        }[node.__class__](node)
+        }[node.__class__](node, **kwargs)
     except TypeError:
         raise CompileError("No translator available for %s." % node.__class__.__name__)
 

File kugelblitz/translator/assignment.py

     def translate_single_assign(self, target, value):
         if isinstance(target, ast.Name):
             return "var %(target)s = %(value)s" % {
-                'target': self.sub_translate(target),
-                'value': self.sub_translate(value),
+                'target': self.sib_translate(target),
+                'value': self.sib_translate(value),
             }
         else:
             return "%(target)s = %(value)s" % {
-                'target': self.sub_translate(target),
-                'value': self.sub_translate(value),
+                'target': self.sib_translate(target),
+                'value': self.sib_translate(value),
             }
 
     def translate(self):

File kugelblitz/translator/base.py

     Base translator class. Instantiated for each node.
     """
     
-    def __init__(self, node):
+    INDENT_STRING = "    "
+    
+    def __init__(self, node, indent_level=0):
         self.node = node
+        self.indent_level = indent_level
     
-    def get_translator(self, node):
+    @property
+    def indent(self):
+        return self.INDENT_STRING * self.indent_level
+    
+    @property
+    def indent_child(self):
+        return self.INDENT_STRING * (self.indent_level + 1)
+    
+    def get_translator(self, node, **kwargs):
         from kugelblitz.translator import get_translator
-        return get_translator(node)
+        return get_translator(node, **kwargs)
     
     def sub_translate(self, node):
-        return self.get_translator(node).translate()
+        """
+        Returns the node, indented the next level down.
+        """
+        return self.get_translator(
+            node,
+            indent_level = self.indent_level + 1,
+        ).translate()
+    
+    def sib_translate(self, node):
+        """
+        Returns the node, indented at the same level
+        """
+        return self.get_translator(
+            node,
+            indent_level = self.indent_level,
+        ).translate()

File kugelblitz/translator/control.py

 class IfTranslator(BodyTranslator):
 
     def translate(self):
-        s = ["if (%(test_def)s) { %(body_def)s }" % {
+        s = ["if (%(test_def)s) {\n%(indent_child)s%(body_def)s\n%(indent)s}" % {
             'test_def': self.sub_translate(self.node.test),
             'body_def': self.translate_body(self.node.body),
+            'indent': self.indent,
+            'indent_child': self.indent_child,
         }]
         if self.node.orelse:
             s.append("else { %(orelse_def)s }" % {

File kugelblitz/translator/toplevel.py

     
     separator = '\n'
     
-    def translate_body(self, body):
+    def translate_body(self, body, sib=False):
+        trans_method = self.sib_translate if sib else self.sub_translate
         s = []
         for node in body:
             if isinstance(node, ast.Pass):
                 continue
-            translator = self.get_translator(node)
             if isinstance(node, ast.If):
-                s.append(translator.translate())
+                s.append(trans_method(node))
             else:
-                s.append('%s;' % translator.translate())
-        return self.separator.join(s)
+                s.append('%s;' % trans_method(node))
+        if sib:
+            return (self.separator + self.indent).join(s)
+        else:
+            return (self.separator + self.indent_child).join(s)
 
 
 class ModuleTranslator(BodyTranslator):
     separator = '\n\n'
     
     def translate(self):
-        return self.translate_body(self.node.body)
+        return self.translate_body(self.node.body, sib=True)
 
 
 class FunctionTranslator(BodyTranslator):
     Translates a function. Includes function name in output.
     """
     
+    def get_body(self):
+        """
+        Returns the body, and a possible docstring.
+        """
+        if self.node.body and isinstance(self.node.body[0], ast.Expr) and isinstance(self.node.body[0].value, ast.Str):
+            docstring = ("\n%s" % self.indent).join([
+                "// %s" % line.strip()
+                for line in self.node.body[0].value.s.strip().split("\n")
+            ])
+            body = self.node.body[1:]
+        else:
+            docstring = None
+            body = self.node.body
+        return docstring, body
+    
     def translate(self):
+        docstring, body = self.get_body()
         args_def = ", ".join([arg.id for arg in self.node.args.args])
-        return "var %(name)s = function (%(args_def)s) { %(body_def)s }" % {
+        context = {
             "args_def": args_def,
-            "body_def": self.translate_body(self.node.body),
+            "body_def": self.translate_body(body),
             "name": self.node.name,
+            "indent": self.indent,
+            "indent_child": self.indent_child,
+            "docstring": docstring,
         }
+        if docstring:
+            return "%(docstring)s\n%(indent)svar %(name)s = function (%(args_def)s) {\n%(indent_child)s%(body_def)s\n%(indent)s}" % context
+        else:
+            return "var %(name)s = function (%(args_def)s) {\n%(body_def)s\n%(indent)s}" % context
 
 
 class LambdaTranslator(BodyTranslator):

File kugelblitz/translator/values.py

             raise CompileError("Invalid value for dict key: %r" % value)
     
     def translate(self):
-        return "{%s}" % ",\n".join([
-            "%s: %s" % (self.str_translate(k), self.sub_translate(v))
-            for k, v in zip(self.node.keys, self.node.values)
-        ])
+        # If it's empty, return on one line
+        if not self.node.keys:
+            return "{}"
+        else:
+            # Otherwise, return nicely indented
+            return "{\n%s%s\n%s}" % (
+                self.indent_child,
+                (",\n%s" % self.indent).join([
+                    "%s: %s" % (self.str_translate(k), self.sub_translate(v))
+                    for k, v in zip(self.node.keys, self.node.values)
+                ]),
+                self.indent,
+            )
 
 class StrTranslator(BaseTranslator):
     def translate(self):