blob: 70b47a17405312f281c3e421718b363c9426c551 [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
Victor Stinner1396d8f2019-01-25 01:49:53 +010082 def _NamedExpr(self, tree):
83 self.write("(")
84 self.dispatch(tree.target)
85 self.write(" := ")
86 self.dispatch(tree.value)
87 self.write(")")
88
Tim Peters400cbc32006-02-28 18:44:41 +000089 def _Import(self, t):
90 self.fill("import ")
Guido van Rossumd8faa362007-04-27 19:54:29 +000091 interleave(lambda: self.write(", "), self.dispatch, t.names)
Tim Peters400cbc32006-02-28 18:44:41 +000092
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000093 def _ImportFrom(self, t):
94 self.fill("from ")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +000095 self.write("." * t.level)
96 if t.module:
97 self.write(t.module)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000098 self.write(" import ")
Guido van Rossumd8faa362007-04-27 19:54:29 +000099 interleave(lambda: self.write(", "), self.dispatch, t.names)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000100
Tim Peters400cbc32006-02-28 18:44:41 +0000101 def _Assign(self, t):
102 self.fill()
103 for target in t.targets:
104 self.dispatch(target)
105 self.write(" = ")
106 self.dispatch(t.value)
107
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000108 def _AugAssign(self, t):
109 self.fill()
110 self.dispatch(t.target)
111 self.write(" "+self.binop[t.op.__class__.__name__]+"= ")
112 self.dispatch(t.value)
113
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700114 def _AnnAssign(self, t):
115 self.fill()
116 if not t.simple and isinstance(t.target, ast.Name):
117 self.write('(')
118 self.dispatch(t.target)
119 if not t.simple and isinstance(t.target, ast.Name):
120 self.write(')')
121 self.write(": ")
122 self.dispatch(t.annotation)
123 if t.value:
124 self.write(" = ")
125 self.dispatch(t.value)
126
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000127 def _Return(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128 self.fill("return")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000129 if t.value:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000130 self.write(" ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000131 self.dispatch(t.value)
132
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000133 def _Pass(self, t):
134 self.fill("pass")
135
136 def _Break(self, t):
137 self.fill("break")
138
139 def _Continue(self, t):
140 self.fill("continue")
141
142 def _Delete(self, t):
143 self.fill("del ")
Mark Dickinsonae100052010-06-28 19:44:20 +0000144 interleave(lambda: self.write(", "), self.dispatch, t.targets)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000145
146 def _Assert(self, t):
147 self.fill("assert ")
148 self.dispatch(t.test)
149 if t.msg:
150 self.write(", ")
151 self.dispatch(t.msg)
152
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000153 def _Global(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000154 self.fill("global ")
155 interleave(lambda: self.write(", "), self.write, t.names)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000156
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000157 def _Nonlocal(self, t):
158 self.fill("nonlocal ")
159 interleave(lambda: self.write(", "), self.write, t.names)
160
Yury Selivanov75445082015-05-11 22:57:16 -0400161 def _Await(self, t):
162 self.write("(")
163 self.write("await")
164 if t.value:
165 self.write(" ")
166 self.dispatch(t.value)
167 self.write(")")
168
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000169 def _Yield(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170 self.write("(")
171 self.write("yield")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000172 if t.value:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173 self.write(" ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000174 self.dispatch(t.value)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000175 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000176
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100177 def _YieldFrom(self, t):
178 self.write("(")
179 self.write("yield from")
180 if t.value:
181 self.write(" ")
182 self.dispatch(t.value)
183 self.write(")")
184
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000185 def _Raise(self, t):
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000186 self.fill("raise")
187 if not t.exc:
188 assert not t.cause
189 return
190 self.write(" ")
191 self.dispatch(t.exc)
192 if t.cause:
193 self.write(" from ")
194 self.dispatch(t.cause)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000195
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100196 def _Try(self, t):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000197 self.fill("try")
198 self.enter()
199 self.dispatch(t.body)
200 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000201 for ex in t.handlers:
202 self.dispatch(ex)
203 if t.orelse:
204 self.fill("else")
205 self.enter()
206 self.dispatch(t.orelse)
207 self.leave()
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100208 if t.finalbody:
209 self.fill("finally")
Mark Dickinson81ad8cc2010-06-30 08:46:53 +0000210 self.enter()
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100211 self.dispatch(t.finalbody)
Mark Dickinson81ad8cc2010-06-30 08:46:53 +0000212 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000213
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000214 def _ExceptHandler(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215 self.fill("except")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216 if t.type:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217 self.write(" ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218 self.dispatch(t.type)
219 if t.name:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000220 self.write(" as ")
221 self.write(t.name)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000222 self.enter()
223 self.dispatch(t.body)
224 self.leave()
225
Tim Peters400cbc32006-02-28 18:44:41 +0000226 def _ClassDef(self, t):
227 self.write("\n")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000228 for deco in t.decorator_list:
229 self.fill("@")
230 self.dispatch(deco)
Tim Peters400cbc32006-02-28 18:44:41 +0000231 self.fill("class "+t.name)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000232 self.write("(")
233 comma = False
234 for e in t.bases:
235 if comma: self.write(", ")
236 else: comma = True
237 self.dispatch(e)
238 for e in t.keywords:
239 if comma: self.write(", ")
240 else: comma = True
241 self.dispatch(e)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000242 self.write(")")
243
Tim Peters400cbc32006-02-28 18:44:41 +0000244 self.enter()
245 self.dispatch(t.body)
246 self.leave()
247
248 def _FunctionDef(self, t):
Yury Selivanov75445082015-05-11 22:57:16 -0400249 self.__FunctionDef_helper(t, "def")
250
251 def _AsyncFunctionDef(self, t):
252 self.__FunctionDef_helper(t, "async def")
253
254 def __FunctionDef_helper(self, t, fill_suffix):
Tim Peters400cbc32006-02-28 18:44:41 +0000255 self.write("\n")
Benjamin Petersonc4fe6f32008-08-19 18:57:56 +0000256 for deco in t.decorator_list:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257 self.fill("@")
258 self.dispatch(deco)
Yury Selivanov75445082015-05-11 22:57:16 -0400259 def_str = fill_suffix+" "+t.name + "("
260 self.fill(def_str)
Tim Peters400cbc32006-02-28 18:44:41 +0000261 self.dispatch(t.args)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000262 self.write(")")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000263 if t.returns:
264 self.write(" -> ")
265 self.dispatch(t.returns)
Tim Peters400cbc32006-02-28 18:44:41 +0000266 self.enter()
267 self.dispatch(t.body)
268 self.leave()
269
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000270 def _For(self, t):
Yury Selivanov75445082015-05-11 22:57:16 -0400271 self.__For_helper("for ", t)
272
273 def _AsyncFor(self, t):
274 self.__For_helper("async for ", t)
275
276 def __For_helper(self, fill, t):
277 self.fill(fill)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000278 self.dispatch(t.target)
279 self.write(" in ")
280 self.dispatch(t.iter)
281 self.enter()
282 self.dispatch(t.body)
283 self.leave()
284 if t.orelse:
285 self.fill("else")
286 self.enter()
287 self.dispatch(t.orelse)
Mark Dickinsonae100052010-06-28 19:44:20 +0000288 self.leave()
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000289
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000290 def _If(self, t):
291 self.fill("if ")
292 self.dispatch(t.test)
293 self.enter()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000294 self.dispatch(t.body)
295 self.leave()
Mark Dickinson8d6d7602010-06-30 08:32:11 +0000296 # collapse nested ifs into equivalent elifs.
297 while (t.orelse and len(t.orelse) == 1 and
298 isinstance(t.orelse[0], ast.If)):
299 t = t.orelse[0]
300 self.fill("elif ")
301 self.dispatch(t.test)
302 self.enter()
303 self.dispatch(t.body)
304 self.leave()
305 # final else
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306 if t.orelse:
307 self.fill("else")
308 self.enter()
309 self.dispatch(t.orelse)
310 self.leave()
311
312 def _While(self, t):
313 self.fill("while ")
314 self.dispatch(t.test)
315 self.enter()
316 self.dispatch(t.body)
317 self.leave()
318 if t.orelse:
319 self.fill("else")
320 self.enter()
321 self.dispatch(t.orelse)
Mark Dickinsonae100052010-06-28 19:44:20 +0000322 self.leave()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000323
324 def _With(self, t):
325 self.fill("with ")
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100326 interleave(lambda: self.write(", "), self.dispatch, t.items)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000327 self.enter()
328 self.dispatch(t.body)
329 self.leave()
330
Yury Selivanov75445082015-05-11 22:57:16 -0400331 def _AsyncWith(self, t):
332 self.fill("async with ")
333 interleave(lambda: self.write(", "), self.dispatch, t.items)
334 self.enter()
335 self.dispatch(t.body)
336 self.leave()
337
Tim Peters400cbc32006-02-28 18:44:41 +0000338 # expr
Eric V. Smith608adf92015-09-20 15:09:15 -0400339 def _JoinedStr(self, t):
340 self.write("f")
341 string = io.StringIO()
342 self._fstring_JoinedStr(t, string.write)
343 self.write(repr(string.getvalue()))
344
345 def _FormattedValue(self, t):
346 self.write("f")
347 string = io.StringIO()
348 self._fstring_FormattedValue(t, string.write)
349 self.write(repr(string.getvalue()))
350
351 def _fstring_JoinedStr(self, t, write):
352 for value in t.values:
353 meth = getattr(self, "_fstring_" + type(value).__name__)
354 meth(value, write)
355
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100356 def _fstring_Constant(self, t, write):
357 assert isinstance(t.value, str)
358 value = t.value.replace("{", "{{").replace("}", "}}")
359 write(value)
360
Eric V. Smith608adf92015-09-20 15:09:15 -0400361 def _fstring_FormattedValue(self, t, write):
362 write("{")
363 expr = io.StringIO()
364 Unparser(t.value, expr)
365 expr = expr.getvalue().rstrip("\n")
366 if expr.startswith("{"):
367 write(" ") # Separate pair of opening brackets as "{ {"
368 write(expr)
369 if t.conversion != -1:
370 conversion = chr(t.conversion)
371 assert conversion in "sra"
372 write(f"!{conversion}")
373 if t.format_spec:
374 write(":")
375 meth = getattr(self, "_fstring_" + type(t.format_spec).__name__)
376 meth(t.format_spec, write)
377 write("}")
378
Tim Peters400cbc32006-02-28 18:44:41 +0000379 def _Name(self, t):
380 self.write(t.id)
381
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100382 def _write_constant(self, value):
383 if isinstance(value, (float, complex)):
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300384 # Substitute overflowing decimal literal for AST infinities.
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100385 self.write(repr(value).replace("inf", INFSTR))
386 else:
387 self.write(repr(value))
388
389 def _Constant(self, t):
390 value = t.value
391 if isinstance(value, tuple):
392 self.write("(")
393 if len(value) == 1:
394 self._write_constant(value[0])
395 self.write(",")
396 else:
397 interleave(lambda: self.write(", "), self._write_constant, value)
398 self.write(")")
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300399 elif value is ...:
400 self.write("...")
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100401 else:
402 self._write_constant(t.value)
403
Tim Peters400cbc32006-02-28 18:44:41 +0000404 def _List(self, t):
405 self.write("[")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000406 interleave(lambda: self.write(", "), self.dispatch, t.elts)
Tim Peters400cbc32006-02-28 18:44:41 +0000407 self.write("]")
408
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409 def _ListComp(self, t):
410 self.write("[")
411 self.dispatch(t.elt)
412 for gen in t.generators:
413 self.dispatch(gen)
414 self.write("]")
415
416 def _GeneratorExp(self, t):
417 self.write("(")
418 self.dispatch(t.elt)
419 for gen in t.generators:
420 self.dispatch(gen)
421 self.write(")")
422
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000423 def _SetComp(self, t):
424 self.write("{")
425 self.dispatch(t.elt)
426 for gen in t.generators:
427 self.dispatch(gen)
428 self.write("}")
429
430 def _DictComp(self, t):
431 self.write("{")
432 self.dispatch(t.key)
433 self.write(": ")
434 self.dispatch(t.value)
435 for gen in t.generators:
436 self.dispatch(gen)
437 self.write("}")
438
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000439 def _comprehension(self, t):
Yury Selivanovbf04b062016-09-09 11:48:39 -0700440 if t.is_async:
441 self.write(" async for ")
442 else:
443 self.write(" for ")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000444 self.dispatch(t.target)
445 self.write(" in ")
446 self.dispatch(t.iter)
447 for if_clause in t.ifs:
448 self.write(" if ")
449 self.dispatch(if_clause)
450
451 def _IfExp(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452 self.write("(")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000453 self.dispatch(t.body)
454 self.write(" if ")
455 self.dispatch(t.test)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000456 self.write(" else ")
457 self.dispatch(t.orelse)
458 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000459
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000460 def _Set(self, t):
461 assert(t.elts) # should be at least one element
462 self.write("{")
463 interleave(lambda: self.write(", "), self.dispatch, t.elts)
464 self.write("}")
465
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000466 def _Dict(self, t):
467 self.write("{")
Berker Peksagd66dd5c2016-03-06 16:50:15 +0200468 def write_key_value_pair(k, v):
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000469 self.dispatch(k)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000470 self.write(": ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000471 self.dispatch(v)
Berker Peksagd66dd5c2016-03-06 16:50:15 +0200472
473 def write_item(item):
474 k, v = item
475 if k is None:
476 # for dictionary unpacking operator in dicts {**{'y': 2}}
477 # see PEP 448 for details
478 self.write("**")
479 self.dispatch(v)
480 else:
481 write_key_value_pair(k, v)
482 interleave(lambda: self.write(", "), write_item, zip(t.keys, t.values))
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000483 self.write("}")
484
485 def _Tuple(self, t):
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000486 self.write("(")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000487 if len(t.elts) == 1:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100488 elt = t.elts[0]
Guido van Rossumd8faa362007-04-27 19:54:29 +0000489 self.dispatch(elt)
490 self.write(",")
491 else:
492 interleave(lambda: self.write(", "), self.dispatch, t.elts)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000493 self.write(")")
494
Tim Peters400cbc32006-02-28 18:44:41 +0000495 unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"}
496 def _UnaryOp(self, t):
Tim Peters400cbc32006-02-28 18:44:41 +0000497 self.write("(")
Mark Dickinsonae100052010-06-28 19:44:20 +0000498 self.write(self.unop[t.op.__class__.__name__])
499 self.write(" ")
Tim Peters400cbc32006-02-28 18:44:41 +0000500 self.dispatch(t.operand)
501 self.write(")")
502
Benjamin Peterson63c46b22014-04-10 00:17:48 -0400503 binop = { "Add":"+", "Sub":"-", "Mult":"*", "MatMult":"@", "Div":"/", "Mod":"%",
Mark Dickinsonae100052010-06-28 19:44:20 +0000504 "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000505 "FloorDiv":"//", "Pow": "**"}
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000506 def _BinOp(self, t):
507 self.write("(")
508 self.dispatch(t.left)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000509 self.write(" " + self.binop[t.op.__class__.__name__] + " ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000510 self.dispatch(t.right)
511 self.write(")")
512
513 cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
514 "Is":"is", "IsNot":"is not", "In":"in", "NotIn":"not in"}
515 def _Compare(self, t):
516 self.write("(")
517 self.dispatch(t.left)
518 for o, e in zip(t.ops, t.comparators):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000519 self.write(" " + self.cmpops[o.__class__.__name__] + " ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000520 self.dispatch(e)
Mark Dickinsonf5451e52010-06-28 20:09:18 +0000521 self.write(")")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000522
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000523 boolops = {ast.And: 'and', ast.Or: 'or'}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000524 def _BoolOp(self, t):
525 self.write("(")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000526 s = " %s " % self.boolops[t.op.__class__]
527 interleave(lambda: self.write(s), self.dispatch, t.values)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000528 self.write(")")
529
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000530 def _Attribute(self,t):
531 self.dispatch(t.value)
Mark Dickinsonb67e15c2010-06-30 09:05:47 +0000532 # Special case: 3.__abs__() is a syntax error, so if t.value
533 # is an integer literal then we need to either parenthesize
534 # it or add an extra space to get 3 .__abs__().
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300535 if isinstance(t.value, ast.Constant) and isinstance(t.value.value, int):
Mark Dickinsonb67e15c2010-06-30 09:05:47 +0000536 self.write(" ")
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000537 self.write(".")
538 self.write(t.attr)
539
540 def _Call(self, t):
541 self.dispatch(t.func)
542 self.write("(")
543 comma = False
544 for e in t.args:
545 if comma: self.write(", ")
546 else: comma = True
547 self.dispatch(e)
548 for e in t.keywords:
549 if comma: self.write(", ")
550 else: comma = True
551 self.dispatch(e)
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000552 self.write(")")
553
554 def _Subscript(self, t):
555 self.dispatch(t.value)
556 self.write("[")
557 self.dispatch(t.slice)
558 self.write("]")
559
Mark Dickinson1b2e9442012-05-06 17:27:39 +0100560 def _Starred(self, t):
561 self.write("*")
562 self.dispatch(t.value)
563
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000564 # slice
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000565 def _Ellipsis(self, t):
566 self.write("...")
567
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000568 def _Index(self, t):
569 self.dispatch(t.value)
570
571 def _Slice(self, t):
572 if t.lower:
573 self.dispatch(t.lower)
574 self.write(":")
575 if t.upper:
576 self.dispatch(t.upper)
577 if t.step:
578 self.write(":")
579 self.dispatch(t.step)
580
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000581 def _ExtSlice(self, t):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000582 interleave(lambda: self.write(', '), self.dispatch, t.dims)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000583
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000584 # argument
585 def _arg(self, t):
586 self.write(t.arg)
587 if t.annotation:
588 self.write(": ")
589 self.dispatch(t.annotation)
590
Tim Peters400cbc32006-02-28 18:44:41 +0000591 # others
592 def _arguments(self, t):
593 first = True
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000594 # normal arguments
595 defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults
596 for a, d in zip(t.args, defaults):
Tim Peters400cbc32006-02-28 18:44:41 +0000597 if first:first = False
598 else: self.write(", ")
599 self.dispatch(a)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000600 if d:
601 self.write("=")
602 self.dispatch(d)
603
604 # varargs, or bare '*' if no varargs but keyword-only arguments present
605 if t.vararg or t.kwonlyargs:
Martin v. Löwis87a8b4f2006-02-28 21:41:30 +0000606 if first:first = False
607 else: self.write(", ")
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000608 self.write("*")
609 if t.vararg:
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700610 self.write(t.vararg.arg)
611 if t.vararg.annotation:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000612 self.write(": ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700613 self.dispatch(t.vararg.annotation)
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000614
615 # keyword-only arguments
616 if t.kwonlyargs:
617 for a, d in zip(t.kwonlyargs, t.kw_defaults):
618 if first:first = False
619 else: self.write(", ")
620 self.dispatch(a),
621 if d:
622 self.write("=")
623 self.dispatch(d)
624
625 # kwargs
Tim Peters400cbc32006-02-28 18:44:41 +0000626 if t.kwarg:
627 if first:first = False
628 else: self.write(", ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700629 self.write("**"+t.kwarg.arg)
630 if t.kwarg.annotation:
Mark Dickinsonfa2e4e92010-06-28 21:14:17 +0000631 self.write(": ")
Benjamin Petersoncda75be2013-03-18 10:48:58 -0700632 self.dispatch(t.kwarg.annotation)
Tim Peters400cbc32006-02-28 18:44:41 +0000633
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000634 def _keyword(self, t):
Benjamin Peterson025e9eb2015-05-05 20:16:41 -0400635 if t.arg is None:
636 self.write("**")
637 else:
638 self.write(t.arg)
639 self.write("=")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000640 self.dispatch(t.value)
641
642 def _Lambda(self, t):
Mark Dickinson8042e282010-06-29 10:01:48 +0000643 self.write("(")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000644 self.write("lambda ")
645 self.dispatch(t.args)
646 self.write(": ")
647 self.dispatch(t.body)
Mark Dickinson8042e282010-06-29 10:01:48 +0000648 self.write(")")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000649
Guido van Rossumd8faa362007-04-27 19:54:29 +0000650 def _alias(self, t):
651 self.write(t.name)
652 if t.asname:
653 self.write(" as "+t.asname)
654
Mark Dickinsonfe8440a2012-05-06 17:35:19 +0100655 def _withitem(self, t):
656 self.dispatch(t.context_expr)
657 if t.optional_vars:
658 self.write(" as ")
659 self.dispatch(t.optional_vars)
660
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000661def roundtrip(filename, output=sys.stdout):
Mark Dickinson82c8d932010-06-29 07:48:23 +0000662 with open(filename, "rb") as pyfile:
663 encoding = tokenize.detect_encoding(pyfile.readline)[0]
664 with open(filename, "r", encoding=encoding) as pyfile:
665 source = pyfile.read()
Mark Dickinson3d1bfbf2010-06-28 21:39:51 +0000666 tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000667 Unparser(tree, output)
668
669
670
671def testdir(a):
672 try:
673 names = [n for n in os.listdir(a) if n.endswith('.py')]
674 except OSError:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000675 print("Directory not readable: %s" % a, file=sys.stderr)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000676 else:
677 for n in names:
678 fullname = os.path.join(a, n)
679 if os.path.isfile(fullname):
Collin Winter6f2df4d2007-07-17 20:59:35 +0000680 output = io.StringIO()
681 print('Testing %s' % fullname)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000682 try:
683 roundtrip(fullname, output)
Guido van Rossumb940e112007-01-10 16:19:56 +0000684 except Exception as e:
Collin Winter6f2df4d2007-07-17 20:59:35 +0000685 print(' Failed to compile, exception is %s' % repr(e))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000686 elif os.path.isdir(fullname):
687 testdir(fullname)
688
689def main(args):
690 if args[0] == '--testdir':
691 for a in args[1:]:
692 testdir(a)
693 else:
694 for a in args:
695 roundtrip(a)
Tim Peters400cbc32006-02-28 18:44:41 +0000696
697if __name__=='__main__':
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000698 main(sys.argv[1:])