blob: 845c80c2bbc0d82a6d307261e2161e50d64a9621 [file] [log] [blame]
Georg Brandl0c77a822008-06-10 16:37:50 +00001"""
2 ast
3 ~~~
4
5 The `ast` module helps Python applications to process trees of the Python
6 abstract syntax grammar. The abstract syntax itself might change with
7 each Python release; this module helps to find out programmatically what
8 the current grammar looks like and allows modifications of it.
9
10 An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
11 a flag to the `compile()` builtin function or by using the `parse()`
12 function from this module. The result will be a tree of objects whose
13 classes all inherit from `ast.AST`.
14
15 A modified abstract syntax tree can be compiled into a Python code object
16 using the built-in `compile()` function.
17
18 Additionally various helper functions are provided that make working with
19 the trees simpler. The main intention of the helper functions and this
20 module in general is to provide an easy to use interface for libraries
21 that work tightly with the python syntax (template engines for example).
22
23
24 :copyright: Copyright 2008 by Armin Ronacher.
25 :license: Python License.
26"""
Pablo Galindo27fc3b62019-11-24 23:02:40 +000027import sys
Georg Brandl0c77a822008-06-10 16:37:50 +000028from _ast import *
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +030029from contextlib import contextmanager, nullcontext
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +030030from enum import IntEnum, auto
Georg Brandl0c77a822008-06-10 16:37:50 +000031
32
Guido van Rossum495da292019-03-07 12:38:08 -080033def parse(source, filename='<unknown>', mode='exec', *,
Guido van Rossum10b55c12019-06-11 17:23:12 -070034 type_comments=False, feature_version=None):
Georg Brandl0c77a822008-06-10 16:37:50 +000035 """
Terry Reedyfeac6242011-01-24 21:36:03 +000036 Parse the source into an AST node.
37 Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
Guido van Rossumdcfcd142019-01-31 03:40:27 -080038 Pass type_comments=True to get back type comments where the syntax allows.
Georg Brandl0c77a822008-06-10 16:37:50 +000039 """
Guido van Rossumdcfcd142019-01-31 03:40:27 -080040 flags = PyCF_ONLY_AST
41 if type_comments:
42 flags |= PyCF_TYPE_COMMENTS
Guido van Rossum10b55c12019-06-11 17:23:12 -070043 if isinstance(feature_version, tuple):
44 major, minor = feature_version # Should be a 2-tuple.
45 assert major == 3
46 feature_version = minor
47 elif feature_version is None:
48 feature_version = -1
49 # Else it should be an int giving the minor version for 3.x.
Guido van Rossum495da292019-03-07 12:38:08 -080050 return compile(source, filename, mode, flags,
Victor Stinnerefdf6ca2019-06-12 02:52:16 +020051 _feature_version=feature_version)
Georg Brandl0c77a822008-06-10 16:37:50 +000052
53
54def literal_eval(node_or_string):
55 """
56 Safely evaluate an expression node or a string containing a Python
57 expression. The string or node provided may only consist of the following
Éric Araujo2a83cc62011-04-17 19:10:27 +020058 Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
59 sets, booleans, and None.
Georg Brandl0c77a822008-06-10 16:37:50 +000060 """
Georg Brandl0c77a822008-06-10 16:37:50 +000061 if isinstance(node_or_string, str):
Batuhan Taskayae799aa82020-10-04 03:46:44 +030062 node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval')
Georg Brandl0c77a822008-06-10 16:37:50 +000063 if isinstance(node_or_string, Expression):
64 node_or_string = node_or_string.body
Curtis Bucherc21c5122020-05-05 12:40:56 -070065 def _raise_malformed_node(node):
Irit Katriel586f3db2020-12-25 17:04:31 +000066 msg = "malformed node or string"
67 if lno := getattr(node, 'lineno', None):
68 msg += f' on line {lno}'
69 raise ValueError(msg + f': {node!r}')
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +020070 def _convert_num(node):
Curtis Bucherc21c5122020-05-05 12:40:56 -070071 if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
72 _raise_malformed_node(node)
73 return node.value
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +020074 def _convert_signed_num(node):
75 if isinstance(node, UnaryOp) and isinstance(node.op, (UAdd, USub)):
76 operand = _convert_num(node.operand)
77 if isinstance(node.op, UAdd):
78 return + operand
79 else:
80 return - operand
81 return _convert_num(node)
Georg Brandl0c77a822008-06-10 16:37:50 +000082 def _convert(node):
Victor Stinnerf2c1aa12016-01-26 00:40:57 +010083 if isinstance(node, Constant):
84 return node.value
Georg Brandl0c77a822008-06-10 16:37:50 +000085 elif isinstance(node, Tuple):
86 return tuple(map(_convert, node.elts))
87 elif isinstance(node, List):
88 return list(map(_convert, node.elts))
Georg Brandl492f3fc2010-07-11 09:41:21 +000089 elif isinstance(node, Set):
90 return set(map(_convert, node.elts))
Raymond Hettinger4fcf5c12020-01-02 22:21:18 -070091 elif (isinstance(node, Call) and isinstance(node.func, Name) and
92 node.func.id == 'set' and node.args == node.keywords == []):
93 return set()
Georg Brandl0c77a822008-06-10 16:37:50 +000094 elif isinstance(node, Dict):
Curtis Bucherc21c5122020-05-05 12:40:56 -070095 if len(node.keys) != len(node.values):
96 _raise_malformed_node(node)
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +020097 return dict(zip(map(_convert, node.keys),
98 map(_convert, node.values)))
Victor Stinnerf2c1aa12016-01-26 00:40:57 +010099 elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200100 left = _convert_signed_num(node.left)
101 right = _convert_num(node.right)
102 if isinstance(left, (int, float)) and isinstance(right, complex):
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100103 if isinstance(node.op, Add):
104 return left + right
105 else:
106 return left - right
Serhiy Storchakad8ac4d12018-01-04 11:15:39 +0200107 return _convert_signed_num(node)
Georg Brandl0c77a822008-06-10 16:37:50 +0000108 return _convert(node_or_string)
109
110
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300111def dump(node, annotate_fields=True, include_attributes=False, *, indent=None):
Georg Brandl0c77a822008-06-10 16:37:50 +0000112 """
Serhiy Storchakae64f9482019-08-29 09:30:23 +0300113 Return a formatted dump of the tree in node. This is mainly useful for
114 debugging purposes. If annotate_fields is true (by default),
115 the returned string will show the names and the values for fields.
116 If annotate_fields is false, the result string will be more compact by
117 omitting unambiguous field names. Attributes such as line
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000118 numbers and column offsets are not dumped by default. If this is wanted,
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300119 include_attributes can be set to true. If indent is a non-negative
120 integer or string, then the tree will be pretty-printed with that indent
121 level. None (the default) selects the single line representation.
Georg Brandl0c77a822008-06-10 16:37:50 +0000122 """
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300123 def _format(node, level=0):
124 if indent is not None:
125 level += 1
126 prefix = '\n' + indent * level
127 sep = ',\n' + indent * level
128 else:
129 prefix = ''
130 sep = ', '
Georg Brandl0c77a822008-06-10 16:37:50 +0000131 if isinstance(node, AST):
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200132 cls = type(node)
Serhiy Storchakae64f9482019-08-29 09:30:23 +0300133 args = []
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300134 allsimple = True
Serhiy Storchakae64f9482019-08-29 09:30:23 +0300135 keywords = annotate_fields
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200136 for name in node._fields:
Serhiy Storchakae64f9482019-08-29 09:30:23 +0300137 try:
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200138 value = getattr(node, name)
Serhiy Storchakae64f9482019-08-29 09:30:23 +0300139 except AttributeError:
140 keywords = True
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200141 continue
142 if value is None and getattr(cls, name, ...) is None:
143 keywords = True
144 continue
145 value, simple = _format(value, level)
146 allsimple = allsimple and simple
147 if keywords:
148 args.append('%s=%s' % (name, value))
Serhiy Storchakae64f9482019-08-29 09:30:23 +0300149 else:
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200150 args.append(value)
151 if include_attributes and node._attributes:
152 for name in node._attributes:
153 try:
154 value = getattr(node, name)
155 except AttributeError:
156 continue
157 if value is None and getattr(cls, name, ...) is None:
158 continue
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300159 value, simple = _format(value, level)
160 allsimple = allsimple and simple
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200161 args.append('%s=%s' % (name, value))
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300162 if allsimple and len(args) <= 3:
163 return '%s(%s)' % (node.__class__.__name__, ', '.join(args)), not args
164 return '%s(%s%s)' % (node.__class__.__name__, prefix, sep.join(args)), False
Georg Brandl0c77a822008-06-10 16:37:50 +0000165 elif isinstance(node, list):
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300166 if not node:
167 return '[]', True
168 return '[%s%s]' % (prefix, sep.join(_format(x, level)[0] for x in node)), False
169 return repr(node), True
170
Georg Brandl0c77a822008-06-10 16:37:50 +0000171 if not isinstance(node, AST):
172 raise TypeError('expected AST, got %r' % node.__class__.__name__)
Serhiy Storchaka850573b2019-09-09 19:33:13 +0300173 if indent is not None and not isinstance(indent, str):
174 indent = ' ' * indent
175 return _format(node)[0]
Georg Brandl0c77a822008-06-10 16:37:50 +0000176
177
178def copy_location(new_node, old_node):
179 """
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000180 Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
181 attributes) from *old_node* to *new_node* if possible, and return *new_node*.
Georg Brandl0c77a822008-06-10 16:37:50 +0000182 """
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000183 for attr in 'lineno', 'col_offset', 'end_lineno', 'end_col_offset':
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200184 if attr in old_node._attributes and attr in new_node._attributes:
185 value = getattr(old_node, attr, None)
Batuhan Taskaya8f4380d2020-08-05 16:32:32 +0300186 # end_lineno and end_col_offset are optional attributes, and they
187 # should be copied whether the value is None or not.
188 if value is not None or (
189 hasattr(old_node, attr) and attr.startswith("end_")
190 ):
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200191 setattr(new_node, attr, value)
Georg Brandl0c77a822008-06-10 16:37:50 +0000192 return new_node
193
194
195def fix_missing_locations(node):
196 """
197 When you compile a node tree with compile(), the compiler expects lineno and
198 col_offset attributes for every node that supports them. This is rather
199 tedious to fill in for generated nodes, so this helper adds these attributes
200 recursively where not already set, by setting them to the values of the
201 parent node. It works recursively starting at *node*.
202 """
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000203 def _fix(node, lineno, col_offset, end_lineno, end_col_offset):
Georg Brandl0c77a822008-06-10 16:37:50 +0000204 if 'lineno' in node._attributes:
205 if not hasattr(node, 'lineno'):
206 node.lineno = lineno
207 else:
208 lineno = node.lineno
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000209 if 'end_lineno' in node._attributes:
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200210 if getattr(node, 'end_lineno', None) is None:
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000211 node.end_lineno = end_lineno
212 else:
213 end_lineno = node.end_lineno
Georg Brandl0c77a822008-06-10 16:37:50 +0000214 if 'col_offset' in node._attributes:
215 if not hasattr(node, 'col_offset'):
216 node.col_offset = col_offset
217 else:
218 col_offset = node.col_offset
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000219 if 'end_col_offset' in node._attributes:
Serhiy Storchakab7e95252020-03-10 00:07:47 +0200220 if getattr(node, 'end_col_offset', None) is None:
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000221 node.end_col_offset = end_col_offset
222 else:
223 end_col_offset = node.end_col_offset
Georg Brandl0c77a822008-06-10 16:37:50 +0000224 for child in iter_child_nodes(node):
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000225 _fix(child, lineno, col_offset, end_lineno, end_col_offset)
226 _fix(node, 1, 0, 1, 0)
Georg Brandl0c77a822008-06-10 16:37:50 +0000227 return node
228
229
230def increment_lineno(node, n=1):
231 """
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000232 Increment the line number and end line number of each node in the tree
233 starting at *node* by *n*. This is useful to "move code" to a different
234 location in a file.
Georg Brandl0c77a822008-06-10 16:37:50 +0000235 """
Georg Brandl0c77a822008-06-10 16:37:50 +0000236 for child in walk(node):
237 if 'lineno' in child._attributes:
238 child.lineno = getattr(child, 'lineno', 0) + n
Batuhan Taskaya8f4380d2020-08-05 16:32:32 +0300239 if (
240 "end_lineno" in child._attributes
241 and (end_lineno := getattr(child, "end_lineno", 0)) is not None
242 ):
243 child.end_lineno = end_lineno + n
Georg Brandl0c77a822008-06-10 16:37:50 +0000244 return node
245
246
247def iter_fields(node):
248 """
249 Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
250 that is present on *node*.
251 """
252 for field in node._fields:
253 try:
254 yield field, getattr(node, field)
255 except AttributeError:
256 pass
257
258
259def iter_child_nodes(node):
260 """
261 Yield all direct child nodes of *node*, that is, all fields that are nodes
262 and all items of fields that are lists of nodes.
263 """
264 for name, field in iter_fields(node):
265 if isinstance(field, AST):
266 yield field
267 elif isinstance(field, list):
268 for item in field:
269 if isinstance(item, AST):
270 yield item
271
272
273def get_docstring(node, clean=True):
274 """
275 Return the docstring for the given node or None if no docstring can
276 be found. If the node provided does not have docstrings a TypeError
277 will be raised.
Matthias Bussonnier41cea702017-02-23 22:44:19 -0800278
279 If *clean* is `True`, all tabs are expanded to spaces and any whitespace
280 that can be uniformly removed from the second line onwards is removed.
Georg Brandl0c77a822008-06-10 16:37:50 +0000281 """
Yury Selivanov2f07a662015-07-23 08:54:35 +0300282 if not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)):
Georg Brandl0c77a822008-06-10 16:37:50 +0000283 raise TypeError("%r can't have docstrings" % node.__class__.__name__)
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300284 if not(node.body and isinstance(node.body[0], Expr)):
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +0300285 return None
286 node = node.body[0].value
287 if isinstance(node, Str):
288 text = node.s
289 elif isinstance(node, Constant) and isinstance(node.value, str):
290 text = node.value
291 else:
292 return None
Serhiy Storchaka08f127a2018-06-15 11:05:15 +0300293 if clean:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +0100294 import inspect
295 text = inspect.cleandoc(text)
296 return text
Georg Brandl0c77a822008-06-10 16:37:50 +0000297
298
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000299def _splitlines_no_ff(source):
300 """Split a string into lines ignoring form feed and other chars.
301
302 This mimics how the Python parser splits source code.
303 """
304 idx = 0
305 lines = []
306 next_line = ''
307 while idx < len(source):
308 c = source[idx]
309 next_line += c
310 idx += 1
311 # Keep \r\n together
312 if c == '\r' and idx < len(source) and source[idx] == '\n':
313 next_line += '\n'
314 idx += 1
315 if c in '\r\n':
316 lines.append(next_line)
317 next_line = ''
318
319 if next_line:
320 lines.append(next_line)
321 return lines
322
323
324def _pad_whitespace(source):
mpheathfbeba8f2020-02-14 04:32:09 +1000325 r"""Replace all chars except '\f\t' in a line with spaces."""
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000326 result = ''
327 for c in source:
328 if c in '\f\t':
329 result += c
330 else:
331 result += ' '
332 return result
333
334
335def get_source_segment(source, node, *, padded=False):
336 """Get source code segment of the *source* that generated *node*.
337
338 If some location information (`lineno`, `end_lineno`, `col_offset`,
339 or `end_col_offset`) is missing, return None.
340
341 If *padded* is `True`, the first line of a multi-line statement will
342 be padded with spaces to match its original position.
343 """
344 try:
Irit Katriele6578a22020-05-18 19:14:12 +0100345 if node.end_lineno is None or node.end_col_offset is None:
346 return None
Ivan Levkivskyi9932a222019-01-22 11:18:22 +0000347 lineno = node.lineno - 1
348 end_lineno = node.end_lineno - 1
349 col_offset = node.col_offset
350 end_col_offset = node.end_col_offset
351 except AttributeError:
352 return None
353
354 lines = _splitlines_no_ff(source)
355 if end_lineno == lineno:
356 return lines[lineno].encode()[col_offset:end_col_offset].decode()
357
358 if padded:
359 padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
360 else:
361 padding = ''
362
363 first = padding + lines[lineno].encode()[col_offset:].decode()
364 last = lines[end_lineno].encode()[:end_col_offset].decode()
365 lines = lines[lineno+1:end_lineno]
366
367 lines.insert(0, first)
368 lines.append(last)
369 return ''.join(lines)
370
371
Georg Brandl0c77a822008-06-10 16:37:50 +0000372def walk(node):
373 """
Georg Brandl619e7ba2011-01-09 07:38:51 +0000374 Recursively yield all descendant nodes in the tree starting at *node*
375 (including *node* itself), in no specified order. This is useful if you
376 only want to modify nodes in place and don't care about the context.
Georg Brandl0c77a822008-06-10 16:37:50 +0000377 """
378 from collections import deque
379 todo = deque([node])
380 while todo:
381 node = todo.popleft()
382 todo.extend(iter_child_nodes(node))
383 yield node
384
385
386class NodeVisitor(object):
387 """
388 A node visitor base class that walks the abstract syntax tree and calls a
389 visitor function for every node found. This function may return a value
390 which is forwarded by the `visit` method.
391
392 This class is meant to be subclassed, with the subclass adding visitor
393 methods.
394
395 Per default the visitor functions for the nodes are ``'visit_'`` +
396 class name of the node. So a `TryFinally` node visit function would
397 be `visit_TryFinally`. This behavior can be changed by overriding
398 the `visit` method. If no visitor function exists for a node
399 (return value `None`) the `generic_visit` visitor is used instead.
400
401 Don't use the `NodeVisitor` if you want to apply changes to nodes during
402 traversing. For this a special visitor exists (`NodeTransformer`) that
403 allows modifications.
404 """
405
406 def visit(self, node):
407 """Visit a node."""
408 method = 'visit_' + node.__class__.__name__
409 visitor = getattr(self, method, self.generic_visit)
410 return visitor(node)
411
412 def generic_visit(self, node):
413 """Called if no explicit visitor function exists for a node."""
414 for field, value in iter_fields(node):
415 if isinstance(value, list):
416 for item in value:
417 if isinstance(item, AST):
418 self.visit(item)
419 elif isinstance(value, AST):
420 self.visit(value)
421
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +0300422 def visit_Constant(self, node):
423 value = node.value
424 type_name = _const_node_type_names.get(type(value))
425 if type_name is None:
426 for cls, name in _const_node_type_names.items():
427 if isinstance(value, cls):
428 type_name = name
429 break
430 if type_name is not None:
431 method = 'visit_' + type_name
432 try:
433 visitor = getattr(self, method)
434 except AttributeError:
435 pass
436 else:
437 import warnings
438 warnings.warn(f"{method} is deprecated; add visit_Constant",
439 DeprecationWarning, 2)
440 return visitor(node)
441 return self.generic_visit(node)
442
Georg Brandl0c77a822008-06-10 16:37:50 +0000443
444class NodeTransformer(NodeVisitor):
445 """
446 A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
447 allows modification of nodes.
448
449 The `NodeTransformer` will walk the AST and use the return value of the
450 visitor methods to replace or remove the old node. If the return value of
451 the visitor method is ``None``, the node will be removed from its location,
452 otherwise it is replaced with the return value. The return value may be the
453 original node in which case no replacement takes place.
454
455 Here is an example transformer that rewrites all occurrences of name lookups
456 (``foo``) to ``data['foo']``::
457
458 class RewriteName(NodeTransformer):
459
460 def visit_Name(self, node):
Pablo Galindoc00c86b2020-03-12 00:48:19 +0000461 return Subscript(
Georg Brandl0c77a822008-06-10 16:37:50 +0000462 value=Name(id='data', ctx=Load()),
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200463 slice=Constant(value=node.id),
Georg Brandl0c77a822008-06-10 16:37:50 +0000464 ctx=node.ctx
Pablo Galindoc00c86b2020-03-12 00:48:19 +0000465 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000466
467 Keep in mind that if the node you're operating on has child nodes you must
468 either transform the child nodes yourself or call the :meth:`generic_visit`
469 method for the node first.
470
471 For nodes that were part of a collection of statements (that applies to all
472 statement nodes), the visitor may also return a list of nodes rather than
473 just a single node.
474
475 Usually you use the transformer like this::
476
477 node = YourTransformer().visit(node)
478 """
479
480 def generic_visit(self, node):
481 for field, old_value in iter_fields(node):
Georg Brandl0c77a822008-06-10 16:37:50 +0000482 if isinstance(old_value, list):
483 new_values = []
484 for value in old_value:
485 if isinstance(value, AST):
486 value = self.visit(value)
487 if value is None:
488 continue
489 elif not isinstance(value, AST):
490 new_values.extend(value)
491 continue
492 new_values.append(value)
493 old_value[:] = new_values
494 elif isinstance(old_value, AST):
495 new_node = self.visit(old_value)
496 if new_node is None:
497 delattr(node, field)
498 else:
499 setattr(node, field, new_node)
500 return node
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300501
502
Victor Stinnere5fbe0c2020-09-15 18:03:34 +0200503# If the ast module is loaded more than once, only add deprecated methods once
504if not hasattr(Constant, 'n'):
505 # The following code is for backward compatibility.
506 # It will be removed in future.
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300507
Victor Stinnere5fbe0c2020-09-15 18:03:34 +0200508 def _getter(self):
509 """Deprecated. Use value instead."""
510 return self.value
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300511
Victor Stinnere5fbe0c2020-09-15 18:03:34 +0200512 def _setter(self, value):
513 self.value = value
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300514
Victor Stinnere5fbe0c2020-09-15 18:03:34 +0200515 Constant.n = property(_getter, _setter)
516 Constant.s = property(_getter, _setter)
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300517
518class _ABC(type):
519
Serhiy Storchakabace59d2020-03-22 20:33:34 +0200520 def __init__(cls, *args):
521 cls.__doc__ = """Deprecated AST node class. Use ast.Constant instead"""
522
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300523 def __instancecheck__(cls, inst):
524 if not isinstance(inst, Constant):
525 return False
526 if cls in _const_types:
527 try:
528 value = inst.value
529 except AttributeError:
530 return False
531 else:
Anthony Sottile74176222019-01-18 11:30:28 -0800532 return (
533 isinstance(value, _const_types[cls]) and
534 not isinstance(value, _const_types_not.get(cls, ()))
535 )
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300536 return type.__instancecheck__(cls, inst)
537
538def _new(cls, *args, **kwargs):
Rémi Lapeyrec73914a2020-05-24 23:12:57 +0200539 for key in kwargs:
540 if key not in cls._fields:
541 # arbitrary keyword arguments are accepted
542 continue
543 pos = cls._fields.index(key)
544 if pos < len(args):
545 raise TypeError(f"{cls.__name__} got multiple values for argument {key!r}")
Serhiy Storchaka3f228112018-09-27 17:42:37 +0300546 if cls in _const_types:
547 return Constant(*args, **kwargs)
548 return Constant.__new__(cls, *args, **kwargs)
549
550class Num(Constant, metaclass=_ABC):
551 _fields = ('n',)
552 __new__ = _new
553
554class Str(Constant, metaclass=_ABC):
555 _fields = ('s',)
556 __new__ = _new
557
558class Bytes(Constant, metaclass=_ABC):
559 _fields = ('s',)
560 __new__ = _new
561
562class NameConstant(Constant, metaclass=_ABC):
563 __new__ = _new
564
565class Ellipsis(Constant, metaclass=_ABC):
566 _fields = ()
567
568 def __new__(cls, *args, **kwargs):
569 if cls is Ellipsis:
570 return Constant(..., *args, **kwargs)
571 return Constant.__new__(cls, *args, **kwargs)
572
573_const_types = {
574 Num: (int, float, complex),
575 Str: (str,),
576 Bytes: (bytes,),
577 NameConstant: (type(None), bool),
578 Ellipsis: (type(...),),
579}
Anthony Sottile74176222019-01-18 11:30:28 -0800580_const_types_not = {
581 Num: (bool,),
582}
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200583
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +0300584_const_node_type_names = {
585 bool: 'NameConstant', # should be before int
586 type(None): 'NameConstant',
587 int: 'Num',
588 float: 'Num',
589 complex: 'Num',
590 str: 'Str',
591 bytes: 'Bytes',
592 type(...): 'Ellipsis',
593}
Serhiy Storchaka832e8642019-09-09 23:36:13 +0300594
Serhiy Storchakabace59d2020-03-22 20:33:34 +0200595class slice(AST):
596 """Deprecated AST node class."""
597
598class Index(slice):
599 """Deprecated AST node class. Use the index value directly instead."""
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200600 def __new__(cls, value, **kwargs):
601 return value
602
Serhiy Storchakabace59d2020-03-22 20:33:34 +0200603class ExtSlice(slice):
604 """Deprecated AST node class. Use ast.Tuple instead."""
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200605 def __new__(cls, dims=(), **kwargs):
606 return Tuple(list(dims), Load(), **kwargs)
607
Victor Stinnere5fbe0c2020-09-15 18:03:34 +0200608# If the ast module is loaded more than once, only add deprecated methods once
609if not hasattr(Tuple, 'dims'):
610 # The following code is for backward compatibility.
611 # It will be removed in future.
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200612
Victor Stinnere5fbe0c2020-09-15 18:03:34 +0200613 def _dims_getter(self):
614 """Deprecated. Use elts instead."""
615 return self.elts
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200616
Victor Stinnere5fbe0c2020-09-15 18:03:34 +0200617 def _dims_setter(self, value):
618 self.elts = value
619
620 Tuple.dims = property(_dims_getter, _dims_setter)
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200621
Serhiy Storchakabace59d2020-03-22 20:33:34 +0200622class Suite(mod):
623 """Deprecated AST node class. Unused in Python 3."""
624
625class AugLoad(expr_context):
626 """Deprecated AST node class. Unused in Python 3."""
627
628class AugStore(expr_context):
629 """Deprecated AST node class. Unused in Python 3."""
630
631class Param(expr_context):
632 """Deprecated AST node class. Unused in Python 3."""
633
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200634
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000635# Large float and imaginary literals get turned into infinities in the AST.
636# We unparse those infinities to INFSTR.
637_INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
638
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300639class _Precedence(IntEnum):
640 """Precedence table that originated from python grammar."""
641
642 TUPLE = auto()
643 YIELD = auto() # 'yield', 'yield from'
644 TEST = auto() # 'if'-'else', 'lambda'
645 OR = auto() # 'or'
646 AND = auto() # 'and'
647 NOT = auto() # 'not'
648 CMP = auto() # '<', '>', '==', '>=', '<=', '!=',
649 # 'in', 'not in', 'is', 'is not'
650 EXPR = auto()
651 BOR = EXPR # '|'
652 BXOR = auto() # '^'
653 BAND = auto() # '&'
654 SHIFT = auto() # '<<', '>>'
655 ARITH = auto() # '+', '-'
656 TERM = auto() # '*', '@', '/', '%', '//'
657 FACTOR = auto() # unary '+', '-', '~'
658 POWER = auto() # '**'
659 AWAIT = auto() # 'await'
660 ATOM = auto()
661
662 def next(self):
663 try:
664 return self.__class__(self + 1)
665 except ValueError:
666 return self
667
Shantanua993e902020-11-20 13:16:42 -0800668
669_SINGLE_QUOTES = ("'", '"')
670_MULTI_QUOTES = ('"""', "'''")
671_ALL_QUOTES = (*_SINGLE_QUOTES, *_MULTI_QUOTES)
672
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000673class _Unparser(NodeVisitor):
674 """Methods in this class recursively traverse an AST and
675 output source code for the abstract syntax; original formatting
676 is disregarded."""
677
Shantanua993e902020-11-20 13:16:42 -0800678 def __init__(self, *, _avoid_backslashes=False):
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000679 self._source = []
680 self._buffer = []
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300681 self._precedences = {}
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300682 self._type_ignores = {}
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000683 self._indent = 0
Shantanua993e902020-11-20 13:16:42 -0800684 self._avoid_backslashes = _avoid_backslashes
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000685
686 def interleave(self, inter, f, seq):
687 """Call f on each item in seq, calling inter() in between."""
688 seq = iter(seq)
689 try:
690 f(next(seq))
691 except StopIteration:
692 pass
693 else:
694 for x in seq:
695 inter()
696 f(x)
697
Batuhan Taşkayae7cab7f2020-03-09 23:27:03 +0300698 def items_view(self, traverser, items):
699 """Traverse and separate the given *items* with a comma and append it to
700 the buffer. If *items* is a single item sequence, a trailing comma
701 will be added."""
702 if len(items) == 1:
703 traverser(items[0])
704 self.write(",")
705 else:
706 self.interleave(lambda: self.write(", "), traverser, items)
707
Batuhan Taskaya493bf1c2020-05-03 20:11:51 +0300708 def maybe_newline(self):
709 """Adds a newline if it isn't the start of generated source"""
710 if self._source:
711 self.write("\n")
712
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000713 def fill(self, text=""):
714 """Indent a piece of text and append it, according to the current
715 indentation level"""
Batuhan Taskaya493bf1c2020-05-03 20:11:51 +0300716 self.maybe_newline()
717 self.write(" " * self._indent + text)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000718
719 def write(self, text):
720 """Append a piece of text"""
721 self._source.append(text)
722
723 def buffer_writer(self, text):
724 self._buffer.append(text)
725
726 @property
727 def buffer(self):
728 value = "".join(self._buffer)
729 self._buffer.clear()
730 return value
731
Pablo Galindod69cbeb2019-12-23 16:42:48 +0000732 @contextmanager
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300733 def block(self, *, extra = None):
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000734 """A context manager for preparing the source for blocks. It adds
735 the character':', increases the indentation on enter and decreases
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300736 the indentation on exit. If *extra* is given, it will be directly
737 appended after the colon character.
738 """
Pablo Galindod69cbeb2019-12-23 16:42:48 +0000739 self.write(":")
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300740 if extra:
741 self.write(extra)
Pablo Galindod69cbeb2019-12-23 16:42:48 +0000742 self._indent += 1
743 yield
744 self._indent -= 1
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000745
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300746 @contextmanager
747 def delimit(self, start, end):
748 """A context manager for preparing the source for expressions. It adds
749 *start* to the buffer and enters, after exit it adds *end*."""
750
751 self.write(start)
752 yield
753 self.write(end)
754
755 def delimit_if(self, start, end, condition):
756 if condition:
757 return self.delimit(start, end)
758 else:
759 return nullcontext()
760
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300761 def require_parens(self, precedence, node):
762 """Shortcut to adding precedence related parens"""
763 return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
764
765 def get_precedence(self, node):
766 return self._precedences.get(node, _Precedence.TEST)
767
768 def set_precedence(self, precedence, *nodes):
769 for node in nodes:
770 self._precedences[node] = precedence
771
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +0300772 def get_raw_docstring(self, node):
773 """If a docstring node is found in the body of the *node* parameter,
774 return that docstring node, None otherwise.
775
776 Logic mirrored from ``_PyAST_GetDocString``."""
777 if not isinstance(
778 node, (AsyncFunctionDef, FunctionDef, ClassDef, Module)
779 ) or len(node.body) < 1:
780 return None
781 node = node.body[0]
782 if not isinstance(node, Expr):
783 return None
784 node = node.value
785 if isinstance(node, Constant) and isinstance(node.value, str):
786 return node
787
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300788 def get_type_comment(self, node):
789 comment = self._type_ignores.get(node.lineno) or node.type_comment
790 if comment is not None:
791 return f" # type: {comment}"
792
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000793 def traverse(self, node):
794 if isinstance(node, list):
795 for item in node:
796 self.traverse(item)
797 else:
798 super().visit(node)
799
800 def visit(self, node):
801 """Outputs a source code string that, if converted back to an ast
802 (using ast.parse) will generate an AST equivalent to *node*"""
803 self._source = []
804 self.traverse(node)
805 return "".join(self._source)
806
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +0300807 def _write_docstring_and_traverse_body(self, node):
808 if (docstring := self.get_raw_docstring(node)):
809 self._write_docstring(docstring)
810 self.traverse(node.body[1:])
811 else:
812 self.traverse(node.body)
813
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000814 def visit_Module(self, node):
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300815 self._type_ignores = {
816 ignore.lineno: f"ignore{ignore.tag}"
817 for ignore in node.type_ignores
818 }
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +0300819 self._write_docstring_and_traverse_body(node)
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300820 self._type_ignores.clear()
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000821
Batuhan Taşkaya5b66ec12020-03-15 22:56:57 +0300822 def visit_FunctionType(self, node):
823 with self.delimit("(", ")"):
824 self.interleave(
825 lambda: self.write(", "), self.traverse, node.argtypes
826 )
827
828 self.write(" -> ")
829 self.traverse(node.returns)
830
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000831 def visit_Expr(self, node):
832 self.fill()
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300833 self.set_precedence(_Precedence.YIELD, node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000834 self.traverse(node.value)
835
836 def visit_NamedExpr(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300837 with self.require_parens(_Precedence.TUPLE, node):
838 self.set_precedence(_Precedence.ATOM, node.target, node.value)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300839 self.traverse(node.target)
840 self.write(" := ")
841 self.traverse(node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000842
843 def visit_Import(self, node):
844 self.fill("import ")
845 self.interleave(lambda: self.write(", "), self.traverse, node.names)
846
847 def visit_ImportFrom(self, node):
848 self.fill("from ")
849 self.write("." * node.level)
850 if node.module:
851 self.write(node.module)
852 self.write(" import ")
853 self.interleave(lambda: self.write(", "), self.traverse, node.names)
854
855 def visit_Assign(self, node):
856 self.fill()
857 for target in node.targets:
858 self.traverse(target)
859 self.write(" = ")
860 self.traverse(node.value)
Batuhan Taskayadff92bb2020-05-17 02:04:12 +0300861 if type_comment := self.get_type_comment(node):
862 self.write(type_comment)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000863
864 def visit_AugAssign(self, node):
865 self.fill()
866 self.traverse(node.target)
867 self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
868 self.traverse(node.value)
869
870 def visit_AnnAssign(self, node):
871 self.fill()
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300872 with self.delimit_if("(", ")", not node.simple and isinstance(node.target, Name)):
873 self.traverse(node.target)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000874 self.write(": ")
875 self.traverse(node.annotation)
876 if node.value:
877 self.write(" = ")
878 self.traverse(node.value)
879
880 def visit_Return(self, node):
881 self.fill("return")
882 if node.value:
883 self.write(" ")
884 self.traverse(node.value)
885
886 def visit_Pass(self, node):
887 self.fill("pass")
888
889 def visit_Break(self, node):
890 self.fill("break")
891
892 def visit_Continue(self, node):
893 self.fill("continue")
894
895 def visit_Delete(self, node):
896 self.fill("del ")
897 self.interleave(lambda: self.write(", "), self.traverse, node.targets)
898
899 def visit_Assert(self, node):
900 self.fill("assert ")
901 self.traverse(node.test)
902 if node.msg:
903 self.write(", ")
904 self.traverse(node.msg)
905
906 def visit_Global(self, node):
907 self.fill("global ")
908 self.interleave(lambda: self.write(", "), self.write, node.names)
909
910 def visit_Nonlocal(self, node):
911 self.fill("nonlocal ")
912 self.interleave(lambda: self.write(", "), self.write, node.names)
913
914 def visit_Await(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300915 with self.require_parens(_Precedence.AWAIT, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300916 self.write("await")
917 if node.value:
918 self.write(" ")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300919 self.set_precedence(_Precedence.ATOM, node.value)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300920 self.traverse(node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000921
922 def visit_Yield(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300923 with self.require_parens(_Precedence.YIELD, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300924 self.write("yield")
925 if node.value:
926 self.write(" ")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300927 self.set_precedence(_Precedence.ATOM, node.value)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300928 self.traverse(node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000929
930 def visit_YieldFrom(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300931 with self.require_parens(_Precedence.YIELD, node):
Batuhan Taşkaya7b35bef2020-01-02 21:20:04 +0300932 self.write("yield from ")
933 if not node.value:
934 raise ValueError("Node can't be used without a value attribute.")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +0300935 self.set_precedence(_Precedence.ATOM, node.value)
Batuhan Taşkaya7b35bef2020-01-02 21:20:04 +0300936 self.traverse(node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000937
938 def visit_Raise(self, node):
939 self.fill("raise")
940 if not node.exc:
941 if node.cause:
942 raise ValueError(f"Node can't use cause without an exception.")
943 return
944 self.write(" ")
945 self.traverse(node.exc)
946 if node.cause:
947 self.write(" from ")
948 self.traverse(node.cause)
949
950 def visit_Try(self, node):
951 self.fill("try")
952 with self.block():
953 self.traverse(node.body)
954 for ex in node.handlers:
955 self.traverse(ex)
956 if node.orelse:
957 self.fill("else")
958 with self.block():
959 self.traverse(node.orelse)
960 if node.finalbody:
961 self.fill("finally")
962 with self.block():
963 self.traverse(node.finalbody)
964
965 def visit_ExceptHandler(self, node):
966 self.fill("except")
967 if node.type:
968 self.write(" ")
969 self.traverse(node.type)
970 if node.name:
971 self.write(" as ")
972 self.write(node.name)
973 with self.block():
974 self.traverse(node.body)
975
976 def visit_ClassDef(self, node):
Batuhan Taskaya493bf1c2020-05-03 20:11:51 +0300977 self.maybe_newline()
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000978 for deco in node.decorator_list:
979 self.fill("@")
980 self.traverse(deco)
981 self.fill("class " + node.name)
Batuhan Taskaya25160cd2020-05-17 00:53:25 +0300982 with self.delimit_if("(", ")", condition = node.bases or node.keywords):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +0300983 comma = False
984 for e in node.bases:
985 if comma:
986 self.write(", ")
987 else:
988 comma = True
989 self.traverse(e)
990 for e in node.keywords:
991 if comma:
992 self.write(", ")
993 else:
994 comma = True
995 self.traverse(e)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000996
997 with self.block():
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +0300998 self._write_docstring_and_traverse_body(node)
Pablo Galindo27fc3b62019-11-24 23:02:40 +0000999
1000 def visit_FunctionDef(self, node):
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001001 self._function_helper(node, "def")
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001002
1003 def visit_AsyncFunctionDef(self, node):
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001004 self._function_helper(node, "async def")
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001005
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001006 def _function_helper(self, node, fill_suffix):
Batuhan Taskaya493bf1c2020-05-03 20:11:51 +03001007 self.maybe_newline()
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001008 for deco in node.decorator_list:
1009 self.fill("@")
1010 self.traverse(deco)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001011 def_str = fill_suffix + " " + node.name
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001012 self.fill(def_str)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001013 with self.delimit("(", ")"):
1014 self.traverse(node.args)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001015 if node.returns:
1016 self.write(" -> ")
1017 self.traverse(node.returns)
Batuhan Taskayadff92bb2020-05-17 02:04:12 +03001018 with self.block(extra=self.get_type_comment(node)):
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001019 self._write_docstring_and_traverse_body(node)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001020
1021 def visit_For(self, node):
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001022 self._for_helper("for ", node)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001023
1024 def visit_AsyncFor(self, node):
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001025 self._for_helper("async for ", node)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001026
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001027 def _for_helper(self, fill, node):
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001028 self.fill(fill)
1029 self.traverse(node.target)
1030 self.write(" in ")
1031 self.traverse(node.iter)
Batuhan Taskayadff92bb2020-05-17 02:04:12 +03001032 with self.block(extra=self.get_type_comment(node)):
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001033 self.traverse(node.body)
1034 if node.orelse:
1035 self.fill("else")
1036 with self.block():
1037 self.traverse(node.orelse)
1038
1039 def visit_If(self, node):
1040 self.fill("if ")
1041 self.traverse(node.test)
1042 with self.block():
1043 self.traverse(node.body)
1044 # collapse nested ifs into equivalent elifs.
1045 while node.orelse and len(node.orelse) == 1 and isinstance(node.orelse[0], If):
1046 node = node.orelse[0]
1047 self.fill("elif ")
1048 self.traverse(node.test)
1049 with self.block():
1050 self.traverse(node.body)
1051 # final else
1052 if node.orelse:
1053 self.fill("else")
1054 with self.block():
1055 self.traverse(node.orelse)
1056
1057 def visit_While(self, node):
1058 self.fill("while ")
1059 self.traverse(node.test)
1060 with self.block():
1061 self.traverse(node.body)
1062 if node.orelse:
1063 self.fill("else")
1064 with self.block():
1065 self.traverse(node.orelse)
1066
1067 def visit_With(self, node):
1068 self.fill("with ")
1069 self.interleave(lambda: self.write(", "), self.traverse, node.items)
Batuhan Taskayadff92bb2020-05-17 02:04:12 +03001070 with self.block(extra=self.get_type_comment(node)):
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001071 self.traverse(node.body)
1072
1073 def visit_AsyncWith(self, node):
1074 self.fill("async with ")
1075 self.interleave(lambda: self.write(", "), self.traverse, node.items)
Batuhan Taskayadff92bb2020-05-17 02:04:12 +03001076 with self.block(extra=self.get_type_comment(node)):
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001077 self.traverse(node.body)
1078
Shantanua993e902020-11-20 13:16:42 -08001079 def _str_literal_helper(
1080 self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False
1081 ):
1082 """Helper for writing string literals, minimizing escapes.
1083 Returns the tuple (string literal to write, possible quote types).
1084 """
1085 def escape_char(c):
1086 # \n and \t are non-printable, but we only escape them if
1087 # escape_special_whitespace is True
1088 if not escape_special_whitespace and c in "\n\t":
1089 return c
1090 # Always escape backslashes and other non-printable characters
1091 if c == "\\" or not c.isprintable():
1092 return c.encode("unicode_escape").decode("ascii")
1093 return c
1094
1095 escaped_string = "".join(map(escape_char, string))
1096 possible_quotes = quote_types
1097 if "\n" in escaped_string:
1098 possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
1099 possible_quotes = [q for q in possible_quotes if q not in escaped_string]
1100 if not possible_quotes:
1101 # If there aren't any possible_quotes, fallback to using repr
1102 # on the original string. Try to use a quote from quote_types,
1103 # e.g., so that we use triple quotes for docstrings.
1104 string = repr(string)
1105 quote = next((q for q in quote_types if string[0] in q), string[0])
1106 return string[1:-1], [quote]
1107 if escaped_string:
1108 # Sort so that we prefer '''"''' over """\""""
1109 possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
1110 # If we're using triple quotes and we'd need to escape a final
1111 # quote, escape it
1112 if possible_quotes[0][0] == escaped_string[-1]:
1113 assert len(possible_quotes[0]) == 3
1114 escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
1115 return escaped_string, possible_quotes
1116
1117 def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES):
1118 """Write string literal value with a best effort attempt to avoid backslashes."""
1119 string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
1120 quote_type = quote_types[0]
1121 self.write(f"{quote_type}{string}{quote_type}")
1122
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001123 def visit_JoinedStr(self, node):
1124 self.write("f")
Shantanua993e902020-11-20 13:16:42 -08001125 if self._avoid_backslashes:
1126 self._fstring_JoinedStr(node, self.buffer_writer)
1127 self._write_str_avoiding_backslashes(self.buffer)
1128 return
1129
1130 # If we don't need to avoid backslashes globally (i.e., we only need
1131 # to avoid them inside FormattedValues), it's cosmetically preferred
1132 # to use escaped whitespace. That is, it's preferred to use backslashes
1133 # for cases like: f"{x}\n". To accomplish this, we keep track of what
1134 # in our buffer corresponds to FormattedValues and what corresponds to
1135 # Constant parts of the f-string, and allow escapes accordingly.
1136 buffer = []
1137 for value in node.values:
1138 meth = getattr(self, "_fstring_" + type(value).__name__)
1139 meth(value, self.buffer_writer)
1140 buffer.append((self.buffer, isinstance(value, Constant)))
1141 new_buffer = []
1142 quote_types = _ALL_QUOTES
1143 for value, is_constant in buffer:
1144 # Repeatedly narrow down the list of possible quote_types
1145 value, quote_types = self._str_literal_helper(
1146 value, quote_types=quote_types,
1147 escape_special_whitespace=is_constant
1148 )
1149 new_buffer.append(value)
1150 value = "".join(new_buffer)
1151 quote_type = quote_types[0]
1152 self.write(f"{quote_type}{value}{quote_type}")
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001153
1154 def visit_FormattedValue(self, node):
1155 self.write("f")
1156 self._fstring_FormattedValue(node, self.buffer_writer)
Shantanua993e902020-11-20 13:16:42 -08001157 self._write_str_avoiding_backslashes(self.buffer)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001158
1159 def _fstring_JoinedStr(self, node, write):
1160 for value in node.values:
1161 meth = getattr(self, "_fstring_" + type(value).__name__)
1162 meth(value, write)
1163
1164 def _fstring_Constant(self, node, write):
1165 if not isinstance(node.value, str):
1166 raise ValueError("Constants inside JoinedStr should be a string.")
1167 value = node.value.replace("{", "{{").replace("}", "}}")
1168 write(value)
1169
1170 def _fstring_FormattedValue(self, node, write):
1171 write("{")
Shantanua993e902020-11-20 13:16:42 -08001172 unparser = type(self)(_avoid_backslashes=True)
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001173 unparser.set_precedence(_Precedence.TEST.next(), node.value)
Batuhan Taskaya493bf1c2020-05-03 20:11:51 +03001174 expr = unparser.visit(node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001175 if expr.startswith("{"):
1176 write(" ") # Separate pair of opening brackets as "{ {"
Shantanua993e902020-11-20 13:16:42 -08001177 if "\\" in expr:
1178 raise ValueError("Unable to avoid backslash in f-string expression part")
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001179 write(expr)
1180 if node.conversion != -1:
1181 conversion = chr(node.conversion)
1182 if conversion not in "sra":
1183 raise ValueError("Unknown f-string conversion.")
1184 write(f"!{conversion}")
1185 if node.format_spec:
1186 write(":")
1187 meth = getattr(self, "_fstring_" + type(node.format_spec).__name__)
1188 meth(node.format_spec, write)
1189 write("}")
1190
1191 def visit_Name(self, node):
1192 self.write(node.id)
1193
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001194 def _write_docstring(self, node):
1195 self.fill()
1196 if node.kind == "u":
1197 self.write("u")
Shantanua993e902020-11-20 13:16:42 -08001198 self._write_str_avoiding_backslashes(node.value, quote_types=_MULTI_QUOTES)
Batuhan Taşkaya89aa4692020-03-02 21:59:01 +03001199
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001200 def _write_constant(self, value):
1201 if isinstance(value, (float, complex)):
1202 # Substitute overflowing decimal literal for AST infinities.
1203 self.write(repr(value).replace("inf", _INFSTR))
Shantanua993e902020-11-20 13:16:42 -08001204 elif self._avoid_backslashes and isinstance(value, str):
1205 self._write_str_avoiding_backslashes(value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001206 else:
1207 self.write(repr(value))
1208
1209 def visit_Constant(self, node):
1210 value = node.value
1211 if isinstance(value, tuple):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001212 with self.delimit("(", ")"):
Batuhan Taşkayae7cab7f2020-03-09 23:27:03 +03001213 self.items_view(self._write_constant, value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001214 elif value is ...:
1215 self.write("...")
1216 else:
1217 if node.kind == "u":
1218 self.write("u")
1219 self._write_constant(node.value)
1220
1221 def visit_List(self, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001222 with self.delimit("[", "]"):
1223 self.interleave(lambda: self.write(", "), self.traverse, node.elts)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001224
1225 def visit_ListComp(self, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001226 with self.delimit("[", "]"):
1227 self.traverse(node.elt)
1228 for gen in node.generators:
1229 self.traverse(gen)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001230
1231 def visit_GeneratorExp(self, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001232 with self.delimit("(", ")"):
1233 self.traverse(node.elt)
1234 for gen in node.generators:
1235 self.traverse(gen)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001236
1237 def visit_SetComp(self, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001238 with self.delimit("{", "}"):
1239 self.traverse(node.elt)
1240 for gen in node.generators:
1241 self.traverse(gen)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001242
1243 def visit_DictComp(self, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001244 with self.delimit("{", "}"):
1245 self.traverse(node.key)
1246 self.write(": ")
1247 self.traverse(node.value)
1248 for gen in node.generators:
1249 self.traverse(gen)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001250
1251 def visit_comprehension(self, node):
1252 if node.is_async:
1253 self.write(" async for ")
1254 else:
1255 self.write(" for ")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001256 self.set_precedence(_Precedence.TUPLE, node.target)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001257 self.traverse(node.target)
1258 self.write(" in ")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001259 self.set_precedence(_Precedence.TEST.next(), node.iter, *node.ifs)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001260 self.traverse(node.iter)
1261 for if_clause in node.ifs:
1262 self.write(" if ")
1263 self.traverse(if_clause)
1264
1265 def visit_IfExp(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001266 with self.require_parens(_Precedence.TEST, node):
1267 self.set_precedence(_Precedence.TEST.next(), node.body, node.test)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001268 self.traverse(node.body)
1269 self.write(" if ")
1270 self.traverse(node.test)
1271 self.write(" else ")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001272 self.set_precedence(_Precedence.TEST, node.orelse)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001273 self.traverse(node.orelse)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001274
1275 def visit_Set(self, node):
1276 if not node.elts:
Shantanu01508dc2020-04-16 03:10:12 -07001277 raise ValueError("Set node should have at least one item")
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001278 with self.delimit("{", "}"):
1279 self.interleave(lambda: self.write(", "), self.traverse, node.elts)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001280
1281 def visit_Dict(self, node):
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001282 def write_key_value_pair(k, v):
1283 self.traverse(k)
1284 self.write(": ")
1285 self.traverse(v)
1286
1287 def write_item(item):
1288 k, v = item
1289 if k is None:
1290 # for dictionary unpacking operator in dicts {**{'y': 2}}
1291 # see PEP 448 for details
1292 self.write("**")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001293 self.set_precedence(_Precedence.EXPR, v)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001294 self.traverse(v)
1295 else:
1296 write_key_value_pair(k, v)
1297
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001298 with self.delimit("{", "}"):
1299 self.interleave(
1300 lambda: self.write(", "), write_item, zip(node.keys, node.values)
1301 )
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001302
1303 def visit_Tuple(self, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001304 with self.delimit("(", ")"):
Batuhan Taşkayae7cab7f2020-03-09 23:27:03 +03001305 self.items_view(self.traverse, node.elts)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001306
1307 unop = {"Invert": "~", "Not": "not", "UAdd": "+", "USub": "-"}
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001308 unop_precedence = {
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001309 "not": _Precedence.NOT,
Batuhan Taskayace4a7532020-05-17 00:46:11 +03001310 "~": _Precedence.FACTOR,
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001311 "+": _Precedence.FACTOR,
Batuhan Taskayace4a7532020-05-17 00:46:11 +03001312 "-": _Precedence.FACTOR,
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001313 }
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001314
1315 def visit_UnaryOp(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001316 operator = self.unop[node.op.__class__.__name__]
1317 operator_precedence = self.unop_precedence[operator]
1318 with self.require_parens(operator_precedence, node):
1319 self.write(operator)
Batuhan Taskayace4a7532020-05-17 00:46:11 +03001320 # factor prefixes (+, -, ~) shouldn't be seperated
1321 # from the value they belong, (e.g: +1 instead of + 1)
1322 if operator_precedence is not _Precedence.FACTOR:
1323 self.write(" ")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001324 self.set_precedence(operator_precedence, node.operand)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001325 self.traverse(node.operand)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001326
1327 binop = {
1328 "Add": "+",
1329 "Sub": "-",
1330 "Mult": "*",
1331 "MatMult": "@",
1332 "Div": "/",
1333 "Mod": "%",
1334 "LShift": "<<",
1335 "RShift": ">>",
1336 "BitOr": "|",
1337 "BitXor": "^",
1338 "BitAnd": "&",
1339 "FloorDiv": "//",
1340 "Pow": "**",
1341 }
1342
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001343 binop_precedence = {
1344 "+": _Precedence.ARITH,
1345 "-": _Precedence.ARITH,
1346 "*": _Precedence.TERM,
1347 "@": _Precedence.TERM,
1348 "/": _Precedence.TERM,
1349 "%": _Precedence.TERM,
1350 "<<": _Precedence.SHIFT,
1351 ">>": _Precedence.SHIFT,
1352 "|": _Precedence.BOR,
1353 "^": _Precedence.BXOR,
1354 "&": _Precedence.BAND,
1355 "//": _Precedence.TERM,
1356 "**": _Precedence.POWER,
1357 }
1358
1359 binop_rassoc = frozenset(("**",))
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001360 def visit_BinOp(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001361 operator = self.binop[node.op.__class__.__name__]
1362 operator_precedence = self.binop_precedence[operator]
1363 with self.require_parens(operator_precedence, node):
1364 if operator in self.binop_rassoc:
1365 left_precedence = operator_precedence.next()
1366 right_precedence = operator_precedence
1367 else:
1368 left_precedence = operator_precedence
1369 right_precedence = operator_precedence.next()
1370
1371 self.set_precedence(left_precedence, node.left)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001372 self.traverse(node.left)
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001373 self.write(f" {operator} ")
1374 self.set_precedence(right_precedence, node.right)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001375 self.traverse(node.right)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001376
1377 cmpops = {
1378 "Eq": "==",
1379 "NotEq": "!=",
1380 "Lt": "<",
1381 "LtE": "<=",
1382 "Gt": ">",
1383 "GtE": ">=",
1384 "Is": "is",
1385 "IsNot": "is not",
1386 "In": "in",
1387 "NotIn": "not in",
1388 }
1389
1390 def visit_Compare(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001391 with self.require_parens(_Precedence.CMP, node):
1392 self.set_precedence(_Precedence.CMP.next(), node.left, *node.comparators)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001393 self.traverse(node.left)
1394 for o, e in zip(node.ops, node.comparators):
1395 self.write(" " + self.cmpops[o.__class__.__name__] + " ")
1396 self.traverse(e)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001397
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001398 boolops = {"And": "and", "Or": "or"}
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001399 boolop_precedence = {"and": _Precedence.AND, "or": _Precedence.OR}
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001400
1401 def visit_BoolOp(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001402 operator = self.boolops[node.op.__class__.__name__]
1403 operator_precedence = self.boolop_precedence[operator]
1404
1405 def increasing_level_traverse(node):
1406 nonlocal operator_precedence
1407 operator_precedence = operator_precedence.next()
1408 self.set_precedence(operator_precedence, node)
1409 self.traverse(node)
1410
1411 with self.require_parens(operator_precedence, node):
1412 s = f" {operator} "
1413 self.interleave(lambda: self.write(s), increasing_level_traverse, node.values)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001414
1415 def visit_Attribute(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001416 self.set_precedence(_Precedence.ATOM, node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001417 self.traverse(node.value)
1418 # Special case: 3.__abs__() is a syntax error, so if node.value
1419 # is an integer literal then we need to either parenthesize
1420 # it or add an extra space to get 3 .__abs__().
1421 if isinstance(node.value, Constant) and isinstance(node.value.value, int):
1422 self.write(" ")
1423 self.write(".")
1424 self.write(node.attr)
1425
1426 def visit_Call(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001427 self.set_precedence(_Precedence.ATOM, node.func)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001428 self.traverse(node.func)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001429 with self.delimit("(", ")"):
1430 comma = False
1431 for e in node.args:
1432 if comma:
1433 self.write(", ")
1434 else:
1435 comma = True
1436 self.traverse(e)
1437 for e in node.keywords:
1438 if comma:
1439 self.write(", ")
1440 else:
1441 comma = True
1442 self.traverse(e)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001443
1444 def visit_Subscript(self, node):
Batuhan Taskayac102a142020-05-18 23:48:49 +03001445 def is_simple_tuple(slice_value):
1446 # when unparsing a non-empty tuple, the parantheses can be safely
1447 # omitted if there aren't any elements that explicitly requires
1448 # parantheses (such as starred expressions).
1449 return (
1450 isinstance(slice_value, Tuple)
1451 and slice_value.elts
1452 and not any(isinstance(elt, Starred) for elt in slice_value.elts)
1453 )
1454
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001455 self.set_precedence(_Precedence.ATOM, node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001456 self.traverse(node.value)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001457 with self.delimit("[", "]"):
Batuhan Taskayac102a142020-05-18 23:48:49 +03001458 if is_simple_tuple(node.slice):
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02001459 self.items_view(self.traverse, node.slice.elts)
Serhiy Storchakac4928fc2020-03-07 17:25:32 +02001460 else:
1461 self.traverse(node.slice)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001462
1463 def visit_Starred(self, node):
1464 self.write("*")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001465 self.set_precedence(_Precedence.EXPR, node.value)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001466 self.traverse(node.value)
1467
1468 def visit_Ellipsis(self, node):
1469 self.write("...")
1470
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001471 def visit_Slice(self, node):
1472 if node.lower:
1473 self.traverse(node.lower)
1474 self.write(":")
1475 if node.upper:
1476 self.traverse(node.upper)
1477 if node.step:
1478 self.write(":")
1479 self.traverse(node.step)
1480
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001481 def visit_arg(self, node):
1482 self.write(node.arg)
1483 if node.annotation:
1484 self.write(": ")
1485 self.traverse(node.annotation)
1486
1487 def visit_arguments(self, node):
1488 first = True
1489 # normal arguments
1490 all_args = node.posonlyargs + node.args
1491 defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
1492 for index, elements in enumerate(zip(all_args, defaults), 1):
1493 a, d = elements
1494 if first:
1495 first = False
1496 else:
1497 self.write(", ")
1498 self.traverse(a)
1499 if d:
1500 self.write("=")
1501 self.traverse(d)
1502 if index == len(node.posonlyargs):
1503 self.write(", /")
1504
1505 # varargs, or bare '*' if no varargs but keyword-only arguments present
1506 if node.vararg or node.kwonlyargs:
1507 if first:
1508 first = False
1509 else:
1510 self.write(", ")
1511 self.write("*")
1512 if node.vararg:
1513 self.write(node.vararg.arg)
1514 if node.vararg.annotation:
1515 self.write(": ")
1516 self.traverse(node.vararg.annotation)
1517
1518 # keyword-only arguments
1519 if node.kwonlyargs:
1520 for a, d in zip(node.kwonlyargs, node.kw_defaults):
Batuhan Taşkayaa322f502019-12-16 15:26:58 +03001521 self.write(", ")
1522 self.traverse(a)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001523 if d:
1524 self.write("=")
1525 self.traverse(d)
1526
1527 # kwargs
1528 if node.kwarg:
1529 if first:
1530 first = False
1531 else:
1532 self.write(", ")
1533 self.write("**" + node.kwarg.arg)
1534 if node.kwarg.annotation:
1535 self.write(": ")
1536 self.traverse(node.kwarg.annotation)
1537
1538 def visit_keyword(self, node):
1539 if node.arg is None:
1540 self.write("**")
1541 else:
1542 self.write(node.arg)
1543 self.write("=")
1544 self.traverse(node.value)
1545
1546 def visit_Lambda(self, node):
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001547 with self.require_parens(_Precedence.TEST, node):
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001548 self.write("lambda ")
1549 self.traverse(node.args)
1550 self.write(": ")
Batuhan Taşkaya397b96f2020-03-01 23:12:17 +03001551 self.set_precedence(_Precedence.TEST, node.body)
Batuhan Taşkaya4b3b1222019-12-23 19:11:00 +03001552 self.traverse(node.body)
Pablo Galindo27fc3b62019-11-24 23:02:40 +00001553
1554 def visit_alias(self, node):
1555 self.write(node.name)
1556 if node.asname:
1557 self.write(" as " + node.asname)
1558
1559 def visit_withitem(self, node):
1560 self.traverse(node.context_expr)
1561 if node.optional_vars:
1562 self.write(" as ")
1563 self.traverse(node.optional_vars)
1564
1565def unparse(ast_obj):
1566 unparser = _Unparser()
1567 return unparser.visit(ast_obj)
1568
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001569
1570def main():
1571 import argparse
1572
1573 parser = argparse.ArgumentParser(prog='python -m ast')
1574 parser.add_argument('infile', type=argparse.FileType(mode='rb'), nargs='?',
1575 default='-',
1576 help='the file to parse; defaults to stdin')
1577 parser.add_argument('-m', '--mode', default='exec',
1578 choices=('exec', 'single', 'eval', 'func_type'),
1579 help='specify what kind of code must be parsed')
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001580 parser.add_argument('--no-type-comments', default=True, action='store_false',
1581 help="don't add information about type comments")
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001582 parser.add_argument('-a', '--include-attributes', action='store_true',
1583 help='include attributes such as line numbers and '
1584 'column offsets')
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001585 parser.add_argument('-i', '--indent', type=int, default=3,
1586 help='indentation of nodes (number of spaces)')
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001587 args = parser.parse_args()
1588
1589 with args.infile as infile:
1590 source = infile.read()
Batuhan Taşkaya814d6872019-12-16 21:23:27 +03001591 tree = parse(source, args.infile.name, args.mode, type_comments=args.no_type_comments)
1592 print(dump(tree, include_attributes=args.include_attributes, indent=args.indent))
Serhiy Storchaka832e8642019-09-09 23:36:13 +03001593
1594if __name__ == '__main__':
1595 main()