# HG changeset patch # User Paul Boddie # Date 1363043545 -3600 # Node ID a8fbd7fc783f73ac23acfefa77a205543810fff0 # Parent 56765af992d19526bbbb5f4677e57d4046bba778 Tidied up docstring presentation and added spacing after definitions. Added statement node flattening in order to eliminate empty statements within other statements (typically produced by AST manipulation) and to produce cleaner output. diff -r 56765af992d1 -r a8fbd7fc783f compiler/ast.py --- a/compiler/ast.py Sun Mar 03 01:31:58 2013 +0100 +++ b/compiler/ast.py Tue Mar 12 00:12:25 2013 +0100 @@ -7,8 +7,7 @@ def flatten(seq): l = [] for elt in seq: - t = type(elt) - if t is tuple or t is list: + if isinstance(elt, (tuple, list)): for elt2 in flatten(elt): l.append(elt2) else: @@ -18,6 +17,24 @@ def flatten_nodes(seq): return [n for n in flatten(seq) if isinstance(n, Node)] +def flatten_statement(seq): + l = [] + for elt in seq: + if isinstance(elt, Stmt): + l += flatten_statement(elt) + else: + l.append(elt) + return l + +def docstring(s): + if s.find("\n") != -1: + if s.find("'''") != -1: + return '"""%s"""' % s.replace('"""', '\\"\\"\\"') + else: + return "'''%s'''" % s.replace("'''", "\\'\\'\\'") + else: + return repr(s) + def indent(s): return s.replace("\n", "\n\t") @@ -532,11 +549,11 @@ return "Class(%r, %r, %r, %r, %r)" % (self.name, self.bases, self.doc, self.code, self.decorators) def __str__(self): - return "%sclass %s%s:%s%s" % ( + return "%sclass %s%s:%s%s\n" % ( self.decorators and "%s\n" % "\n".join([("@%s" % decorator) for decorator in self.decorators]) or "", self.name, self.bases and "(%s)" % ", ".join(map(str, self.bases)) or "", - indent(self.doc and "\n%r" % self.doc or ""), + indent(self.doc and "\n%s" % docstring(self.doc) or ""), indent("\n%s" % self.code) ) @@ -889,11 +906,11 @@ def __str__(self): parameters = decode_function(self) - return "%sdef %s(%s):%s%s" % ( + return "%sdef %s(%s):%s%s\n" % ( self.decorators and "%s\n" % "\n".join([("@%s" % decorator) for decorator in self.decorators]) or "", self.name, ", ".join(parameters), - indent(self.doc and "\n%r" % self.doc or ""), + indent(self.doc and "\n\n%s\n" % docstring(self.doc) or ""), indent("\n%s" % self.code) ) @@ -1447,7 +1464,7 @@ return "Module(%r, %r)" % (self.doc, self.node) def __str__(self): - return "%s%s" % (self.doc and "%r\n" % self.doc or "", self.node) + return "%s%s" % (self.doc and "%s\n\n" % docstring(self.doc) or "", self.node) def visit(self, visitor, *args): return visitor.visitModule(self, *args) @@ -1833,7 +1850,7 @@ return "Stmt(%r)" % (self.nodes,) def __str__(self): - return "\n".join(map(str, self.nodes)) + return "\n".join(map(str, flatten_statement(self.nodes))) def visit(self, visitor, *args): return visitor.visitStmt(self, *args)