+++ /dev/null
-"Usage: unparse.py <path to source file>"\r
-import sys\r
-import ast\r
-import cStringIO\r
-import os\r
-\r
-# Large float and imaginary literals get turned into infinities in the AST.\r
-# We unparse those infinities to INFSTR.\r
-INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)\r
-\r
-def interleave(inter, f, seq):\r
- """Call f on each item in seq, calling inter() in between.\r
- """\r
- seq = iter(seq)\r
- try:\r
- f(next(seq))\r
- except StopIteration:\r
- pass\r
- else:\r
- for x in seq:\r
- inter()\r
- f(x)\r
-\r
-class Unparser:\r
- """Methods in this class recursively traverse an AST and\r
- output source code for the abstract syntax; original formatting\r
- is disregarded. """\r
-\r
- def __init__(self, tree, file = sys.stdout):\r
- """Unparser(tree, file=sys.stdout) -> None.\r
- Print the source for tree to file."""\r
- self.f = file\r
- self.future_imports = []\r
- self._indent = 0\r
- self.dispatch(tree)\r
- self.f.write("")\r
- self.f.flush()\r
-\r
- def fill(self, text = ""):\r
- "Indent a piece of text, according to the current indentation level"\r
- self.f.write("\n"+" "*self._indent + text)\r
-\r
- def write(self, text):\r
- "Append a piece of text to the current line."\r
- self.f.write(text)\r
-\r
- def enter(self):\r
- "Print ':', and increase the indentation."\r
- self.write(":")\r
- self._indent += 1\r
-\r
- def leave(self):\r
- "Decrease the indentation level."\r
- self._indent -= 1\r
-\r
- def dispatch(self, tree):\r
- "Dispatcher function, dispatching tree type T to method _T."\r
- if isinstance(tree, list):\r
- for t in tree:\r
- self.dispatch(t)\r
- return\r
- meth = getattr(self, "_"+tree.__class__.__name__)\r
- meth(tree)\r
-\r
-\r
- ############### Unparsing methods ######################\r
- # There should be one method per concrete grammar type #\r
- # Constructors should be grouped by sum type. Ideally, #\r
- # this would follow the order in the grammar, but #\r
- # currently doesn't. #\r
- ########################################################\r
-\r
- def _Module(self, tree):\r
- for stmt in tree.body:\r
- self.dispatch(stmt)\r
-\r
- # stmt\r
- def _Expr(self, tree):\r
- self.fill()\r
- self.dispatch(tree.value)\r
-\r
- def _Import(self, t):\r
- self.fill("import ")\r
- interleave(lambda: self.write(", "), self.dispatch, t.names)\r
-\r
- def _ImportFrom(self, t):\r
- # A from __future__ import may affect unparsing, so record it.\r
- if t.module and t.module == '__future__':\r
- self.future_imports.extend(n.name for n in t.names)\r
-\r
- self.fill("from ")\r
- self.write("." * t.level)\r
- if t.module:\r
- self.write(t.module)\r
- self.write(" import ")\r
- interleave(lambda: self.write(", "), self.dispatch, t.names)\r
-\r
- def _Assign(self, t):\r
- self.fill()\r
- for target in t.targets:\r
- self.dispatch(target)\r
- self.write(" = ")\r
- self.dispatch(t.value)\r
-\r
- def _AugAssign(self, t):\r
- self.fill()\r
- self.dispatch(t.target)\r
- self.write(" "+self.binop[t.op.__class__.__name__]+"= ")\r
- self.dispatch(t.value)\r
-\r
- def _Return(self, t):\r
- self.fill("return")\r
- if t.value:\r
- self.write(" ")\r
- self.dispatch(t.value)\r
-\r
- def _Pass(self, t):\r
- self.fill("pass")\r
-\r
- def _Break(self, t):\r
- self.fill("break")\r
-\r
- def _Continue(self, t):\r
- self.fill("continue")\r
-\r
- def _Delete(self, t):\r
- self.fill("del ")\r
- interleave(lambda: self.write(", "), self.dispatch, t.targets)\r
-\r
- def _Assert(self, t):\r
- self.fill("assert ")\r
- self.dispatch(t.test)\r
- if t.msg:\r
- self.write(", ")\r
- self.dispatch(t.msg)\r
-\r
- def _Exec(self, t):\r
- self.fill("exec ")\r
- self.dispatch(t.body)\r
- if t.globals:\r
- self.write(" in ")\r
- self.dispatch(t.globals)\r
- if t.locals:\r
- self.write(", ")\r
- self.dispatch(t.locals)\r
-\r
- def _Print(self, t):\r
- self.fill("print ")\r
- do_comma = False\r
- if t.dest:\r
- self.write(">>")\r
- self.dispatch(t.dest)\r
- do_comma = True\r
- for e in t.values:\r
- if do_comma:self.write(", ")\r
- else:do_comma=True\r
- self.dispatch(e)\r
- if not t.nl:\r
- self.write(",")\r
-\r
- def _Global(self, t):\r
- self.fill("global ")\r
- interleave(lambda: self.write(", "), self.write, t.names)\r
-\r
- def _Yield(self, t):\r
- self.write("(")\r
- self.write("yield")\r
- if t.value:\r
- self.write(" ")\r
- self.dispatch(t.value)\r
- self.write(")")\r
-\r
- def _Raise(self, t):\r
- self.fill('raise ')\r
- if t.type:\r
- self.dispatch(t.type)\r
- if t.inst:\r
- self.write(", ")\r
- self.dispatch(t.inst)\r
- if t.tback:\r
- self.write(", ")\r
- self.dispatch(t.tback)\r
-\r
- def _TryExcept(self, t):\r
- self.fill("try")\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
-\r
- for ex in t.handlers:\r
- self.dispatch(ex)\r
- if t.orelse:\r
- self.fill("else")\r
- self.enter()\r
- self.dispatch(t.orelse)\r
- self.leave()\r
-\r
- def _TryFinally(self, t):\r
- if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept):\r
- # try-except-finally\r
- self.dispatch(t.body)\r
- else:\r
- self.fill("try")\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
-\r
- self.fill("finally")\r
- self.enter()\r
- self.dispatch(t.finalbody)\r
- self.leave()\r
-\r
- def _ExceptHandler(self, t):\r
- self.fill("except")\r
- if t.type:\r
- self.write(" ")\r
- self.dispatch(t.type)\r
- if t.name:\r
- self.write(" as ")\r
- self.dispatch(t.name)\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
-\r
- def _ClassDef(self, t):\r
- self.write("\n")\r
- for deco in t.decorator_list:\r
- self.fill("@")\r
- self.dispatch(deco)\r
- self.fill("class "+t.name)\r
- if t.bases:\r
- self.write("(")\r
- for a in t.bases:\r
- self.dispatch(a)\r
- self.write(", ")\r
- self.write(")")\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
-\r
- def _FunctionDef(self, t):\r
- self.write("\n")\r
- for deco in t.decorator_list:\r
- self.fill("@")\r
- self.dispatch(deco)\r
- self.fill("def "+t.name + "(")\r
- self.dispatch(t.args)\r
- self.write(")")\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
-\r
- def _For(self, t):\r
- self.fill("for ")\r
- self.dispatch(t.target)\r
- self.write(" in ")\r
- self.dispatch(t.iter)\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
- if t.orelse:\r
- self.fill("else")\r
- self.enter()\r
- self.dispatch(t.orelse)\r
- self.leave()\r
-\r
- def _If(self, t):\r
- self.fill("if ")\r
- self.dispatch(t.test)\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
- # collapse nested ifs into equivalent elifs.\r
- while (t.orelse and len(t.orelse) == 1 and\r
- isinstance(t.orelse[0], ast.If)):\r
- t = t.orelse[0]\r
- self.fill("elif ")\r
- self.dispatch(t.test)\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
- # final else\r
- if t.orelse:\r
- self.fill("else")\r
- self.enter()\r
- self.dispatch(t.orelse)\r
- self.leave()\r
-\r
- def _While(self, t):\r
- self.fill("while ")\r
- self.dispatch(t.test)\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
- if t.orelse:\r
- self.fill("else")\r
- self.enter()\r
- self.dispatch(t.orelse)\r
- self.leave()\r
-\r
- def _With(self, t):\r
- self.fill("with ")\r
- self.dispatch(t.context_expr)\r
- if t.optional_vars:\r
- self.write(" as ")\r
- self.dispatch(t.optional_vars)\r
- self.enter()\r
- self.dispatch(t.body)\r
- self.leave()\r
-\r
- # expr\r
- def _Str(self, tree):\r
- # if from __future__ import unicode_literals is in effect,\r
- # then we want to output string literals using a 'b' prefix\r
- # and unicode literals with no prefix.\r
- if "unicode_literals" not in self.future_imports:\r
- self.write(repr(tree.s))\r
- elif isinstance(tree.s, str):\r
- self.write("b" + repr(tree.s))\r
- elif isinstance(tree.s, unicode):\r
- self.write(repr(tree.s).lstrip("u"))\r
- else:\r
- assert False, "shouldn't get here"\r
-\r
- def _Name(self, t):\r
- self.write(t.id)\r
-\r
- def _Repr(self, t):\r
- self.write("`")\r
- self.dispatch(t.value)\r
- self.write("`")\r
-\r
- def _Num(self, t):\r
- repr_n = repr(t.n)\r
- # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2.\r
- if repr_n.startswith("-"):\r
- self.write("(")\r
- # Substitute overflowing decimal literal for AST infinities.\r
- self.write(repr_n.replace("inf", INFSTR))\r
- if repr_n.startswith("-"):\r
- self.write(")")\r
-\r
- def _List(self, t):\r
- self.write("[")\r
- interleave(lambda: self.write(", "), self.dispatch, t.elts)\r
- self.write("]")\r
-\r
- def _ListComp(self, t):\r
- self.write("[")\r
- self.dispatch(t.elt)\r
- for gen in t.generators:\r
- self.dispatch(gen)\r
- self.write("]")\r
-\r
- def _GeneratorExp(self, t):\r
- self.write("(")\r
- self.dispatch(t.elt)\r
- for gen in t.generators:\r
- self.dispatch(gen)\r
- self.write(")")\r
-\r
- def _SetComp(self, t):\r
- self.write("{")\r
- self.dispatch(t.elt)\r
- for gen in t.generators:\r
- self.dispatch(gen)\r
- self.write("}")\r
-\r
- def _DictComp(self, t):\r
- self.write("{")\r
- self.dispatch(t.key)\r
- self.write(": ")\r
- self.dispatch(t.value)\r
- for gen in t.generators:\r
- self.dispatch(gen)\r
- self.write("}")\r
-\r
- def _comprehension(self, t):\r
- self.write(" for ")\r
- self.dispatch(t.target)\r
- self.write(" in ")\r
- self.dispatch(t.iter)\r
- for if_clause in t.ifs:\r
- self.write(" if ")\r
- self.dispatch(if_clause)\r
-\r
- def _IfExp(self, t):\r
- self.write("(")\r
- self.dispatch(t.body)\r
- self.write(" if ")\r
- self.dispatch(t.test)\r
- self.write(" else ")\r
- self.dispatch(t.orelse)\r
- self.write(")")\r
-\r
- def _Set(self, t):\r
- assert(t.elts) # should be at least one element\r
- self.write("{")\r
- interleave(lambda: self.write(", "), self.dispatch, t.elts)\r
- self.write("}")\r
-\r
- def _Dict(self, t):\r
- self.write("{")\r
- def write_pair(pair):\r
- (k, v) = pair\r
- self.dispatch(k)\r
- self.write(": ")\r
- self.dispatch(v)\r
- interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values))\r
- self.write("}")\r
-\r
- def _Tuple(self, t):\r
- self.write("(")\r
- if len(t.elts) == 1:\r
- (elt,) = t.elts\r
- self.dispatch(elt)\r
- self.write(",")\r
- else:\r
- interleave(lambda: self.write(", "), self.dispatch, t.elts)\r
- self.write(")")\r
-\r
- unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}\r
- def _UnaryOp(self, t):\r
- self.write("(")\r
- self.write(self.unop[t.op.__class__.__name__])\r
- self.write(" ")\r
- # If we're applying unary minus to a number, parenthesize the number.\r
- # This is necessary: -2147483648 is different from -(2147483648) on\r
- # a 32-bit machine (the first is an int, the second a long), and\r
- # -7j is different from -(7j). (The first has real part 0.0, the second\r
- # has real part -0.0.)\r
- if isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num):\r
- self.write("(")\r
- self.dispatch(t.operand)\r
- self.write(")")\r
- else:\r
- self.dispatch(t.operand)\r
- self.write(")")\r
-\r
- binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",\r
- "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",\r
- "FloorDiv":"//", "Pow": "**"}\r
- def _BinOp(self, t):\r
- self.write("(")\r
- self.dispatch(t.left)\r
- self.write(" " + self.binop[t.op.__class__.__name__] + " ")\r
- self.dispatch(t.right)\r
- self.write(")")\r
-\r
- cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",\r
- "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}\r
- def _Compare(self, t):\r
- self.write("(")\r
- self.dispatch(t.left)\r
- for o, e in zip(t.ops, t.comparators):\r
- self.write(" " + self.cmpops[o.__class__.__name__] + " ")\r
- self.dispatch(e)\r
- self.write(")")\r
-\r
- boolops = {ast.And: 'and', ast.Or: 'or'}\r
- def _BoolOp(self, t):\r
- self.write("(")\r
- s = " %s " % self.boolops[t.op.__class__]\r
- interleave(lambda: self.write(s), self.dispatch, t.values)\r
- self.write(")")\r
-\r
- def _Attribute(self,t):\r
- self.dispatch(t.value)\r
- # Special case: 3.__abs__() is a syntax error, so if t.value\r
- # is an integer literal then we need to either parenthesize\r
- # it or add an extra space to get 3 .__abs__().\r
- if isinstance(t.value, ast.Num) and isinstance(t.value.n, int):\r
- self.write(" ")\r
- self.write(".")\r
- self.write(t.attr)\r
-\r
- def _Call(self, t):\r
- self.dispatch(t.func)\r
- self.write("(")\r
- comma = False\r
- for e in t.args:\r
- if comma: self.write(", ")\r
- else: comma = True\r
- self.dispatch(e)\r
- for e in t.keywords:\r
- if comma: self.write(", ")\r
- else: comma = True\r
- self.dispatch(e)\r
- if t.starargs:\r
- if comma: self.write(", ")\r
- else: comma = True\r
- self.write("*")\r
- self.dispatch(t.starargs)\r
- if t.kwargs:\r
- if comma: self.write(", ")\r
- else: comma = True\r
- self.write("**")\r
- self.dispatch(t.kwargs)\r
- self.write(")")\r
-\r
- def _Subscript(self, t):\r
- self.dispatch(t.value)\r
- self.write("[")\r
- self.dispatch(t.slice)\r
- self.write("]")\r
-\r
- # slice\r
- def _Ellipsis(self, t):\r
- self.write("...")\r
-\r
- def _Index(self, t):\r
- self.dispatch(t.value)\r
-\r
- def _Slice(self, t):\r
- if t.lower:\r
- self.dispatch(t.lower)\r
- self.write(":")\r
- if t.upper:\r
- self.dispatch(t.upper)\r
- if t.step:\r
- self.write(":")\r
- self.dispatch(t.step)\r
-\r
- def _ExtSlice(self, t):\r
- interleave(lambda: self.write(', '), self.dispatch, t.dims)\r
-\r
- # others\r
- def _arguments(self, t):\r
- first = True\r
- # normal arguments\r
- defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults\r
- for a,d in zip(t.args, defaults):\r
- if first:first = False\r
- else: self.write(", ")\r
- self.dispatch(a),\r
- if d:\r
- self.write("=")\r
- self.dispatch(d)\r
-\r
- # varargs\r
- if t.vararg:\r
- if first:first = False\r
- else: self.write(", ")\r
- self.write("*")\r
- self.write(t.vararg)\r
-\r
- # kwargs\r
- if t.kwarg:\r
- if first:first = False\r
- else: self.write(", ")\r
- self.write("**"+t.kwarg)\r
-\r
- def _keyword(self, t):\r
- self.write(t.arg)\r
- self.write("=")\r
- self.dispatch(t.value)\r
-\r
- def _Lambda(self, t):\r
- self.write("(")\r
- self.write("lambda ")\r
- self.dispatch(t.args)\r
- self.write(": ")\r
- self.dispatch(t.body)\r
- self.write(")")\r
-\r
- def _alias(self, t):\r
- self.write(t.name)\r
- if t.asname:\r
- self.write(" as "+t.asname)\r
-\r
-def roundtrip(filename, output=sys.stdout):\r
- with open(filename, "r") as pyfile:\r
- source = pyfile.read()\r
- tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST)\r
- Unparser(tree, output)\r
-\r
-\r
-\r
-def testdir(a):\r
- try:\r
- names = [n for n in os.listdir(a) if n.endswith('.py')]\r
- except OSError:\r
- sys.stderr.write("Directory not readable: %s" % a)\r
- else:\r
- for n in names:\r
- fullname = os.path.join(a, n)\r
- if os.path.isfile(fullname):\r
- output = cStringIO.StringIO()\r
- print 'Testing %s' % fullname\r
- try:\r
- roundtrip(fullname, output)\r
- except Exception as e:\r
- print ' Failed to compile, exception is %s' % repr(e)\r
- elif os.path.isdir(fullname):\r
- testdir(fullname)\r
-\r
-def main(args):\r
- if args[0] == '--testdir':\r
- for a in args[1:]:\r
- testdir(a)\r
- else:\r
- for a in args:\r
- roundtrip(a)\r
-\r
-if __name__=='__main__':\r
- main(sys.argv[1:])\r