blob: f3a5ffe2d5c13fb37067b05c28cb3988b467ee8e [file] [log] [blame]
Tim Peters400cbc32006-02-28 18:44:41 +00001"Usage: unparse.py <path to source file>"
2import sys
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003import _ast
4import cStringIO
5import os
Tim Peters400cbc32006-02-28 18:44:41 +00006
7class Unparser:
8 """Methods in this class recursively traverse an AST and
9 output source code for the abstract syntax; original formatting
10 is disregarged. """
11
12 def __init__(self, tree, file = sys.stdout):
13 """Unparser(tree, file=sys.stdout) -> None.
14 Print the source for tree to file."""
15 self.f = file
16 self._indent = 0
17 self.dispatch(tree)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +000018 print >>self.f,""
Tim Peters400cbc32006-02-28 18:44:41 +000019 self.f.flush()
20
21 def fill(self, text = ""):
22 "Indent a piece of text, according to the current indentation level"
23 self.f.write("\n"+" "*self._indent + text)
24
25 def write(self, text):
26 "Append a piece of text to the current line."
27 self.f.write(text)
28
29 def enter(self):
30 "Print ':', and increase the indentation."
31 self.write(":")
32 self._indent += 1
33
34 def leave(self):
35 "Decrease the indentation level."
36 self._indent -= 1
37
38 def dispatch(self, tree):
39 "Dispatcher function, dispatching tree type T to method _T."
40 if isinstance(tree, list):
41 for t in tree:
42 self.dispatch(t)
43 return
44 meth = getattr(self, "_"+tree.__class__.__name__)
45 meth(tree)
46
47
48 ############### Unparsing methods ######################
49 # There should be one method per concrete grammar type #
50 # Constructors should be grouped by sum type. Ideally, #
51 # this would follow the order in the grammar, but #
52 # currently doesn't. #
53 ########################################################
54
55 def _Module(self, tree):
56 for stmt in tree.body:
57 self.dispatch(stmt)
58
59 # stmt
60 def _Expr(self, tree):
61 self.fill()
62 self.dispatch(tree.value)
63
64 def _Import(self, t):
65 self.fill("import ")
66 first = True
67 for a in t.names:
68 if first:
69 first = False
70 else:
71 self.write(", ")
72 self.write(a.name)
73 if a.asname:
74 self.write(" as "+a.asname)
75
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076 def _ImportFrom(self, t):
77 self.fill("from ")
78 self.write(t.module)
79 self.write(" import ")
80 for i, a in enumerate(t.names):
81 if i == 0:
82 self.write(", ")
83 self.write(a.name)
84 if a.asname:
85 self.write(" as "+a.asname)
86 # XXX(jpe) what is level for?
87
Tim Peters400cbc32006-02-28 18:44:41 +000088 def _Assign(self, t):
89 self.fill()
90 for target in t.targets:
91 self.dispatch(target)
92 self.write(" = ")
93 self.dispatch(t.value)
94
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +000095 def _AugAssign(self, t):
96 self.fill()
97 self.dispatch(t.target)
98 self.write(" "+self.binop[t.op.__class__.__name__]+"= ")
99 self.dispatch(t.value)
100
101 def _Return(self, t):
102 self.fill("return ")
103 if t.value:
104 self.dispatch(t.value)
105
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000106 def _Pass(self, t):
107 self.fill("pass")
108
109 def _Break(self, t):
110 self.fill("break")
111
112 def _Continue(self, t):
113 self.fill("continue")
114
115 def _Delete(self, t):
116 self.fill("del ")
117 self.dispatch(t.targets)
118
119 def _Assert(self, t):
120 self.fill("assert ")
121 self.dispatch(t.test)
122 if t.msg:
123 self.write(", ")
124 self.dispatch(t.msg)
125
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000126 def _Print(self, t):
127 self.fill("print ")
128 do_comma = False
129 if t.dest:
130 self.write(">>")
131 self.dispatch(t.dest)
132 do_comma = True
133 for e in t.values:
134 if do_comma:self.write(", ")
135 else:do_comma=True
136 self.dispatch(e)
137 if not t.nl:
138 self.write(",")
139
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000140 def _Global(self, t):
141 self.fill("global")
142 for i, n in enumerate(t.names):
143 if i != 0:
144 self.write(",")
145 self.write(" " + n)
146
147 def _Yield(self, t):
148 self.fill("yield")
149 if t.value:
150 self.write(" (")
151 self.dispatch(t.value)
152 self.write(")")
153
154 def _Raise(self, t):
155 self.fill('raise ')
156 if t.type:
157 self.dispatch(t.type)
158 if t.inst:
159 self.write(", ")
160 self.dispatch(t.inst)
161 if t.tback:
162 self.write(", ")
163 self.dispatch(t.tback)
164
165 def _TryExcept(self, t):
166 self.fill("try")
167 self.enter()
168 self.dispatch(t.body)
169 self.leave()
170
171 for ex in t.handlers:
172 self.dispatch(ex)
173 if t.orelse:
174 self.fill("else")
175 self.enter()
176 self.dispatch(t.orelse)
177 self.leave()
178
179 def _TryFinally(self, t):
180 self.fill("try")
181 self.enter()
182 self.dispatch(t.body)
183 self.leave()
184
185 self.fill("finally")
186 self.enter()
187 self.dispatch(t.finalbody)
188 self.leave()
189
190 def _excepthandler(self, t):
191 self.fill("except ")
192 if t.type:
193 self.dispatch(t.type)
194 if t.name:
195 self.write(", ")
196 self.dispatch(t.name)
197 self.enter()
198 self.dispatch(t.body)
199 self.leave()
200
Tim Peters400cbc32006-02-28 18:44:41 +0000201 def _ClassDef(self, t):
202 self.write("\n")
203 self.fill("class "+t.name)
204 if t.bases:
205 self.write("(")
206 for a in t.bases:
207 self.dispatch(a)
208 self.write(", ")
209 self.write(")")
210 self.enter()
211 self.dispatch(t.body)
212 self.leave()
213
214 def _FunctionDef(self, t):
215 self.write("\n")
216 self.fill("def "+t.name + "(")
217 self.dispatch(t.args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218 self.write(")")
Tim Peters400cbc32006-02-28 18:44:41 +0000219 self.enter()
220 self.dispatch(t.body)
221 self.leave()
222
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000223 def _For(self, t):
224 self.fill("for ")
225 self.dispatch(t.target)
226 self.write(" in ")
227 self.dispatch(t.iter)
228 self.enter()
229 self.dispatch(t.body)
230 self.leave()
231 if t.orelse:
232 self.fill("else")
233 self.enter()
234 self.dispatch(t.orelse)
235 self.leave
236
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000237 def _If(self, t):
238 self.fill("if ")
239 self.dispatch(t.test)
240 self.enter()
241 # XXX elif?
242 self.dispatch(t.body)
243 self.leave()
244 if t.orelse:
245 self.fill("else")
246 self.enter()
247 self.dispatch(t.orelse)
248 self.leave()
249
250 def _While(self, t):
251 self.fill("while ")
252 self.dispatch(t.test)
253 self.enter()
254 self.dispatch(t.body)
255 self.leave()
256 if t.orelse:
257 self.fill("else")
258 self.enter()
259 self.dispatch(t.orelse)
260 self.leave
261
262 def _With(self, t):
263 self.fill("with ")
264 self.dispatch(t.context_expr)
265 if t.optional_vars:
266 self.write(" as ")
267 self.dispatch(t.optional_vars)
268 self.enter()
269 self.dispatch(t.body)
270 self.leave()
271
Tim Peters400cbc32006-02-28 18:44:41 +0000272 # expr
273 def _Str(self, tree):
274 self.write(repr(tree.s))
275
276 def _Name(self, t):
277 self.write(t.id)
278
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000279 def _Repr(self, t):
280 self.write("`")
281 self.dispatch(t.value)
282 self.write("`")
283
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000284 def _Num(self, t):
285 self.write(repr(t.n))
286
Tim Peters400cbc32006-02-28 18:44:41 +0000287 def _List(self, t):
288 self.write("[")
289 for e in t.elts:
290 self.dispatch(e)
291 self.write(", ")
292 self.write("]")
293
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000294 def _ListComp(self, t):
295 self.write("[")
296 self.dispatch(t.elt)
297 for gen in t.generators:
298 self.dispatch(gen)
299 self.write("]")
300
301 def _GeneratorExp(self, t):
302 self.write("(")
303 self.dispatch(t.elt)
304 for gen in t.generators:
305 self.dispatch(gen)
306 self.write(")")
307
308 def _comprehension(self, t):
309 self.write(" for ")
310 self.dispatch(t.target)
311 self.write(" in ")
312 self.dispatch(t.iter)
313 for if_clause in t.ifs:
314 self.write(" if ")
315 self.dispatch(if_clause)
316
317 def _IfExp(self, t):
318 self.dispatch(t.body)
319 self.write(" if ")
320 self.dispatch(t.test)
321 if t.orelse:
322 self.write(" else ")
323 self.dispatch(t.orelse)
324
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000325 def _Dict(self, t):
326 self.write("{")
327 for k,v in zip(t.keys, t.values):
328 self.dispatch(k)
329 self.write(" : ")
330 self.dispatch(v)
331 self.write(", ")
332 self.write("}")
333
334 def _Tuple(self, t):
335 if not t.elts:
336 self.write("()")
337 return
338 self.write("(")
339 for e in t.elts:
340 self.dispatch(e)
341 self.write(", ")
342 self.write(")")
343
Tim Peters400cbc32006-02-28 18:44:41 +0000344 unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
345 def _UnaryOp(self, t):
346 self.write(self.unop[t.op.__class__.__name__])
347 self.write("(")
348 self.dispatch(t.operand)
349 self.write(")")
350
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000351 binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000352 "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
353 "FloorDiv":"//", "Pow": "**"}
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000354 def _BinOp(self, t):
355 self.write("(")
356 self.dispatch(t.left)
357 self.write(")" + self.binop[t.op.__class__.__name__] + "(")
358 self.dispatch(t.right)
359 self.write(")")
360
361 cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
362 "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}
363 def _Compare(self, t):
364 self.write("(")
365 self.dispatch(t.left)
366 for o, e in zip(t.ops, t.comparators):
367 self.write(") " +self.cmpops[o.__class__.__name__] + " (")
368 self.dispatch(e)
369 self.write(")")
370
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000371 boolops = {_ast.And: 'and', _ast.Or: 'or'}
372 def _BoolOp(self, t):
373 self.write("(")
374 self.dispatch(t.values[0])
375 for v in t.values[1:]:
376 self.write(" %s " % self.boolops[t.op.__class__])
377 self.dispatch(v)
378 self.write(")")
379
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000380 def _Attribute(self,t):
381 self.dispatch(t.value)
382 self.write(".")
383 self.write(t.attr)
384
385 def _Call(self, t):
386 self.dispatch(t.func)
387 self.write("(")
388 comma = False
389 for e in t.args:
390 if comma: self.write(", ")
391 else: comma = True
392 self.dispatch(e)
393 for e in t.keywords:
394 if comma: self.write(", ")
395 else: comma = True
396 self.dispatch(e)
397 if t.starargs:
398 if comma: self.write(", ")
399 else: comma = True
400 self.write("*")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000401 self.dispatch(t.starargs)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000402 if t.kwargs:
403 if comma: self.write(", ")
404 else: comma = True
405 self.write("**")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406 self.dispatch(t.kwargs)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000407 self.write(")")
408
409 def _Subscript(self, t):
410 self.dispatch(t.value)
411 self.write("[")
412 self.dispatch(t.slice)
413 self.write("]")
414
415 # slice
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000416 def _Ellipsis(self, t):
417 self.write("...")
418
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000419 def _Index(self, t):
420 self.dispatch(t.value)
421
422 def _Slice(self, t):
423 if t.lower:
424 self.dispatch(t.lower)
425 self.write(":")
426 if t.upper:
427 self.dispatch(t.upper)
428 if t.step:
429 self.write(":")
430 self.dispatch(t.step)
431
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 def _ExtSlice(self, t):
433 for i, d in enumerate(t.dims):
434 if i != 0:
435 self.write(': ')
436 self.dispatch(d)
437
Tim Peters400cbc32006-02-28 18:44:41 +0000438 # others
439 def _arguments(self, t):
440 first = True
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000441 nonDef = len(t.args)-len(t.defaults)
442 for a in t.args[0:nonDef]:
Tim Peters400cbc32006-02-28 18:44:41 +0000443 if first:first = False
444 else: self.write(", ")
445 self.dispatch(a)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000446 for a,d in zip(t.args[nonDef:], t.defaults):
447 if first:first = False
448 else: self.write(", ")
449 self.dispatch(a),
450 self.write("=")
451 self.dispatch(d)
Tim Peters400cbc32006-02-28 18:44:41 +0000452 if t.vararg:
453 if first:first = False
454 else: self.write(", ")
455 self.write("*"+t.vararg)
456 if t.kwarg:
457 if first:first = False
458 else: self.write(", ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000459 self.write("**"+t.kwarg)
Tim Peters400cbc32006-02-28 18:44:41 +0000460
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000461 def _keyword(self, t):
462 self.write(t.arg)
463 self.write("=")
464 self.dispatch(t.value)
465
466 def _Lambda(self, t):
467 self.write("lambda ")
468 self.dispatch(t.args)
469 self.write(": ")
470 self.dispatch(t.body)
471
472def roundtrip(filename, output=sys.stdout):
Tim Peters400cbc32006-02-28 18:44:41 +0000473 source = open(filename).read()
474 tree = compile(source, filename, "exec", 0x400)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000475 Unparser(tree, output)
476
477
478
479def testdir(a):
480 try:
481 names = [n for n in os.listdir(a) if n.endswith('.py')]
482 except OSError:
483 print >> sys.stderr, "Directory not readable: %s" % a
484 else:
485 for n in names:
486 fullname = os.path.join(a, n)
487 if os.path.isfile(fullname):
488 output = cStringIO.StringIO()
489 print 'Testing %s' % fullname
490 try:
491 roundtrip(fullname, output)
492 except Exception, e:
493 print ' Failed to compile, exception is %s' % repr(e)
494 elif os.path.isdir(fullname):
495 testdir(fullname)
496
497def main(args):
498 if args[0] == '--testdir':
499 for a in args[1:]:
500 testdir(a)
501 else:
502 for a in args:
503 roundtrip(a)
Tim Peters400cbc32006-02-28 18:44:41 +0000504
505if __name__=='__main__':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000506 main(sys.argv[1:])