blob: c82857710b06e9ca8c875efde842358d234da20b [file] [log] [blame]
Tim Peters400cbc32006-02-28 18:44:41 +00001"Usage: unparse.py <path to source file>"
2import sys
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +00003import ast
Mark Dickinson82c8d932010-06-29 07:48:23 +00004import tokenize
Collin Winter6f2df4d2007-07-17 20:59:35 +00005import io
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006import os
Tim Peters400cbc32006-02-28 18:44:41 +00007
Mark Dickinsoncba8c102010-06-30 11:45:53 +00008# Large float and imaginary literals get turned into infinities in the AST.
9# We unparse those infinities to INFSTR.
10INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
11
Guido van Rossumd8faa362007-04-27 19:54:29 +000012def interleave(inter, f, seq):
13 """Call f on each item in seq, calling inter() in between.
14 """
15 seq = iter(seq)
16 try:
Collin Winter6f2df4d2007-07-17 20:59:35 +000017 f(next(seq))
Guido van Rossumd8faa362007-04-27 19:54:29 +000018 except StopIteration:
19 pass
20 else:
21 for x in seq:
22 inter()
23 f(x)
24
Tim Peters400cbc32006-02-28 18:44:41 +000025class Unparser:
26 """Methods in this class recursively traverse an AST and
27 output source code for the abstract syntax; original formatting
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000028 is disregarded. """
Tim Peters400cbc32006-02-28 18:44:41 +000029
30 def __init__(self, tree, file = sys.stdout):
31 """Unparser(tree, file=sys.stdout) -> None.
32 Print the source for tree to file."""
33 self.f = file
34 self._indent = 0
35 self.dispatch(tree)
Collin Winter6f2df4d2007-07-17 20:59:35 +000036 print("", file=self.f)
Tim Peters400cbc32006-02-28 18:44:41 +000037 self.f.flush()
38
39 def fill(self, text = ""):
40 "Indent a piece of text, according to the current indentation level"
41 self.f.write("\n"+" "*self._indent + text)
42
43 def write(self, text):
44 "Append a piece of text to the current line."
45 self.f.write(text)
46
47 def enter(self):
48 "Print ':', and increase the indentation."
49 self.write(":")
50 self._indent += 1
51
52 def leave(self):
53 "Decrease the indentation level."
54 self._indent -= 1
55
56 def dispatch(self, tree):
57 "Dispatcher function, dispatching tree type T to method _T."
58 if isinstance(tree, list):
59 for t in tree:
60 self.dispatch(t)
61 return
62 meth = getattr(self, "_"+tree.__class__.__name__)
63 meth(tree)
64
65
66 ############### Unparsing methods ######################
67 # There should be one method per concrete grammar type #
68 # Constructors should be grouped by sum type. Ideally, #
69 # this would follow the order in the grammar, but #
70 # currently doesn't. #
71 ########################################################
72
73 def _Module(self, tree):
74 for stmt in tree.body:
75 self.dispatch(stmt)
76
77 # stmt
78 def _Expr(self, tree):
79 self.fill()
80 self.dispatch(tree.value)
81
82 def _Import(self, t):
83 self.fill("import ")
Guido van Rossumd8faa362007-04-27 19:54:29 +000084 interleave(lambda: self.write(", "), self.dispatch, t.names)
Tim Peters400cbc32006-02-28 18:44:41 +000085
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000086 def _ImportFrom(self, t):
87 self.fill("from ")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000088 self.write("." * t.level)
89 if t.module:
90 self.write(t.module)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091 self.write(" import ")
Guido van Rossumd8faa362007-04-27 19:54:29 +000092 interleave(lambda: self.write(", "), self.dispatch, t.names)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093
Tim Peters400cbc32006-02-28 18:44:41 +000094 def _Assign(self, t):
95 self.fill()
96 for target in t.targets:
97 self.dispatch(target)
98 self.write(" = ")
99 self.dispatch(t.value)
100
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000101 def _AugAssign(self, t):
102 self.fill()
103 self.dispatch(t.target)
104 self.write(" "+self.binop[t.op.__class__.__name__]+"= ")
105 self.dispatch(t.value)
106
107 def _Return(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108 self.fill("return")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000109 if t.value:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000110 self.write(" ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000111 self.dispatch(t.value)
112
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000113 def _Pass(self, t):
114 self.fill("pass")
115
116 def _Break(self, t):
117 self.fill("break")
118
119 def _Continue(self, t):
120 self.fill("continue")
121
122 def _Delete(self, t):
123 self.fill("del ")
Mark Dickinsonae100052010-06-28 19:44:20 +0000124 interleave(lambda: self.write(", "), self.dispatch, t.targets)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000125
126 def _Assert(self, t):
127 self.fill("assert ")
128 self.dispatch(t.test)
129 if t.msg:
130 self.write(", ")
131 self.dispatch(t.msg)
132
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000133 def _Global(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134 self.fill("global ")
135 interleave(lambda: self.write(", "), self.write, t.names)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000136
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000137 def _Nonlocal(self, t):
138 self.fill("nonlocal ")
139 interleave(lambda: self.write(", "), self.write, t.names)
140
Yury Selivanov75445082015-05-11 22:57:16 -0400141 def _Await(self, t):
142 self.write("(")
143 self.write("await")
144 if t.value:
145 self.write(" ")
146 self.dispatch(t.value)
147 self.write(")")
148
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000149 def _Yield(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150 self.write("(")
151 self.write("yield")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000152 if t.value:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000153 self.write(" ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000154 self.dispatch(t.value)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000155 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100157 def _YieldFrom(self, t):
158 self.write("(")
159 self.write("yield from")
160 if t.value:
161 self.write(" ")
162 self.dispatch(t.value)
163 self.write(")")
164
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000165 def _Raise(self, t):
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000166 self.fill("raise")
167 if not t.exc:
168 assert not t.cause
169 return
170 self.write(" ")
171 self.dispatch(t.exc)
172 if t.cause:
173 self.write(" from ")
174 self.dispatch(t.cause)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000175
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100176 def _Try(self, t):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000177 self.fill("try")
178 self.enter()
179 self.dispatch(t.body)
180 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000181 for ex in t.handlers:
182 self.dispatch(ex)
183 if t.orelse:
184 self.fill("else")
185 self.enter()
186 self.dispatch(t.orelse)
187 self.leave()
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100188 if t.finalbody:
189 self.fill("finally")
Mark Dickinson81ad8cc2010-06-30 08:46:53 +0000190 self.enter()
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100191 self.dispatch(t.finalbody)
Mark Dickinson81ad8cc2010-06-30 08:46:53 +0000192 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000193
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000194 def _ExceptHandler(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000195 self.fill("except")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000196 if t.type:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000197 self.write(" ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000198 self.dispatch(t.type)
199 if t.name:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000200 self.write(" as ")
201 self.write(t.name)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000202 self.enter()
203 self.dispatch(t.body)
204 self.leave()
205
Tim Peters400cbc32006-02-28 18:44:41 +0000206 def _ClassDef(self, t):
207 self.write("\n")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000208 for deco in t.decorator_list:
209 self.fill("@")
210 self.dispatch(deco)
Tim Peters400cbc32006-02-28 18:44:41 +0000211 self.fill("class "+t.name)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000212 self.write("(")
213 comma = False
214 for e in t.bases:
215 if comma: self.write(", ")
216 else: comma = True
217 self.dispatch(e)
218 for e in t.keywords:
219 if comma: self.write(", ")
220 else: comma = True
221 self.dispatch(e)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000222 self.write(")")
223
Tim Peters400cbc32006-02-28 18:44:41 +0000224 self.enter()
225 self.dispatch(t.body)
226 self.leave()
227
228 def _FunctionDef(self, t):
Yury Selivanov75445082015-05-11 22:57:16 -0400229 self.__FunctionDef_helper(t, "def")
230
231 def _AsyncFunctionDef(self, t):
232 self.__FunctionDef_helper(t, "async def")
233
234 def __FunctionDef_helper(self, t, fill_suffix):
Tim Peters400cbc32006-02-28 18:44:41 +0000235 self.write("\n")
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000236 for deco in t.decorator_list:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000237 self.fill("@")
238 self.dispatch(deco)
Yury Selivanov75445082015-05-11 22:57:16 -0400239 def_str = fill_suffix+" "+t.name + "("
240 self.fill(def_str)
Tim Peters400cbc32006-02-28 18:44:41 +0000241 self.dispatch(t.args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000242 self.write(")")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000243 if t.returns:
244 self.write(" -> ")
245 self.dispatch(t.returns)
Tim Peters400cbc32006-02-28 18:44:41 +0000246 self.enter()
247 self.dispatch(t.body)
248 self.leave()
249
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000250 def _For(self, t):
Yury Selivanov75445082015-05-11 22:57:16 -0400251 self.__For_helper("for ", t)
252
253 def _AsyncFor(self, t):
254 self.__For_helper("async for ", t)
255
256 def __For_helper(self, fill, t):
257 self.fill(fill)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000258 self.dispatch(t.target)
259 self.write(" in ")
260 self.dispatch(t.iter)
261 self.enter()
262 self.dispatch(t.body)
263 self.leave()
264 if t.orelse:
265 self.fill("else")
266 self.enter()
267 self.dispatch(t.orelse)
Mark Dickinsonae100052010-06-28 19:44:20 +0000268 self.leave()
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000269
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000270 def _If(self, t):
271 self.fill("if ")
272 self.dispatch(t.test)
273 self.enter()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000274 self.dispatch(t.body)
275 self.leave()
Mark Dickinson8d6d7602010-06-30 08:32:11 +0000276 # collapse nested ifs into equivalent elifs.
277 while (t.orelse and len(t.orelse) == 1 and
278 isinstance(t.orelse[0], ast.If)):
279 t = t.orelse[0]
280 self.fill("elif ")
281 self.dispatch(t.test)
282 self.enter()
283 self.dispatch(t.body)
284 self.leave()
285 # final else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 if t.orelse:
287 self.fill("else")
288 self.enter()
289 self.dispatch(t.orelse)
290 self.leave()
291
292 def _While(self, t):
293 self.fill("while ")
294 self.dispatch(t.test)
295 self.enter()
296 self.dispatch(t.body)
297 self.leave()
298 if t.orelse:
299 self.fill("else")
300 self.enter()
301 self.dispatch(t.orelse)
Mark Dickinsonae100052010-06-28 19:44:20 +0000302 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000303
304 def _With(self, t):
305 self.fill("with ")
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100306 interleave(lambda: self.write(", "), self.dispatch, t.items)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000307 self.enter()
308 self.dispatch(t.body)
309 self.leave()
310
Yury Selivanov75445082015-05-11 22:57:16 -0400311 def _AsyncWith(self, t):
312 self.fill("async with ")
313 interleave(lambda: self.write(", "), self.dispatch, t.items)
314 self.enter()
315 self.dispatch(t.body)
316 self.leave()
317
Tim Peters400cbc32006-02-28 18:44:41 +0000318 # expr
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000319 def _Bytes(self, t):
320 self.write(repr(t.s))
321
Tim Peters400cbc32006-02-28 18:44:41 +0000322 def _Str(self, tree):
323 self.write(repr(tree.s))
324
325 def _Name(self, t):
326 self.write(t.id)
327
Benjamin Peterson442f2092012-12-06 17:41:04 -0500328 def _NameConstant(self, t):
329 self.write(repr(t.value))
330
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000331 def _Num(self, t):
Mark Dickinsoncba8c102010-06-30 11:45:53 +0000332 # Substitute overflowing decimal literal for AST infinities.
333 self.write(repr(t.n).replace("inf", INFSTR))
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000334
Tim Peters400cbc32006-02-28 18:44:41 +0000335 def _List(self, t):
336 self.write("[")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000337 interleave(lambda: self.write(", "), self.dispatch, t.elts)
Tim Peters400cbc32006-02-28 18:44:41 +0000338 self.write("]")
339
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000340 def _ListComp(self, t):
341 self.write("[")
342 self.dispatch(t.elt)
343 for gen in t.generators:
344 self.dispatch(gen)
345 self.write("]")
346
347 def _GeneratorExp(self, t):
348 self.write("(")
349 self.dispatch(t.elt)
350 for gen in t.generators:
351 self.dispatch(gen)
352 self.write(")")
353
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000354 def _SetComp(self, t):
355 self.write("{")
356 self.dispatch(t.elt)
357 for gen in t.generators:
358 self.dispatch(gen)
359 self.write("}")
360
361 def _DictComp(self, t):
362 self.write("{")
363 self.dispatch(t.key)
364 self.write(": ")
365 self.dispatch(t.value)
366 for gen in t.generators:
367 self.dispatch(gen)
368 self.write("}")
369
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000370 def _comprehension(self, t):
371 self.write(" for ")
372 self.dispatch(t.target)
373 self.write(" in ")
374 self.dispatch(t.iter)
375 for if_clause in t.ifs:
376 self.write(" if ")
377 self.dispatch(if_clause)
378
379 def _IfExp(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000380 self.write("(")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000381 self.dispatch(t.body)
382 self.write(" if ")
383 self.dispatch(t.test)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000384 self.write(" else ")
385 self.dispatch(t.orelse)
386 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000388 def _Set(self, t):
389 assert(t.elts) # should be at least one element
390 self.write("{")
391 interleave(lambda: self.write(", "), self.dispatch, t.elts)
392 self.write("}")
393
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000394 def _Dict(self, t):
395 self.write("{")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000396 def write_pair(pair):
397 (k, v) = pair
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000398 self.dispatch(k)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000399 self.write(": ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000400 self.dispatch(v)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000401 interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values))
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000402 self.write("}")
403
404 def _Tuple(self, t):
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000405 self.write("(")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 if len(t.elts) == 1:
407 (elt,) = t.elts
408 self.dispatch(elt)
409 self.write(",")
410 else:
411 interleave(lambda: self.write(", "), self.dispatch, t.elts)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000412 self.write(")")
413
Tim Peters400cbc32006-02-28 18:44:41 +0000414 unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
415 def _UnaryOp(self, t):
Tim Peters400cbc32006-02-28 18:44:41 +0000416 self.write("(")
Mark Dickinsonae100052010-06-28 19:44:20 +0000417 self.write(self.unop[t.op.__class__.__name__])
418 self.write(" ")
Tim Peters400cbc32006-02-28 18:44:41 +0000419 self.dispatch(t.operand)
420 self.write(")")
421
Benjamin Peterson63c46b22014-04-10 00:17:48 -0400422 binop = { "Add":"+", "Sub":"-", "Mult":"*", "MatMult":"@", "Div":"/", "Mod":"%",
Mark Dickinsonae100052010-06-28 19:44:20 +0000423 "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424 "FloorDiv":"//", "Pow": "**"}
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000425 def _BinOp(self, t):
426 self.write("(")
427 self.dispatch(t.left)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000428 self.write(" " + self.binop[t.op.__class__.__name__] + " ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000429 self.dispatch(t.right)
430 self.write(")")
431
432 cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
433 "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}
434 def _Compare(self, t):
435 self.write("(")
436 self.dispatch(t.left)
437 for o, e in zip(t.ops, t.comparators):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438 self.write(" " + self.cmpops[o.__class__.__name__] + " ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000439 self.dispatch(e)
Mark Dickinsonf5451e52010-06-28 20:09:18 +0000440 self.write(")")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000441
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000442 boolops = {ast.And: 'and', ast.Or: 'or'}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000443 def _BoolOp(self, t):
444 self.write("(")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445 s = " %s " % self.boolops[t.op.__class__]
446 interleave(lambda: self.write(s), self.dispatch, t.values)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000447 self.write(")")
448
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000449 def _Attribute(self,t):
450 self.dispatch(t.value)
Mark Dickinsonb67e15c2010-06-30 09:05:47 +0000451 # Special case: 3.__abs__() is a syntax error, so if t.value
452 # is an integer literal then we need to either parenthesize
453 # it or add an extra space to get 3 .__abs__().
454 if isinstance(t.value, ast.Num) and isinstance(t.value.n, int):
455 self.write(" ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000456 self.write(".")
457 self.write(t.attr)
458
459 def _Call(self, t):
460 self.dispatch(t.func)
461 self.write("(")
462 comma = False
463 for e in t.args:
464 if comma: self.write(", ")
465 else: comma = True
466 self.dispatch(e)
467 for e in t.keywords:
468 if comma: self.write(", ")
469 else: comma = True
470 self.dispatch(e)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000471 self.write(")")
472
473 def _Subscript(self, t):
474 self.dispatch(t.value)
475 self.write("[")
476 self.dispatch(t.slice)
477 self.write("]")
478
Mark Dickinson1b2e9442012-05-06 17:27:39 +0100479 def _Starred(self, t):
480 self.write("*")
481 self.dispatch(t.value)
482
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000483 # slice
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000484 def _Ellipsis(self, t):
485 self.write("...")
486
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000487 def _Index(self, t):
488 self.dispatch(t.value)
489
490 def _Slice(self, t):
491 if t.lower:
492 self.dispatch(t.lower)
493 self.write(":")
494 if t.upper:
495 self.dispatch(t.upper)
496 if t.step:
497 self.write(":")
498 self.dispatch(t.step)
499
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000500 def _ExtSlice(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000501 interleave(lambda: self.write(', '), self.dispatch, t.dims)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000502
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000503 # argument
504 def _arg(self, t):
505 self.write(t.arg)
506 if t.annotation:
507 self.write(": ")
508 self.dispatch(t.annotation)
509
Tim Peters400cbc32006-02-28 18:44:41 +0000510 # others
511 def _arguments(self, t):
512 first = True
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000513 # normal arguments
514 defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults
515 for a, d in zip(t.args, defaults):
Tim Peters400cbc32006-02-28 18:44:41 +0000516 if first:first = False
517 else: self.write(", ")
518 self.dispatch(a)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000519 if d:
520 self.write("=")
521 self.dispatch(d)
522
523 # varargs, or bare '*' if no varargs but keyword-only arguments present
524 if t.vararg or t.kwonlyargs:
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000525 if first:first = False
526 else: self.write(", ")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000527 self.write("*")
528 if t.vararg:
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700529 self.write(t.vararg.arg)
530 if t.vararg.annotation:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000531 self.write(": ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700532 self.dispatch(t.vararg.annotation)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000533
534 # keyword-only arguments
535 if t.kwonlyargs:
536 for a, d in zip(t.kwonlyargs, t.kw_defaults):
537 if first:first = False
538 else: self.write(", ")
539 self.dispatch(a),
540 if d:
541 self.write("=")
542 self.dispatch(d)
543
544 # kwargs
Tim Peters400cbc32006-02-28 18:44:41 +0000545 if t.kwarg:
546 if first:first = False
547 else: self.write(", ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700548 self.write("**"+t.kwarg.arg)
549 if t.kwarg.annotation:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000550 self.write(": ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700551 self.dispatch(t.kwarg.annotation)
Tim Peters400cbc32006-02-28 18:44:41 +0000552
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000553 def _keyword(self, t):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400554 if t.arg is None:
555 self.write("**")
556 else:
557 self.write(t.arg)
558 self.write("=")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000559 self.dispatch(t.value)
560
561 def _Lambda(self, t):
Mark Dickinson8042e282010-06-29 10:01:48 +0000562 self.write("(")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000563 self.write("lambda ")
564 self.dispatch(t.args)
565 self.write(": ")
566 self.dispatch(t.body)
Mark Dickinson8042e282010-06-29 10:01:48 +0000567 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000568
Guido van Rossumd8faa362007-04-27 19:54:29 +0000569 def _alias(self, t):
570 self.write(t.name)
571 if t.asname:
572 self.write(" as "+t.asname)
573
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100574 def _withitem(self, t):
575 self.dispatch(t.context_expr)
576 if t.optional_vars:
577 self.write(" as ")
578 self.dispatch(t.optional_vars)
579
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000580def roundtrip(filename, output=sys.stdout):
Mark Dickinson82c8d932010-06-29 07:48:23 +0000581 with open(filename, "rb") as pyfile:
582 encoding = tokenize.detect_encoding(pyfile.readline)[0]
583 with open(filename, "r", encoding=encoding) as pyfile:
584 source = pyfile.read()
Mark Dickinson3d1bfbf2010-06-28 21:39:51 +0000585 tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000586 Unparser(tree, output)
587
588
589
590def testdir(a):
591 try:
592 names = [n for n in os.listdir(a) if n.endswith('.py')]
593 except OSError:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000594 print("Directory not readable: %s" % a, file=sys.stderr)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000595 else:
596 for n in names:
597 fullname = os.path.join(a, n)
598 if os.path.isfile(fullname):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000599 output = io.StringIO()
600 print('Testing %s' % fullname)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601 try:
602 roundtrip(fullname, output)
Guido van Rossumb940e112007-01-10 16:19:56 +0000603 except Exception as e:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000604 print(' Failed to compile, exception is %s' % repr(e))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000605 elif os.path.isdir(fullname):
606 testdir(fullname)
607
608def main(args):
609 if args[0] == '--testdir':
610 for a in args[1:]:
611 testdir(a)
612 else:
613 for a in args:
614 roundtrip(a)
Tim Peters400cbc32006-02-28 18:44:41 +0000615
616if __name__=='__main__':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000617 main(sys.argv[1:])