blob: 82c3c776807283abfb7f1fd4bce790ba6bdb5f16 [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
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700107 def _AnnAssign(self, t):
108 self.fill()
109 if not t.simple and isinstance(t.target, ast.Name):
110 self.write('(')
111 self.dispatch(t.target)
112 if not t.simple and isinstance(t.target, ast.Name):
113 self.write(')')
114 self.write(": ")
115 self.dispatch(t.annotation)
116 if t.value:
117 self.write(" = ")
118 self.dispatch(t.value)
119
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000120 def _Return(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000121 self.fill("return")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000122 if t.value:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123 self.write(" ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000124 self.dispatch(t.value)
125
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000126 def _Pass(self, t):
127 self.fill("pass")
128
129 def _Break(self, t):
130 self.fill("break")
131
132 def _Continue(self, t):
133 self.fill("continue")
134
135 def _Delete(self, t):
136 self.fill("del ")
Mark Dickinsonae100052010-06-28 19:44:20 +0000137 interleave(lambda: self.write(", "), self.dispatch, t.targets)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000138
139 def _Assert(self, t):
140 self.fill("assert ")
141 self.dispatch(t.test)
142 if t.msg:
143 self.write(", ")
144 self.dispatch(t.msg)
145
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000146 def _Global(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147 self.fill("global ")
148 interleave(lambda: self.write(", "), self.write, t.names)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000149
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000150 def _Nonlocal(self, t):
151 self.fill("nonlocal ")
152 interleave(lambda: self.write(", "), self.write, t.names)
153
Yury Selivanov75445082015-05-11 22:57:16 -0400154 def _Await(self, t):
155 self.write("(")
156 self.write("await")
157 if t.value:
158 self.write(" ")
159 self.dispatch(t.value)
160 self.write(")")
161
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000162 def _Yield(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000163 self.write("(")
164 self.write("yield")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000165 if t.value:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166 self.write(" ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000167 self.dispatch(t.value)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000168 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000169
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100170 def _YieldFrom(self, t):
171 self.write("(")
172 self.write("yield from")
173 if t.value:
174 self.write(" ")
175 self.dispatch(t.value)
176 self.write(")")
177
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000178 def _Raise(self, t):
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000179 self.fill("raise")
180 if not t.exc:
181 assert not t.cause
182 return
183 self.write(" ")
184 self.dispatch(t.exc)
185 if t.cause:
186 self.write(" from ")
187 self.dispatch(t.cause)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000188
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100189 def _Try(self, t):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000190 self.fill("try")
191 self.enter()
192 self.dispatch(t.body)
193 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000194 for ex in t.handlers:
195 self.dispatch(ex)
196 if t.orelse:
197 self.fill("else")
198 self.enter()
199 self.dispatch(t.orelse)
200 self.leave()
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100201 if t.finalbody:
202 self.fill("finally")
Mark Dickinson81ad8cc2010-06-30 08:46:53 +0000203 self.enter()
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100204 self.dispatch(t.finalbody)
Mark Dickinson81ad8cc2010-06-30 08:46:53 +0000205 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000206
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000207 def _ExceptHandler(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 self.fill("except")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000209 if t.type:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 self.write(" ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211 self.dispatch(t.type)
212 if t.name:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000213 self.write(" as ")
214 self.write(t.name)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000215 self.enter()
216 self.dispatch(t.body)
217 self.leave()
218
Tim Peters400cbc32006-02-28 18:44:41 +0000219 def _ClassDef(self, t):
220 self.write("\n")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000221 for deco in t.decorator_list:
222 self.fill("@")
223 self.dispatch(deco)
Tim Peters400cbc32006-02-28 18:44:41 +0000224 self.fill("class "+t.name)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000225 self.write("(")
226 comma = False
227 for e in t.bases:
228 if comma: self.write(", ")
229 else: comma = True
230 self.dispatch(e)
231 for e in t.keywords:
232 if comma: self.write(", ")
233 else: comma = True
234 self.dispatch(e)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000235 self.write(")")
236
Tim Peters400cbc32006-02-28 18:44:41 +0000237 self.enter()
238 self.dispatch(t.body)
239 self.leave()
240
241 def _FunctionDef(self, t):
Yury Selivanov75445082015-05-11 22:57:16 -0400242 self.__FunctionDef_helper(t, "def")
243
244 def _AsyncFunctionDef(self, t):
245 self.__FunctionDef_helper(t, "async def")
246
247 def __FunctionDef_helper(self, t, fill_suffix):
Tim Peters400cbc32006-02-28 18:44:41 +0000248 self.write("\n")
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000249 for deco in t.decorator_list:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000250 self.fill("@")
251 self.dispatch(deco)
Yury Selivanov75445082015-05-11 22:57:16 -0400252 def_str = fill_suffix+" "+t.name + "("
253 self.fill(def_str)
Tim Peters400cbc32006-02-28 18:44:41 +0000254 self.dispatch(t.args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000255 self.write(")")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000256 if t.returns:
257 self.write(" -> ")
258 self.dispatch(t.returns)
Tim Peters400cbc32006-02-28 18:44:41 +0000259 self.enter()
260 self.dispatch(t.body)
261 self.leave()
262
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000263 def _For(self, t):
Yury Selivanov75445082015-05-11 22:57:16 -0400264 self.__For_helper("for ", t)
265
266 def _AsyncFor(self, t):
267 self.__For_helper("async for ", t)
268
269 def __For_helper(self, fill, t):
270 self.fill(fill)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000271 self.dispatch(t.target)
272 self.write(" in ")
273 self.dispatch(t.iter)
274 self.enter()
275 self.dispatch(t.body)
276 self.leave()
277 if t.orelse:
278 self.fill("else")
279 self.enter()
280 self.dispatch(t.orelse)
Mark Dickinsonae100052010-06-28 19:44:20 +0000281 self.leave()
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000282
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000283 def _If(self, t):
284 self.fill("if ")
285 self.dispatch(t.test)
286 self.enter()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000287 self.dispatch(t.body)
288 self.leave()
Mark Dickinson8d6d7602010-06-30 08:32:11 +0000289 # collapse nested ifs into equivalent elifs.
290 while (t.orelse and len(t.orelse) == 1 and
291 isinstance(t.orelse[0], ast.If)):
292 t = t.orelse[0]
293 self.fill("elif ")
294 self.dispatch(t.test)
295 self.enter()
296 self.dispatch(t.body)
297 self.leave()
298 # final else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000299 if t.orelse:
300 self.fill("else")
301 self.enter()
302 self.dispatch(t.orelse)
303 self.leave()
304
305 def _While(self, t):
306 self.fill("while ")
307 self.dispatch(t.test)
308 self.enter()
309 self.dispatch(t.body)
310 self.leave()
311 if t.orelse:
312 self.fill("else")
313 self.enter()
314 self.dispatch(t.orelse)
Mark Dickinsonae100052010-06-28 19:44:20 +0000315 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000316
317 def _With(self, t):
318 self.fill("with ")
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100319 interleave(lambda: self.write(", "), self.dispatch, t.items)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320 self.enter()
321 self.dispatch(t.body)
322 self.leave()
323
Yury Selivanov75445082015-05-11 22:57:16 -0400324 def _AsyncWith(self, t):
325 self.fill("async with ")
326 interleave(lambda: self.write(", "), self.dispatch, t.items)
327 self.enter()
328 self.dispatch(t.body)
329 self.leave()
330
Tim Peters400cbc32006-02-28 18:44:41 +0000331 # expr
Eric V. Smith608adf92015-09-20 15:09:15 -0400332 def _JoinedStr(self, t):
333 self.write("f")
334 string = io.StringIO()
335 self._fstring_JoinedStr(t, string.write)
336 self.write(repr(string.getvalue()))
337
338 def _FormattedValue(self, t):
339 self.write("f")
340 string = io.StringIO()
341 self._fstring_FormattedValue(t, string.write)
342 self.write(repr(string.getvalue()))
343
344 def _fstring_JoinedStr(self, t, write):
345 for value in t.values:
346 meth = getattr(self, "_fstring_" + type(value).__name__)
347 meth(value, write)
348
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100349 def _fstring_Constant(self, t, write):
350 assert isinstance(t.value, str)
351 value = t.value.replace("{", "{{").replace("}", "}}")
352 write(value)
353
Eric V. Smith608adf92015-09-20 15:09:15 -0400354 def _fstring_FormattedValue(self, t, write):
355 write("{")
356 expr = io.StringIO()
357 Unparser(t.value, expr)
358 expr = expr.getvalue().rstrip("\n")
359 if expr.startswith("{"):
360 write(" ") # Separate pair of opening brackets as "{ {"
361 write(expr)
362 if t.conversion != -1:
363 conversion = chr(t.conversion)
364 assert conversion in "sra"
365 write(f"!{conversion}")
366 if t.format_spec:
367 write(":")
368 meth = getattr(self, "_fstring_" + type(t.format_spec).__name__)
369 meth(t.format_spec, write)
370 write("}")
371
Tim Peters400cbc32006-02-28 18:44:41 +0000372 def _Name(self, t):
373 self.write(t.id)
374
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100375 def _write_constant(self, value):
376 if isinstance(value, (float, complex)):
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300377 # Substitute overflowing decimal literal for AST infinities.
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100378 self.write(repr(value).replace("inf", INFSTR))
379 else:
380 self.write(repr(value))
381
382 def _Constant(self, t):
383 value = t.value
384 if isinstance(value, tuple):
385 self.write("(")
386 if len(value) == 1:
387 self._write_constant(value[0])
388 self.write(",")
389 else:
390 interleave(lambda: self.write(", "), self._write_constant, value)
391 self.write(")")
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300392 elif value is ...:
393 self.write("...")
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100394 else:
395 self._write_constant(t.value)
396
Tim Peters400cbc32006-02-28 18:44:41 +0000397 def _List(self, t):
398 self.write("[")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000399 interleave(lambda: self.write(", "), self.dispatch, t.elts)
Tim Peters400cbc32006-02-28 18:44:41 +0000400 self.write("]")
401
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000402 def _ListComp(self, t):
403 self.write("[")
404 self.dispatch(t.elt)
405 for gen in t.generators:
406 self.dispatch(gen)
407 self.write("]")
408
409 def _GeneratorExp(self, t):
410 self.write("(")
411 self.dispatch(t.elt)
412 for gen in t.generators:
413 self.dispatch(gen)
414 self.write(")")
415
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000416 def _SetComp(self, t):
417 self.write("{")
418 self.dispatch(t.elt)
419 for gen in t.generators:
420 self.dispatch(gen)
421 self.write("}")
422
423 def _DictComp(self, t):
424 self.write("{")
425 self.dispatch(t.key)
426 self.write(": ")
427 self.dispatch(t.value)
428 for gen in t.generators:
429 self.dispatch(gen)
430 self.write("}")
431
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432 def _comprehension(self, t):
Yury Selivanovbf04b062016-09-09 11:48:39 -0700433 if t.is_async:
434 self.write(" async for ")
435 else:
436 self.write(" for ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000437 self.dispatch(t.target)
438 self.write(" in ")
439 self.dispatch(t.iter)
440 for if_clause in t.ifs:
441 self.write(" if ")
442 self.dispatch(if_clause)
443
444 def _IfExp(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445 self.write("(")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446 self.dispatch(t.body)
447 self.write(" if ")
448 self.dispatch(t.test)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000449 self.write(" else ")
450 self.dispatch(t.orelse)
451 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000452
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000453 def _Set(self, t):
454 assert(t.elts) # should be at least one element
455 self.write("{")
456 interleave(lambda: self.write(", "), self.dispatch, t.elts)
457 self.write("}")
458
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000459 def _Dict(self, t):
460 self.write("{")
Berker Peksagd66dd5c2016-03-06 16:50:15 +0200461 def write_key_value_pair(k, v):
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000462 self.dispatch(k)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000463 self.write(": ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000464 self.dispatch(v)
Berker Peksagd66dd5c2016-03-06 16:50:15 +0200465
466 def write_item(item):
467 k, v = item
468 if k is None:
469 # for dictionary unpacking operator in dicts {**{'y': 2}}
470 # see PEP 448 for details
471 self.write("**")
472 self.dispatch(v)
473 else:
474 write_key_value_pair(k, v)
475 interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values))
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000476 self.write("}")
477
478 def _Tuple(self, t):
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000479 self.write("(")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480 if len(t.elts) == 1:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100481 elt = t.elts[0]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000482 self.dispatch(elt)
483 self.write(",")
484 else:
485 interleave(lambda: self.write(", "), self.dispatch, t.elts)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000486 self.write(")")
487
Tim Peters400cbc32006-02-28 18:44:41 +0000488 unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
489 def _UnaryOp(self, t):
Tim Peters400cbc32006-02-28 18:44:41 +0000490 self.write("(")
Mark Dickinsonae100052010-06-28 19:44:20 +0000491 self.write(self.unop[t.op.__class__.__name__])
492 self.write(" ")
Tim Peters400cbc32006-02-28 18:44:41 +0000493 self.dispatch(t.operand)
494 self.write(")")
495
Benjamin Peterson63c46b22014-04-10 00:17:48 -0400496 binop = { "Add":"+", "Sub":"-", "Mult":"*", "MatMult":"@", "Div":"/", "Mod":"%",
Mark Dickinsonae100052010-06-28 19:44:20 +0000497 "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000498 "FloorDiv":"//", "Pow": "**"}
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000499 def _BinOp(self, t):
500 self.write("(")
501 self.dispatch(t.left)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000502 self.write(" " + self.binop[t.op.__class__.__name__] + " ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000503 self.dispatch(t.right)
504 self.write(")")
505
506 cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
507 "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}
508 def _Compare(self, t):
509 self.write("(")
510 self.dispatch(t.left)
511 for o, e in zip(t.ops, t.comparators):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000512 self.write(" " + self.cmpops[o.__class__.__name__] + " ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000513 self.dispatch(e)
Mark Dickinsonf5451e52010-06-28 20:09:18 +0000514 self.write(")")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000515
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000516 boolops = {ast.And: 'and', ast.Or: 'or'}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000517 def _BoolOp(self, t):
518 self.write("(")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 s = " %s " % self.boolops[t.op.__class__]
520 interleave(lambda: self.write(s), self.dispatch, t.values)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000521 self.write(")")
522
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000523 def _Attribute(self,t):
524 self.dispatch(t.value)
Mark Dickinsonb67e15c2010-06-30 09:05:47 +0000525 # Special case: 3.__abs__() is a syntax error, so if t.value
526 # is an integer literal then we need to either parenthesize
527 # it or add an extra space to get 3 .__abs__().
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300528 if isinstance(t.value, ast.Constant) and isinstance(t.value.value, int):
Mark Dickinsonb67e15c2010-06-30 09:05:47 +0000529 self.write(" ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000530 self.write(".")
531 self.write(t.attr)
532
533 def _Call(self, t):
534 self.dispatch(t.func)
535 self.write("(")
536 comma = False
537 for e in t.args:
538 if comma: self.write(", ")
539 else: comma = True
540 self.dispatch(e)
541 for e in t.keywords:
542 if comma: self.write(", ")
543 else: comma = True
544 self.dispatch(e)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000545 self.write(")")
546
547 def _Subscript(self, t):
548 self.dispatch(t.value)
549 self.write("[")
550 self.dispatch(t.slice)
551 self.write("]")
552
Mark Dickinson1b2e9442012-05-06 17:27:39 +0100553 def _Starred(self, t):
554 self.write("*")
555 self.dispatch(t.value)
556
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000557 # slice
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000558 def _Ellipsis(self, t):
559 self.write("...")
560
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000561 def _Index(self, t):
562 self.dispatch(t.value)
563
564 def _Slice(self, t):
565 if t.lower:
566 self.dispatch(t.lower)
567 self.write(":")
568 if t.upper:
569 self.dispatch(t.upper)
570 if t.step:
571 self.write(":")
572 self.dispatch(t.step)
573
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000574 def _ExtSlice(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000575 interleave(lambda: self.write(', '), self.dispatch, t.dims)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000576
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000577 # argument
578 def _arg(self, t):
579 self.write(t.arg)
580 if t.annotation:
581 self.write(": ")
582 self.dispatch(t.annotation)
583
Tim Peters400cbc32006-02-28 18:44:41 +0000584 # others
585 def _arguments(self, t):
586 first = True
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000587 # normal arguments
588 defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults
589 for a, d in zip(t.args, defaults):
Tim Peters400cbc32006-02-28 18:44:41 +0000590 if first:first = False
591 else: self.write(", ")
592 self.dispatch(a)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000593 if d:
594 self.write("=")
595 self.dispatch(d)
596
597 # varargs, or bare '*' if no varargs but keyword-only arguments present
598 if t.vararg or t.kwonlyargs:
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000599 if first:first = False
600 else: self.write(", ")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000601 self.write("*")
602 if t.vararg:
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700603 self.write(t.vararg.arg)
604 if t.vararg.annotation:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000605 self.write(": ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700606 self.dispatch(t.vararg.annotation)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000607
608 # keyword-only arguments
609 if t.kwonlyargs:
610 for a, d in zip(t.kwonlyargs, t.kw_defaults):
611 if first:first = False
612 else: self.write(", ")
613 self.dispatch(a),
614 if d:
615 self.write("=")
616 self.dispatch(d)
617
618 # kwargs
Tim Peters400cbc32006-02-28 18:44:41 +0000619 if t.kwarg:
620 if first:first = False
621 else: self.write(", ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700622 self.write("**"+t.kwarg.arg)
623 if t.kwarg.annotation:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000624 self.write(": ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700625 self.dispatch(t.kwarg.annotation)
Tim Peters400cbc32006-02-28 18:44:41 +0000626
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627 def _keyword(self, t):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400628 if t.arg is None:
629 self.write("**")
630 else:
631 self.write(t.arg)
632 self.write("=")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000633 self.dispatch(t.value)
634
635 def _Lambda(self, t):
Mark Dickinson8042e282010-06-29 10:01:48 +0000636 self.write("(")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000637 self.write("lambda ")
638 self.dispatch(t.args)
639 self.write(": ")
640 self.dispatch(t.body)
Mark Dickinson8042e282010-06-29 10:01:48 +0000641 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642
Guido van Rossumd8faa362007-04-27 19:54:29 +0000643 def _alias(self, t):
644 self.write(t.name)
645 if t.asname:
646 self.write(" as "+t.asname)
647
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100648 def _withitem(self, t):
649 self.dispatch(t.context_expr)
650 if t.optional_vars:
651 self.write(" as ")
652 self.dispatch(t.optional_vars)
653
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000654def roundtrip(filename, output=sys.stdout):
Mark Dickinson82c8d932010-06-29 07:48:23 +0000655 with open(filename, "rb") as pyfile:
656 encoding = tokenize.detect_encoding(pyfile.readline)[0]
657 with open(filename, "r", encoding=encoding) as pyfile:
658 source = pyfile.read()
Mark Dickinson3d1bfbf2010-06-28 21:39:51 +0000659 tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000660 Unparser(tree, output)
661
662
663
664def testdir(a):
665 try:
666 names = [n for n in os.listdir(a) if n.endswith('.py')]
667 except OSError:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000668 print("Directory not readable: %s" % a, file=sys.stderr)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000669 else:
670 for n in names:
671 fullname = os.path.join(a, n)
672 if os.path.isfile(fullname):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000673 output = io.StringIO()
674 print('Testing %s' % fullname)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000675 try:
676 roundtrip(fullname, output)
Guido van Rossumb940e112007-01-10 16:19:56 +0000677 except Exception as e:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000678 print(' Failed to compile, exception is %s' % repr(e))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000679 elif os.path.isdir(fullname):
680 testdir(fullname)
681
682def main(args):
683 if args[0] == '--testdir':
684 for a in args[1:]:
685 testdir(a)
686 else:
687 for a in args:
688 roundtrip(a)
Tim Peters400cbc32006-02-28 18:44:41 +0000689
690if __name__=='__main__':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000691 main(sys.argv[1:])